-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
1845 lines (1634 loc) · 65.9 KB
/
Program.cs
File metadata and controls
1845 lines (1634 loc) · 65.9 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
using System.Diagnostics.CodeAnalysis;
using System.Buffers;
using System.IO;
using System.Runtime.InteropServices;
using NAudio.CoreAudioApi;
using NAudio.Wave;
using SharpHook;
using SharpHook.Data;
namespace PrimeDictate;
internal sealed class GlobalHotkeyListener : IDisposable
{
private readonly IGlobalHook hook;
private readonly Func<Task> onDictationHotkeyPressedAsync;
private readonly Func<Task> onStopHotkeyPressedAsync;
private readonly Func<Task> onHistoryHotkeyPressedAsync;
private readonly object configSync = new();
private HotkeyGesture dictationHotkey;
private HotkeyGesture stopHotkey;
private HotkeyGesture historyHotkey;
public GlobalHotkeyListener(
Func<Task> onDictationHotkeyPressedAsync,
Func<Task> onStopHotkeyPressedAsync,
Func<Task> onHistoryHotkeyPressedAsync,
HotkeyGesture dictationHotkey,
HotkeyGesture stopHotkey,
HotkeyGesture historyHotkey)
{
this.onDictationHotkeyPressedAsync = onDictationHotkeyPressedAsync;
this.onStopHotkeyPressedAsync = onStopHotkeyPressedAsync;
this.onHistoryHotkeyPressedAsync = onHistoryHotkeyPressedAsync;
this.dictationHotkey = dictationHotkey;
this.stopHotkey = stopHotkey;
this.historyHotkey = historyHotkey;
this.hook = new SimpleGlobalHook(GlobalHookType.Keyboard);
this.hook.KeyPressed += this.OnKeyPressed;
}
public Task RunAsync() => this.hook.RunAsync();
public void Dispose()
{
this.hook.KeyPressed -= this.OnKeyPressed;
this.hook.Dispose();
}
private void OnKeyPressed(object? sender, KeyboardHookEventArgs args)
{
var action = this.MatchHotkey(args);
if (action is null)
{
return;
}
args.SuppressEvent = true;
_ = Task.Run(async () =>
{
try
{
await action().ConfigureAwait(false);
}
catch (Exception ex)
{
AppLog.Error($"Hotkey action failed: {ex.Message}");
}
});
}
public void UpdateHotkeys(HotkeyGesture dictationHotkey, HotkeyGesture stopHotkey, HotkeyGesture historyHotkey)
{
lock (this.configSync)
{
this.dictationHotkey = dictationHotkey;
this.stopHotkey = stopHotkey;
this.historyHotkey = historyHotkey;
}
}
private Func<Task>? MatchHotkey(KeyboardHookEventArgs args)
{
var mask = args.RawEvent.Mask;
HotkeyGesture currentDictationHotkey;
HotkeyGesture currentStopHotkey;
HotkeyGesture currentHistoryHotkey;
lock (this.configSync)
{
currentDictationHotkey = this.dictationHotkey;
currentStopHotkey = this.stopHotkey;
currentHistoryHotkey = this.historyHotkey;
}
if (Matches(args, mask, currentStopHotkey))
{
return this.onStopHotkeyPressedAsync;
}
if (Matches(args, mask, currentHistoryHotkey))
{
return this.onHistoryHotkeyPressedAsync;
}
return Matches(args, mask, currentDictationHotkey)
? this.onDictationHotkeyPressedAsync
: null;
}
private static bool Matches(KeyboardHookEventArgs args, EventMask mask, HotkeyGesture hotkey) =>
args.Data.KeyCode == hotkey.KeyCode &&
(!hotkey.Ctrl || mask.HasCtrl()) &&
(!hotkey.Shift || mask.HasShift()) &&
(!hotkey.Alt || mask.HasAlt());
}
internal sealed class DictationController : IAsyncDisposable
{
private static readonly TimeSpan LiveTranscribeInterval = TimeSpan.FromMilliseconds(1_500);
private static readonly TimeSpan LiveMinAudio = TimeSpan.FromSeconds(0.55);
private static readonly TimeSpan LivePreviewMaxAudio = TimeSpan.FromSeconds(12);
private static readonly TimeSpan MinAutoCommitRecordingDuration = TimeSpan.FromSeconds(1.5);
private static readonly TimeSpan VoiceShellTypeTargetWait = TimeSpan.FromSeconds(2);
private static readonly TimeSpan VoiceShellTypePollInterval = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan SilenceProbeInterval = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan RecentSpeechWindow = TimeSpan.FromMilliseconds(450);
private const double MinSpeechRmsThreshold = 0.0018;
private const double MaxSpeechRmsThreshold = 0.02;
private const double NoiseFloorRiseSmoothing = 0.02;
private const double NoiseFloorFallSmoothing = 0.18;
private const int MinSpeechLevelEventsBeforeAutoCommit = 3;
private readonly SemaphoreSlim toggleGate = new(initialCount: 1, maxCount: 1);
private readonly DefaultMicrophoneRecorder recorder = new();
private readonly WhisperTextInjectionPipeline textInjectionPipeline = new();
private readonly object configSync = new();
private bool exclusiveMicAccessWhileDictating;
private string? selectedInputDeviceId;
private double inputGainMultiplier;
private TimeSpan autoCommitSilenceDelay;
private bool sendEnterAfterCommit;
private bool returnToStartTargetOnCommit;
private bool enableVoiceCommands = true;
private string voiceDictationPhrase = AppSettings.DefaultVoiceDictationPhrase;
private string voiceStopPhrase = AppSettings.DefaultVoiceStopPhrase;
private string voiceHistoryPhrase = AppSettings.DefaultVoiceHistoryPhrase;
private List<VoiceShellCommand> voiceShellCommands = new();
private CancellationTokenSource? livePreviewCts;
private Task? livePreviewTask;
private Guid? activeThreadId;
private ForegroundInputTarget? activeInputTarget;
private int autoCommitRequested;
private int emergencyStopRequested;
private int voiceCommitRequested;
private int voiceStopRequested;
private int voiceHistoryRequested;
private bool enableOllamaPostProcessing;
private string ollamaEndpoint = "http://localhost:11434";
private string ollamaModel = "gemma:2b";
private OllamaMode ollamaMode = OllamaMode.Default;
private List<TranscriptReplacementRule> transcriptReplacements = new();
private long lastSpeechTicksUtc;
private int speechLevelEventsThisSession;
private double adaptiveNoiseFloorRms = MinSpeechRmsThreshold;
private double maxObservedRmsThisSession;
public event Action<bool>? RecordingStateChanged;
public event Action<bool>? ProcessingStateChanged;
public event Action<Guid>? ThreadStarted;
public event Action<Guid>? ThreadCompleted;
public event Action<Guid, string>? ThreadTranscriptUpdated;
public event Action<TranscriptCommittedEvent>? TranscriptCommitted;
public event Action<double>? AudioLevelUpdated;
public event Action? HistoryRequested;
public DictationController(
bool exclusiveMicAccessWhileDictating = false,
string? selectedInputDeviceId = null,
double inputGainMultiplier = 1.0,
TimeSpan? autoCommitSilenceDelay = null,
bool sendEnterAfterCommit = false,
bool returnToStartTargetOnCommit = false,
TranscriptionBackendKind transcriptionBackend = TranscriptionBackendKind.Whisper,
TranscriptionComputeInterface transcriptionComputeInterface = TranscriptionComputeInterface.Cpu,
string? selectedModelId = null,
string? modelPath = null,
bool enableOllamaPostProcessing = false,
string ollamaEndpoint = "http://localhost:11434",
string ollamaModel = "gemma:2b",
OllamaMode ollamaMode = OllamaMode.Default,
bool enableVoiceCommands = true,
string voiceDictationPhrase = AppSettings.DefaultVoiceDictationPhrase,
string voiceStopPhrase = AppSettings.DefaultVoiceStopPhrase,
string voiceHistoryPhrase = AppSettings.DefaultVoiceHistoryPhrase,
IReadOnlyList<VoiceShellCommand>? voiceShellCommands = null,
IReadOnlyList<TranscriptReplacementRule>? transcriptReplacements = null)
{
this.exclusiveMicAccessWhileDictating = exclusiveMicAccessWhileDictating;
this.selectedInputDeviceId = string.IsNullOrWhiteSpace(selectedInputDeviceId) ? null : selectedInputDeviceId;
this.inputGainMultiplier = NormalizeInputGain(inputGainMultiplier);
this.autoCommitSilenceDelay = NormalizeSilenceDelay(autoCommitSilenceDelay ?? TimeSpan.FromSeconds(3));
this.sendEnterAfterCommit = sendEnterAfterCommit;
this.returnToStartTargetOnCommit = returnToStartTargetOnCommit;
this.enableOllamaPostProcessing = enableOllamaPostProcessing;
this.ollamaEndpoint = ollamaEndpoint;
this.ollamaModel = ollamaModel;
this.ollamaMode = ollamaMode;
this.enableVoiceCommands = enableVoiceCommands;
this.voiceDictationPhrase = NormalizeVoiceCommandPhrase(voiceDictationPhrase);
this.voiceStopPhrase = NormalizeVoiceCommandPhrase(voiceStopPhrase);
this.voiceHistoryPhrase = NormalizeVoiceCommandPhrase(voiceHistoryPhrase);
this.ReplaceVoiceShellCommands(voiceShellCommands);
this.ReplaceTranscriptReplacementRules(transcriptReplacements);
this.textInjectionPipeline.UpdateConfiguration(
transcriptionBackend,
transcriptionComputeInterface,
selectedModelId,
modelPath);
this.recorder.UpdateInputDevice(this.selectedInputDeviceId);
this.recorder.UpdateInputGain(this.inputGainMultiplier);
this.recorder.AudioLevelUpdated += this.OnRecorderAudioLevelUpdated;
}
public bool IsRecording => this.recorder.IsRecording;
public string ActiveMicAccessModeLabel => this.recorder.ActiveShareMode switch
{
AudioClientShareMode.Exclusive => "Exclusive",
AudioClientShareMode.Shared => "Shared",
_ => "N/A"
};
public void UpdateCaptureOptions(
bool exclusiveMicAccessWhileDictating,
string? selectedInputDeviceId,
double inputGainMultiplier,
TimeSpan autoCommitSilenceDelay,
bool sendEnterAfterCommit,
bool returnToStartTargetOnCommit,
TranscriptionBackendKind transcriptionBackend,
TranscriptionComputeInterface transcriptionComputeInterface,
string? selectedModelId,
string? modelPath,
bool enableOllamaPostProcessing,
string ollamaEndpoint,
string ollamaModel,
OllamaMode ollamaMode,
bool enableVoiceCommands,
string voiceDictationPhrase,
string voiceStopPhrase,
string voiceHistoryPhrase,
IReadOnlyList<VoiceShellCommand>? voiceShellCommands = null,
IReadOnlyList<TranscriptReplacementRule>? transcriptReplacements = null)
{
lock (this.configSync)
{
this.exclusiveMicAccessWhileDictating = exclusiveMicAccessWhileDictating;
this.selectedInputDeviceId = string.IsNullOrWhiteSpace(selectedInputDeviceId) ? null : selectedInputDeviceId;
this.inputGainMultiplier = NormalizeInputGain(inputGainMultiplier);
this.autoCommitSilenceDelay = NormalizeSilenceDelay(autoCommitSilenceDelay);
this.sendEnterAfterCommit = sendEnterAfterCommit;
this.returnToStartTargetOnCommit = returnToStartTargetOnCommit;
this.enableOllamaPostProcessing = enableOllamaPostProcessing;
this.ollamaEndpoint = ollamaEndpoint;
this.ollamaModel = ollamaModel;
this.ollamaMode = ollamaMode;
this.enableVoiceCommands = enableVoiceCommands;
this.voiceDictationPhrase = NormalizeVoiceCommandPhrase(voiceDictationPhrase);
this.voiceStopPhrase = NormalizeVoiceCommandPhrase(voiceStopPhrase);
this.voiceHistoryPhrase = NormalizeVoiceCommandPhrase(voiceHistoryPhrase);
this.ReplaceVoiceShellCommands(voiceShellCommands);
this.ReplaceTranscriptReplacementRules(transcriptReplacements);
}
this.textInjectionPipeline.UpdateConfiguration(
transcriptionBackend,
transcriptionComputeInterface,
selectedModelId,
modelPath);
this.recorder.UpdateInputDevice(this.selectedInputDeviceId);
this.recorder.UpdateInputGain(this.inputGainMultiplier);
}
public async Task ToggleRecordingAsync()
{
await this.toggleGate.WaitAsync().ConfigureAwait(false);
try
{
if (!this.recorder.IsRecording)
{
bool useExclusiveMicAccess;
TimeSpan silenceDelay;
lock (this.configSync)
{
useExclusiveMicAccess = this.exclusiveMicAccessWhileDictating;
silenceDelay = this.autoCommitSilenceDelay;
}
var threadId = Guid.NewGuid();
this.activeThreadId = threadId;
this.activeInputTarget = ForegroundInputTarget.Capture();
Interlocked.Exchange(ref this.autoCommitRequested, 0);
Interlocked.Exchange(ref this.emergencyStopRequested, 0);
Interlocked.Exchange(ref this.voiceCommitRequested, 0);
Interlocked.Exchange(ref this.voiceStopRequested, 0);
Interlocked.Exchange(ref this.voiceHistoryRequested, 0);
Interlocked.Exchange(ref this.lastSpeechTicksUtc, 0);
Interlocked.Exchange(ref this.speechLevelEventsThisSession, 0);
this.adaptiveNoiseFloorRms = MinSpeechRmsThreshold;
this.maxObservedRmsThisSession = 0;
this.ThreadStarted?.Invoke(threadId);
this.recorder.Start(useExclusiveMicAccess);
this.livePreviewCts = new CancellationTokenSource();
var liveToken = this.livePreviewCts.Token;
this.livePreviewTask = Task.Run(() => this.LivePreviewLoopAsync(liveToken), CancellationToken.None);
var autoCommitLabel = silenceDelay > TimeSpan.Zero
? $"auto-commit after {silenceDelay.TotalSeconds:N0}s silence"
: "manual hotkey stop only";
AppLog.Info(
$"Recording started (live preview, {autoCommitLabel}, mic mode: {this.ActiveMicAccessModeLabel}).",
threadId);
this.RecordingStateChanged?.Invoke(true);
return;
}
await this.StopAndCommitRecordingCoreAsync("manual stop").ConfigureAwait(false);
}
finally
{
this.toggleGate.Release();
}
}
public async Task StopRecordingAsync()
{
Interlocked.Exchange(ref this.emergencyStopRequested, 1);
await this.toggleGate.WaitAsync().ConfigureAwait(false);
try
{
if (!this.recorder.IsRecording)
{
AppLog.Info("Emergency stop requested; no active recording to discard.", this.activeThreadId);
return;
}
await this.StopAndDiscardRecordingCoreAsync("emergency stop hotkey").ConfigureAwait(false);
}
finally
{
this.toggleGate.Release();
}
}
private async Task LivePreviewLoopAsync(CancellationToken cancellationToken)
{
long lastTranscribedCapturedBytes = 0;
var recordingStartedUtc = DateTime.UtcNow;
var nextTranscribeAfterUtc = DateTime.MinValue;
while (true)
{
try
{
await Task.Delay(SilenceProbeInterval, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
var nowUtc = DateTime.UtcNow;
var lastSpeechUtc = this.GetLastSpeechUtc();
var heardSpeech = lastSpeechUtc is DateTime detectedSpeechUtc &&
detectedSpeechUtc >= recordingStartedUtc;
if (heardSpeech &&
nowUtc >= nextTranscribeAfterUtc)
{
nextTranscribeAfterUtc = nowUtc + LiveTranscribeInterval;
if (this.recorder.TryGetPcm16KhzMonoSnapshot(
out var snap,
out var capturedBytes,
LivePreviewMaxAudio) &&
!snap.IsEmpty &&
snap.Duration >= LiveMinAudio &&
capturedBytes != lastTranscribedCapturedBytes)
{
try
{
var transcript = await this.textInjectionPipeline
.TranscribeAsync(snap, cancellationToken, logTranscript: false)
.ConfigureAwait(false);
lastTranscribedCapturedBytes = capturedBytes;
var commandMatch = VoiceCommandMatcher.Apply(transcript, this.GetVoiceCommandOptionsSnapshot());
if (this.activeThreadId is Guid threadId &&
(!string.IsNullOrWhiteSpace(commandMatch.CleanedText) ||
commandMatch.CommitRequested ||
commandMatch.StopRequested ||
commandMatch.HistoryRequested))
{
this.ThreadTranscriptUpdated?.Invoke(threadId, commandMatch.CleanedText);
}
if (commandMatch.HistoryRequested)
{
this.RequestHistoryFromVoiceCommand();
this.RequestStopFromVoiceCommand();
}
if (commandMatch.StopRequested)
{
this.RequestStopFromVoiceCommand();
}
if (commandMatch.CommitRequested &&
!commandMatch.StopRequested &&
!commandMatch.HistoryRequested)
{
this.RequestCommitFromVoiceCommand();
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
AppLog.Error($"Live preview transcription failed: {ex.Message}", this.activeThreadId);
}
}
}
if (!heardSpeech)
{
continue;
}
TimeSpan silenceDelay;
lock (this.configSync)
{
silenceDelay = this.autoCommitSilenceDelay;
}
if (silenceDelay <= TimeSpan.Zero ||
!this.IsAutoCommitArmed(recordingStartedUtc, nowUtc))
{
continue;
}
if (lastSpeechUtc is DateTime speechUtc && nowUtc - speechUtc >= silenceDelay)
{
this.RequestCommitAfterSilence();
continue;
}
}
}
private void RequestCommitAfterSilence()
{
if (Interlocked.Exchange(ref this.autoCommitRequested, 1) == 1)
{
return;
}
_ = Task.Run(async () =>
{
try
{
await this.CommitAfterSilenceAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
AppLog.Error($"Silence auto-commit failed: {ex.Message}", this.activeThreadId);
}
});
}
private void RequestCommitFromVoiceCommand()
{
if (Interlocked.Exchange(ref this.voiceCommitRequested, 1) == 1)
{
return;
}
_ = Task.Run(async () =>
{
await this.toggleGate.WaitAsync().ConfigureAwait(false);
try
{
if (!this.recorder.IsRecording || this.IsEmergencyStopRequested())
{
return;
}
AppLog.Info("Voice start / stop command detected.", this.activeThreadId);
await this.StopAndCommitRecordingCoreAsync("voice start / stop command").ConfigureAwait(false);
}
catch (Exception ex)
{
AppLog.Error($"Voice start / stop command failed: {ex.Message}", this.activeThreadId);
}
finally
{
this.toggleGate.Release();
}
});
}
private void RequestStopFromVoiceCommand()
{
if (Interlocked.Exchange(ref this.voiceStopRequested, 1) == 1)
{
return;
}
Interlocked.Exchange(ref this.emergencyStopRequested, 1);
_ = Task.Run(async () =>
{
await this.toggleGate.WaitAsync().ConfigureAwait(false);
try
{
if (!this.recorder.IsRecording)
{
return;
}
AppLog.Info("Voice stop command detected.", this.activeThreadId);
await this.StopAndDiscardRecordingCoreAsync("voice stop command").ConfigureAwait(false);
}
catch (Exception ex)
{
AppLog.Error($"Voice stop command failed: {ex.Message}", this.activeThreadId);
}
finally
{
this.toggleGate.Release();
}
});
}
private void RequestHistoryFromVoiceCommand()
{
if (Interlocked.Exchange(ref this.voiceHistoryRequested, 1) == 1)
{
return;
}
AppLog.Info("Voice history command detected.", this.activeThreadId);
}
private async Task CommitAfterSilenceAsync()
{
await this.toggleGate.WaitAsync().ConfigureAwait(false);
try
{
if (!this.recorder.IsRecording)
{
return;
}
var speechResumeWindow = RecentSpeechWindow + TimeSpan.FromMilliseconds(150);
if (this.GetLastSpeechUtc() is DateTime lastSpeechUtc &&
DateTime.UtcNow - lastSpeechUtc < speechResumeWindow)
{
// If speech resumed while auto-commit was queued, keep recording.
Interlocked.Exchange(ref this.autoCommitRequested, 0);
AppLog.Info("Auto-commit canceled because speech resumed.", this.activeThreadId);
return;
}
if (this.recorder.TryGetPcm16KhzMonoSnapshot(
out var recentSnapshot,
out _,
speechResumeWindow) &&
recentSnapshot is not null &&
!recentSnapshot.IsEmpty &&
ContainsLikelySpeech(recentSnapshot))
{
// If the buffered audio still contains speech, treat the silence as a false alarm.
Interlocked.Exchange(ref this.autoCommitRequested, 0);
AppLog.Info("Auto-commit canceled because buffered speech was still present.", this.activeThreadId);
return;
}
AppLog.Info("Auto-commit triggered by silence.", this.activeThreadId);
await this.StopAndCommitRecordingCoreAsync("silence auto-commit").ConfigureAwait(false);
}
finally
{
this.toggleGate.Release();
}
}
private async Task StopAndCommitRecordingCoreAsync(string reason)
{
this.livePreviewCts?.Cancel();
// Stop recording and update UI immediately so it feels responsive even if the NPU is lagging
var audio = await this.recorder.StopAsync().ConfigureAwait(false);
AppLog.Info(
$"Recording stopped ({reason}): {audio.Duration.TotalSeconds:N2}s, {audio.Pcm16KhzMono.Length:N0} bytes PCM.",
this.activeThreadId);
this.RecordingStateChanged?.Invoke(false);
this.ProcessingStateChanged?.Invoke(true);
if (this.livePreviewTask is { } liveTask)
{
try
{
await liveTask.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
AppLog.Error($"Live preview loop failed: {ex.Message}", this.activeThreadId);
}
}
this.livePreviewCts?.Dispose();
this.livePreviewCts = null;
this.livePreviewTask = null;
if (this.IsEmergencyStopRequested())
{
AppLog.Info("Final transcription skipped because emergency stop was requested.", this.activeThreadId);
if (this.activeThreadId is Guid canceledId)
{
this.ThreadCompleted?.Invoke(canceledId);
}
this.ProcessingStateChanged?.Invoke(false);
this.activeThreadId = null;
this.activeInputTarget = null;
return;
}
try
{
await this.HandleRecordedAudioAsync(audio, reason).ConfigureAwait(false);
if (this.activeThreadId is Guid completedId)
{
this.ThreadCompleted?.Invoke(completedId);
}
}
finally
{
this.ProcessingStateChanged?.Invoke(false);
this.activeThreadId = null;
this.activeInputTarget = null;
if (Interlocked.Exchange(ref this.voiceHistoryRequested, 0) == 1)
{
this.HistoryRequested?.Invoke();
}
}
}
private async Task StopAndDiscardRecordingCoreAsync(string reason)
{
this.livePreviewCts?.Cancel();
var audio = await this.recorder.StopAsync().ConfigureAwait(false);
AppLog.Info(
$"Recording discarded ({reason}): {audio.Duration.TotalSeconds:N2}s, {audio.Pcm16KhzMono.Length:N0} bytes PCM.",
this.activeThreadId);
this.RecordingStateChanged?.Invoke(false);
if (this.livePreviewTask is { } liveTask)
{
try
{
await liveTask.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
AppLog.Error($"Live preview loop failed during discard: {ex.Message}", this.activeThreadId);
}
}
this.livePreviewCts?.Dispose();
this.livePreviewCts = null;
this.livePreviewTask = null;
if (this.activeThreadId is Guid completedId)
{
this.ThreadCompleted?.Invoke(completedId);
}
this.ProcessingStateChanged?.Invoke(false);
this.activeThreadId = null;
this.activeInputTarget = null;
if (Interlocked.Exchange(ref this.voiceHistoryRequested, 0) == 1)
{
this.HistoryRequested?.Invoke();
}
}
public async ValueTask DisposeAsync()
{
await this.toggleGate.WaitAsync().ConfigureAwait(false);
try
{
try
{
if (this.recorder.IsRecording)
{
this.livePreviewCts?.Cancel();
if (this.livePreviewTask is { } liveTask)
{
try
{
await liveTask.ConfigureAwait(false);
}
catch
{
}
}
this.livePreviewCts?.Dispose();
this.livePreviewCts = null;
this.livePreviewTask = null;
_ = await this.recorder.StopAsync().ConfigureAwait(false);
this.RecordingStateChanged?.Invoke(false);
this.ProcessingStateChanged?.Invoke(false);
}
this.recorder.AudioLevelUpdated -= this.OnRecorderAudioLevelUpdated;
this.recorder.Dispose();
}
finally
{
await this.textInjectionPipeline.DisposeAsync().ConfigureAwait(false);
}
}
finally
{
this.toggleGate.Release();
this.toggleGate.Dispose();
}
}
private async Task HandleRecordedAudioAsync(PcmAudioBuffer audio, string stopReason)
{
if (audio.IsEmpty)
{
AppLog.Info("No audio captured.", this.activeThreadId);
return;
}
if (!this.HasRecordedSpeechEvidence(audio))
{
AppLog.Info(
$"No speech detected; skipped final transcription. Peak mic RMS this session: {this.maxObservedRmsThisSession:0.0000}.",
this.activeThreadId);
return;
}
if (this.IsEmergencyStopRequested())
{
AppLog.Info("Recorded audio discarded before final transcription because emergency stop was requested.", this.activeThreadId);
return;
}
var target = this.activeInputTarget;
if (target is null)
{
AppLog.Info("No foreground target snapshot captured at dictation start; text will go to current foreground app.", this.activeThreadId);
}
else
{
AppLog.Info($"Captured target: {target.DisplayName} (pid {target.ProcessId}).", this.activeThreadId);
}
AppLog.Info($"Runtime transcription config: {this.textInjectionPipeline.ConfigurationSummary}", this.activeThreadId);
string? finalTranscript = null;
string? originalTranscript = null;
string? ollamaSystemPrompt = null;
try
{
finalTranscript = await this.textInjectionPipeline.TranscribeAsync(audio, CancellationToken.None)
.ConfigureAwait(false);
finalTranscript = RemoveTrailingSilenceArtifact(finalTranscript, stopReason);
var finalCommandMatch = VoiceCommandMatcher.Apply(
finalTranscript,
this.GetVoiceCommandOptionsSnapshot(),
includeShellCommands: true);
if (finalCommandMatch.ShellCommandInvocation is { } shellCommandInvocation)
{
await this.HandleVoiceShellCommandAsync(shellCommandInvocation, audio.Duration).ConfigureAwait(false);
if (shellCommandInvocation.Command.CompletionBehavior == VoiceShellCommandCompletionBehavior.Stop ||
string.IsNullOrWhiteSpace(finalCommandMatch.CleanedText))
{
return;
}
}
finalTranscript = finalCommandMatch.CleanedText;
if (finalCommandMatch.StopRequested)
{
Interlocked.Exchange(ref this.emergencyStopRequested, 1);
AppLog.Info("Voice stop command detected in final transcript; skipped injection.", this.activeThreadId);
return;
}
if (finalCommandMatch.HistoryRequested)
{
this.RequestHistoryFromVoiceCommand();
}
if (this.IsEmergencyStopRequested())
{
AppLog.Info("Final transcript discarded because emergency stop was requested.", this.activeThreadId);
return;
}
TranscriptReplacementRule[] replacementSnapshot;
lock (this.configSync)
{
replacementSnapshot = this.transcriptReplacements.Count == 0
? Array.Empty<TranscriptReplacementRule>()
: this.transcriptReplacements.ToArray();
}
finalTranscript = TranscriptReplacement.Apply(finalTranscript, replacementSnapshot);
if (this.IsEmergencyStopRequested())
{
AppLog.Info("Final transcript discarded before preview update because emergency stop was requested.", this.activeThreadId);
return;
}
if (this.activeThreadId is Guid threadId && !string.IsNullOrWhiteSpace(finalTranscript))
{
this.ThreadTranscriptUpdated?.Invoke(threadId, finalTranscript);
}
if (string.IsNullOrWhiteSpace(finalTranscript))
{
AppLog.Info(
$"No transcript text produced. Peak mic RMS this session: {this.maxObservedRmsThisSession:0.0000}. " +
"Try increasing Input Gain or selecting a different model/backend.",
this.activeThreadId);
return;
}
bool enableOllama;
string ollamaUrl;
string ollamaMod;
OllamaMode ollamaModeSetting;
lock (this.configSync)
{
enableOllama = this.enableOllamaPostProcessing;
ollamaUrl = this.ollamaEndpoint;
ollamaMod = this.ollamaModel;
ollamaModeSetting = this.ollamaMode;
}
if (enableOllama)
{
originalTranscript = finalTranscript;
if (this.activeThreadId is Guid id)
{
this.ThreadTranscriptUpdated?.Invoke(id, "[AI is processing transcript...]");
}
var ollamaResult = await OllamaPostProcessor.ProcessTranscriptAsync(
finalTranscript,
ollamaUrl,
ollamaMod,
ollamaModeSetting,
target,
CancellationToken.None).ConfigureAwait(false);
finalTranscript = ollamaResult.ProcessedText;
ollamaSystemPrompt = ollamaResult.SystemPrompt;
if (this.IsEmergencyStopRequested())
{
AppLog.Info("Processed transcript discarded because emergency stop was requested.", this.activeThreadId);
return;
}
if (this.activeThreadId is Guid updatedId && !string.IsNullOrWhiteSpace(finalTranscript))
{
this.ThreadTranscriptUpdated?.Invoke(updatedId, finalTranscript);
}
}
bool shouldSendEnter;
bool shouldReturnToStartTarget;
lock (this.configSync)
{
shouldSendEnter = this.sendEnterAfterCommit;
shouldReturnToStartTarget = this.returnToStartTargetOnCommit;
}
if (this.IsEmergencyStopRequested())
{
AppLog.Info("Transcript injection skipped because emergency stop was requested.", this.activeThreadId);
return;
}
if (target is not null && !target.IsStillForeground())
{
if (!shouldReturnToStartTarget)
{
AppLog.Error(
$"Focused window changed before transcript typing; skipped injection for {target.DisplayName}.",
this.activeThreadId);
this.PublishTranscriptCommit(
finalTranscript,
audio.Duration,
TranscriptDeliveryStatus.SkippedFocusChanged,
target.DisplayName,
"Focused window changed before transcript typing.",
sendEnterAfterCommit: false,
originalTranscript: originalTranscript,
ollamaSystemPrompt: ollamaSystemPrompt,
targetAppName: target.ProcessName,
targetWindowTitle: target.Title);
return;
}
if (!shouldSendEnter && target.TryInjectTextDirectly(finalTranscript))
{
AppLog.Info(
$"Transcript inserted into the original target without reactivating {target.DisplayName}.",
this.activeThreadId);
this.PublishTranscriptCommit(
finalTranscript,
audio.Duration,
TranscriptDeliveryStatus.Injected,
target.DisplayName,
error: null,
sendEnterAfterCommit: false,
originalTranscript: originalTranscript,
ollamaSystemPrompt: ollamaSystemPrompt,
targetAppName: target.ProcessName,
targetWindowTitle: target.Title);
return;
}
if (!target.TryRestoreForInput())
{
AppLog.Error(
$"Focused window changed before transcript typing; could not restore original target {target.DisplayName}.",
this.activeThreadId);
this.PublishTranscriptCommit(
finalTranscript,
audio.Duration,
TranscriptDeliveryStatus.SkippedFocusChanged,
target.DisplayName,
"Focused window changed and PrimeDictate could not restore the original target.",
sendEnterAfterCommit: false,
originalTranscript: originalTranscript,
ollamaSystemPrompt: ollamaSystemPrompt,
targetAppName: target.ProcessName,
targetWindowTitle: target.Title);
return;
}
AppLog.Info(
$"Focused window changed; restored original target {target.DisplayName} for transcript typing.",
this.activeThreadId);
}
this.textInjectionPipeline.InjectTextToTarget(finalTranscript);
AppLog.Info($"Transcript typed into target ({finalTranscript.Length:N0} chars).", this.activeThreadId);
if (shouldSendEnter)
{
this.textInjectionPipeline.SendEnterToTarget();
AppLog.Info("Enter key sent after transcript commit.", this.activeThreadId);
}
this.PublishTranscriptCommit(
finalTranscript,
audio.Duration,
TranscriptDeliveryStatus.Injected,
target?.DisplayName,
error: null,
sendEnterAfterCommit: shouldSendEnter,
originalTranscript: originalTranscript,
ollamaSystemPrompt: ollamaSystemPrompt,
targetAppName: target?.ProcessName,
targetWindowTitle: target?.Title);
}
catch (Exception ex)
{
AppLog.Error($"Transcription or text injection failed: {ex.GetType().Name}: {ex.Message}", this.activeThreadId);
AppLog.Error(ex.ToString(), this.activeThreadId);
if (this.activeThreadId is Guid threadId && !string.IsNullOrWhiteSpace(finalTranscript))
{
this.TranscriptCommitted?.Invoke(new TranscriptCommittedEvent(
ThreadId: threadId,