Repository navigation
Expand file tree
/
Copy pathfeedback.rs
More file actions
1887 lines (1749 loc) · 67.7 KB
/
Copy pathfeedback.rs
File metadata and controls
1887 lines (1749 loc) · 67.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
use std::io::Cursor;
#[cfg(target_os = "macos")]
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};
use std::sync::mpsc::{self, SyncSender};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, WrapErr, eyre};
use rodio::buffer::SamplesBuffer;
use rodio::cpal::BufferSize;
use rodio::{DeviceSinkBuilder, MixerDeviceSink, Source};
use serde::{Deserialize, Serialize};
/// Auditionable key-sound styles for the onboarding typing demo.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum KeySoundStyle {
/// Dry, crisp 13 ms Apple Taptic-style micro-pulse (default).
#[default]
Taptic,
/// Whisper-quiet 28 ms felt-damped Magic Keyboard tap.
Felt,
/// Rounded 22 ms low-pitch warm droplet.
Soft,
/// Silent typing (only Hex's dictation tones play).
Silent,
}
impl KeySoundStyle {
pub const ALL: [Self; 4] = [Self::Taptic, Self::Felt, Self::Soft, Self::Silent];
pub fn name(self) -> &'static str {
match self {
Self::Taptic => "Taptic tick",
Self::Felt => "Muted felt",
Self::Soft => "Soft warm",
Self::Silent => "Silent typing",
}
}
pub fn next(self) -> Self {
match self {
Self::Taptic => Self::Felt,
Self::Felt => Self::Soft,
Self::Soft => Self::Silent,
Self::Silent => Self::Taptic,
}
}
}
/// Soft, varied tactile and motion cues for first-run onboarding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OnboardingTone {
/// One of six distinct key taps (`0..6`) in `style`.
Key(KeySoundStyle, u8),
/// Deeper stabilized space / return bar tap in `style`.
KeySpace(KeySoundStyle),
/// Soft delete / backspace tap in `style`.
KeyBackspace(KeySoundStyle),
/// Dictation shortcut keycap pressed down.
ShortcutDown,
/// Dictation shortcut keycap released.
ShortcutUp,
/// The single-hexagon mark arriving or settling.
Hexagon,
/// The Accessibility helper detaching and docking beside System Settings.
PanelEscape,
/// A permission row ticking to `Allowed`.
PermissionTick,
/// `"Almost ready"` appearing while finishing a slow model download.
AlmostReady,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Tone {
Error,
DictationStart,
DictationStop,
/// A dictation pasted at least [`DONE_MIN_AFTER_STOP`] after its stop
/// sound, such as after a slow rewrite.
DictationDone,
Cancel,
/// The first-run tour reached its last step.
OnboardingSuccess,
/// A first-run onboarding cue (typing clacks, shortcut keycap, motion landings).
Onboarding(OnboardingTone),
/// A Scrawl capture started recording.
#[cfg(hex_capture)]
CaptureStart,
/// It stopped and is being written.
#[cfg(hex_capture)]
CaptureStop,
/// Its auto-send went, once Undo ran out.
#[cfg(hex_capture)]
CaptureSent,
/// A send was taken back, or a recording cancelled.
#[cfg(hex_capture)]
CaptureUndo,
#[cfg(hex_capture)]
CaptureFailed,
}
/// A request to the playback worker. The start tone of a shortcut press is
/// provisional: the press may still become a chord or short tap, which
/// retracts it before or while it sounds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Request {
Play(Tone),
Audition(SoundSet, Audition),
StopAudition,
ProvisionalStart,
RetractStart,
Prepare,
}
static DICTATION_PLAYER: OnceLock<SyncSender<Request>> = OnceLock::new();
static LOADER_STARTED: AtomicBool = AtomicBool::new(false);
static ENABLED: AtomicBool = AtomicBool::new(true);
static VOLUME: AtomicU32 = AtomicU32::new(0.5_f32.to_bits());
pub fn set_enabled(enabled: bool) {
ENABLED.store(enabled, Ordering::Relaxed);
}
pub fn set_volume(volume: f32) {
VOLUME.store(volume.clamp(0.0, 1.0).to_bits(), Ordering::Relaxed);
}
fn volume() -> f32 {
f32::from_bits(VOLUME.load(Ordering::Relaxed))
}
fn sounds_enabled() -> bool {
ENABLED.load(Ordering::Relaxed) && volume() > 0.0
}
/// How long the output device stays open after the last tone finishes. Holding
/// the default output open keeps macOS from idle-sleeping, so an idle app must
/// release it. A tone implies recent user activity, so a grace shorter than any
/// idle-sleep timer costs nothing while sparing bursts of dictation the cold
/// device reopen.
const IDLE_RELEASE_GRACE: Duration = Duration::from_secs(5 * 60);
const OPEN_RETRY_BACKOFF: Duration = Duration::from_secs(2);
// Only the playback worker owns a device. It opens lazily for a tone, stays
// open through the idle grace, and drops within one observation interval once
// sounds turn off or the grace expires. Opening never blocks capture or UI.
struct FeedbackOutput<S> {
sink: Option<S>,
retry_at: Instant,
playing_until: Option<Instant>,
/// The output route generation the device was opened (or last tried)
/// under. A newer one means the default output changed or disappeared.
route: u64,
}
impl<S> FeedbackOutput<S> {
fn new() -> Self {
Self {
sink: None,
retry_at: Instant::now(),
playing_until: None,
route: 0,
}
}
/// Opens the device for a tone unless a recent failure is still backing off.
/// An output opened under an older `route` is dropped and the current
/// default opens at once, without the failure backoff, so tones follow a
/// default output that changed or went away instead of feeding a dead one.
fn open_for_tone(
&mut self,
now: Instant,
route: u64,
open: impl FnOnce() -> Result<S>,
) -> Result<()> {
if self.route != route {
self.route = route;
if self.sink.take().is_some() {
tracing::debug!("default output changed; reopening feedback output");
}
self.retry_at = now;
}
if self.sink.is_none() && now >= self.retry_at {
self.retry_at = now + OPEN_RETRY_BACKOFF;
self.sink = Some(open()?);
}
Ok(())
}
fn mark_playing(&mut self, now: Instant, duration: Duration) {
let until = now + duration;
self.playing_until = Some(self.playing_until.unwrap_or(until).max(until));
}
/// Releases the device when sounds are off or nothing has played within the
/// idle grace. A released device reopens immediately for the next tone.
fn release_when_idle(&mut self, enabled: bool, now: Instant) {
let idle = self
.playing_until
.is_none_or(|until| now >= until + IDLE_RELEASE_GRACE);
if !enabled || idle {
self.playing_until = None;
if self.sink.take().is_some() {
self.retry_at = now;
}
}
}
}
/// Maps the admission wait outcome to an error. A timeout does not stop the
/// loader thread: the audio stack may simply be cold, and the loader keeps
/// running so tones recover once the default output finally opens.
fn admission_error(outcome: Result<Result<()>, mpsc::RecvTimeoutError>) -> Result<()> {
match outcome {
Ok(Ok(())) => Ok(()),
Ok(Err(error)) => Err(error),
Err(mpsc::RecvTimeoutError::Timeout) => Err(eyre!("timed out preloading feedback audio")),
Err(mpsc::RecvTimeoutError::Disconnected) => {
Err(eyre!("feedback audio loader exited before initializing"))
}
}
}
fn publish_player(
player: &OnceLock<SyncSender<Request>>,
sender: SyncSender<Request>,
ready: SyncSender<Result<()>>,
outcome: Result<()>,
) {
let _ = player.set(sender);
let _ = ready.send(outcome);
}
pub fn preload() -> Result<()> {
if DICTATION_PLAYER.get().is_some() {
return Ok(());
}
if LOADER_STARTED.swap(true, Ordering::AcqRel) {
// A loader is already running from an earlier admission; it registers
// the player itself, so report the same slow-audio outcome.
return Err(eyre!("feedback audio is still initializing"));
}
let (sender, receiver) = mpsc::sync_channel::<Request>(32);
let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
thread::spawn(move || {
let sounds = match Sounds::load() {
Ok(sounds) => sounds,
Err(error) => {
let _ = ready_sender.send(Err(error));
LOADER_STARTED.store(false, Ordering::Release);
return;
}
};
let mut output = FeedbackOutput::new();
// The device opens for the first tone, not at startup, so an idle app
// holds no output stream. Publish before any tone arrives.
publish_player(&DICTATION_PLAYER, sender, ready_sender, Ok(()));
let mut start_tone = ProvisionalStart::default();
let mut audition = Auditioning::default();
loop {
let timeout = start_tone.wait(Instant::now(), OBSERVATION_INTERVAL);
let request = match receiver.recv_timeout(timeout) {
Ok(request) => Some(request),
Err(mpsc::RecvTimeoutError::Timeout) => None,
Err(mpsc::RecvTimeoutError::Disconnected) => break,
};
let received_at = Instant::now();
let timed_out = request.is_none();
let enabled = sounds_enabled();
output.release_when_idle(enabled, received_at);
if !enabled {
start_tone.retract();
audition.stop();
continue;
}
let tone = match request {
Some(Request::Play(tone)) => {
if tone == Tone::DictationStart {
start_tone.cancel_pending();
}
Some(tone)
}
Some(Request::ProvisionalStart) => {
start_tone.request(received_at);
// Opening during the chord grace keeps a cold device off
// the path to the audible tone.
output.prepare(received_at);
None
}
Some(Request::RetractStart) => {
start_tone.retract();
None
}
Some(Request::Prepare) => {
output.prepare(received_at);
None
}
Some(Request::Audition(set, what)) => {
audition.stop();
let stopped = audition.begin();
for (sound, at, cue) in sounds.audition(set, what) {
let (sound, _) = Retractable::with_flag(sound.delay(at), stopped.clone());
output.play(sound, (set, cue));
}
#[cfg(target_os = "macos")]
if what == Audition::Cue(Cue::Error) && !set.has_own_error() {
audition.system = spawn_system_sound("Basso");
}
None
}
Some(Request::StopAudition) => {
audition.stop();
None
}
None => None,
};
if let Some(tone) = tone {
if let Some(sound) = sounds.get(sound_set(), tone) {
output.play(sound.clone(), tone);
}
} else if timed_out && start_tone.is_due(Instant::now()) {
// Only an empty queue reaches here, so a retraction sent while
// the device opened always wins over the tone.
let start = sounds.set(sound_set()).start.clone();
let (sound, retracted) = Retractable::new(start);
if output.play(sound, Tone::DictationStart) {
start_tone.sounding(retracted);
} else {
start_tone.retract();
}
}
}
});
let outcome = ready_receiver.recv_timeout(Duration::from_secs(2));
admission_error(outcome)?;
Ok(())
}
/// The least time between the stop sound and a paste for the done sound to
/// play. A dictation that pastes at once is already over when stop sounds.
pub const DONE_MIN_AFTER_STOP: Duration = Duration::from_secs(2);
static LAST_STOP: Mutex<Option<Instant>> = Mutex::new(None);
/// Whether a done sound asked for now follows a stop sound by
/// [`DONE_MIN_AFTER_STOP`]; without a stop sound there is nothing to follow.
fn done_is_late(stopped: Option<Instant>, now: Instant) -> bool {
stopped.is_none_or(|at| now.saturating_duration_since(at) >= DONE_MIN_AFTER_STOP)
}
pub fn play(tone: Tone) {
if !sounds_enabled() {
return;
}
match tone {
Tone::DictationStop => {
*LAST_STOP.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
}
Tone::DictationDone => {
let stopped = *LAST_STOP.lock().unwrap_or_else(|e| e.into_inner());
if !done_is_late(stopped, Instant::now()) {
return;
}
}
_ => {}
}
match tone {
#[cfg(target_os = "macos")]
Tone::Error if !sound_set().has_own_error() => play_system_sound(tone),
_ => enqueue(DICTATION_PLAYER.get(), Request::Play(tone)),
}
}
/// A set of feedback sounds, chosen in Settings. Every set has its own start,
/// stop and cancel, and all are level-matched, so a volume sounds the same in
/// each. `scripts/sounds/synth.py` makes their files.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[repr(u8)]
pub enum SoundSet {
/// One kalimba-like voice playing one motif across a dictation.
Signature = 0,
/// The sounds Hex played before the signature set. It has no done tone,
/// and errors play macOS Basso as they did.
#[default]
Classic = 1,
Click = 2,
Soft = 3,
Wood = 4,
Analog = 5,
/// The team vote's winner (2026-10): one mechanical key's thock.
Thock = 6,
}
impl SoundSet {
/// In the order Settings lists them.
pub const ALL: [Self; 7] = [
Self::Signature,
Self::Classic,
Self::Click,
Self::Soft,
Self::Wood,
Self::Analog,
Self::Thock,
];
/// The English name Settings shows, translated where it is shown.
pub fn name(self) -> &'static str {
match self {
Self::Signature => "Hex signature",
Self::Classic => "Classic",
Self::Click => "Click",
Self::Soft => "Soft tone",
Self::Wood => "Wood",
Self::Analog => "Warm synth",
Self::Thock => "Thock",
}
}
/// What the set sounds like, in a few words, as the sound picker lists it.
pub fn character(self) -> &'static str {
match self {
Self::Signature => "A kalimba motif that rises and comes home",
Self::Classic => "The tones Hex first shipped with",
Self::Click => "Mechanical key clicks",
Self::Soft => "Warm, rounded blips",
Self::Wood => "Soft marimba and hollow wood blocks",
Self::Analog => "A mellow analogue synth",
Self::Thock => "A deep, creamy keyboard key",
}
}
/// Whether the set plays a sound for `cue`. Classic and Thock have no done
/// sound; Classic's error is macOS Basso, or Signature's elsewhere.
pub fn has(self, cue: Cue) -> bool {
cue != Cue::Done || BUNDLED_SETS[self as usize].done.is_some()
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn has_own_error(self) -> bool {
BUNDLED_SETS[self as usize].error.is_some()
}
fn decode(value: u8) -> Self {
Self::ALL
.get(usize::from(value))
.copied()
.unwrap_or_default()
}
}
/// A moment of dictation that has its own sound, as the sound picker plays
/// them one at a time.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Cue {
Start,
Stop,
Done,
Cancel,
Error,
}
impl Cue {
pub const ALL: [Self; 5] = [
Self::Start,
Self::Stop,
Self::Done,
Self::Cancel,
Self::Error,
];
/// The English label the sound picker shows, translated where shown.
pub fn name(self) -> &'static str {
match self {
Self::Start => "Start",
Self::Stop => "Stop",
Self::Done => "Done",
Self::Cancel => "Cancel",
Self::Error => "Error",
}
}
}
/// What the sound picker plays of a set.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Audition {
/// A short dictation: start, a moment of speaking, stop, a moment of
/// transcribing, then done.
Dictation,
Cue(Cue),
}
/// When a dictation audition plays each sound, from its start.
const DICTATION_CUES: [(Cue, Duration); 3] = [
(Cue::Start, Duration::ZERO),
(Cue::Stop, Duration::from_millis(1_400)),
(Cue::Done, Duration::from_millis(2_100)),
];
impl Audition {
/// Each cue it plays and when, from its start. A cue the set has no
/// sound for keeps its moment and plays nothing.
pub fn cues(self) -> &'static [(Cue, Duration)] {
match self {
Self::Dictation => &DICTATION_CUES,
Self::Cue(Cue::Start) => &[(Cue::Start, Duration::ZERO)],
Self::Cue(Cue::Stop) => &[(Cue::Stop, Duration::ZERO)],
Self::Cue(Cue::Done) => &[(Cue::Done, Duration::ZERO)],
Self::Cue(Cue::Cancel) => &[(Cue::Cancel, Duration::ZERO)],
Self::Cue(Cue::Error) => &[(Cue::Error, Duration::ZERO)],
}
}
/// How long its moments show, past its last sound.
pub fn length(self) -> Duration {
match self {
Self::Dictation => Duration::from_millis(2_900),
Self::Cue(_) => Duration::from_millis(900),
}
}
}
static SOUND_SET: AtomicU8 = AtomicU8::new(SoundSet::Classic as u8);
pub fn set_sound_set(set: SoundSet) {
SOUND_SET.store(set as u8, Ordering::Relaxed);
}
fn sound_set() -> SoundSet {
SoundSet::decode(SOUND_SET.load(Ordering::Relaxed))
}
/// Plays `what` of `set` at the current volume, so the sound picker can be
/// heard. It ends the audition still sounding, if any.
pub fn audition(set: SoundSet, what: Audition) {
if sounds_enabled() {
enqueue(DICTATION_PLAYER.get(), Request::Audition(set, what));
}
}
/// Ends the audition still sounding, fading it out over [`RETRACT_FADE`].
pub fn stop_audition() {
enqueue(DICTATION_PLAYER.get(), Request::StopAudition);
}
/// The worker's view of the audition sounding, if any.
#[derive(Default)]
struct Auditioning {
stopped: Option<Arc<AtomicBool>>,
/// Basso, for Classic's error.
#[cfg(target_os = "macos")]
system: Option<std::process::Child>,
}
impl Auditioning {
/// The flag that stops the audition beginning now.
fn begin(&mut self) -> Arc<AtomicBool> {
self.stopped
.insert(Arc::new(AtomicBool::new(false)))
.clone()
}
fn stop(&mut self) {
if let Some(stopped) = self.stopped.take() {
stopped.store(true, Ordering::Release);
}
#[cfg(target_os = "macos")]
if let Some(mut child) = self.system.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
/// One set's bundled files, in `resources/audio/sounds/<set>/`. A missing
/// done tone stays silent, a missing error (macOS only) plays Basso, and a missing
/// success plays the set's own stop sound.
struct BundledSet {
start: &'static [u8],
stop: &'static [u8],
done: Option<&'static [u8]>,
cancel: &'static [u8],
error: Option<&'static [u8]>,
success: Option<&'static [u8]>,
}
macro_rules! bundled_sound {
($set:literal, $name:literal) => {
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/resources/audio/sounds/",
$set,
"/",
$name,
".wav"
))
.as_slice()
};
}
/// A set `synth.py` makes whole.
macro_rules! synthesized_set {
($set:literal) => {
BundledSet {
start: bundled_sound!($set, "start"),
stop: bundled_sound!($set, "stop"),
done: Some(bundled_sound!($set, "done")),
cancel: bundled_sound!($set, "cancel"),
error: Some(bundled_sound!($set, "error")),
success: Some(bundled_sound!($set, "success")),
}
};
}
/// In [`SoundSet::ALL`]'s order.
const BUNDLED_SETS: [BundledSet; 7] = [
synthesized_set!("signature"),
BundledSet {
start: bundled_sound!("classic", "start"),
stop: bundled_sound!("classic", "stop"),
done: None,
cancel: bundled_sound!("classic", "cancel"),
// macOS plays Basso; elsewhere Classic borrows Signature's error.
error: if cfg!(target_os = "macos") {
None
} else {
Some(bundled_sound!("signature", "error"))
},
success: None,
},
synthesized_set!("click"),
synthesized_set!("soft"),
synthesized_set!("wood"),
synthesized_set!("analog"),
// No done sound: the stop already says it (Kit, 2026-10-30).
BundledSet {
start: bundled_sound!("thock", "start"),
stop: bundled_sound!("thock", "stop"),
done: None,
cancel: bundled_sound!("thock", "cancel"),
error: Some(bundled_sound!("thock", "error")),
success: Some(bundled_sound!("thock", "success")),
},
];
/// One set, decoded.
struct SetSounds {
start: SamplesBuffer,
stop: SamplesBuffer,
done: Option<SamplesBuffer>,
cancel: SamplesBuffer,
/// Played for failures; `None` plays macOS Basso.
error: Option<SamplesBuffer>,
success: Option<SamplesBuffer>,
}
impl SetSounds {
fn load(bundled: &BundledSet) -> Result<Self> {
let optional = |bytes: Option<&'static [u8]>| bytes.map(decode_wav).transpose();
Ok(Self {
start: decode_wav(bundled.start)?,
stop: decode_wav(bundled.stop)?,
done: optional(bundled.done)?,
cancel: decode_wav(bundled.cancel)?,
error: optional(bundled.error)?,
success: optional(bundled.success)?,
})
}
}
/// Decoded onboarding cues (`resources/audio/sounds/onboarding/`).
struct OnboardingSounds {
felt_keys: [SamplesBuffer; 6],
felt_space: SamplesBuffer,
felt_backspace: SamplesBuffer,
taptic_keys: [SamplesBuffer; 6],
taptic_space: SamplesBuffer,
soft_keys: [SamplesBuffer; 6],
soft_space: SamplesBuffer,
shortcut_down: SamplesBuffer,
shortcut_up: SamplesBuffer,
hexagon: SamplesBuffer,
panel_escape: SamplesBuffer,
permission_tick: SamplesBuffer,
almost_ready: SamplesBuffer,
}
impl OnboardingSounds {
fn load() -> Result<Self> {
Ok(Self {
felt_keys: [
decode_wav(bundled_sound!("onboarding", "key_1"))?,
decode_wav(bundled_sound!("onboarding", "key_2"))?,
decode_wav(bundled_sound!("onboarding", "key_3"))?,
decode_wav(bundled_sound!("onboarding", "key_4"))?,
decode_wav(bundled_sound!("onboarding", "key_5"))?,
decode_wav(bundled_sound!("onboarding", "key_6"))?,
],
felt_space: decode_wav(bundled_sound!("onboarding", "key_space"))?,
felt_backspace: decode_wav(bundled_sound!("onboarding", "key_backspace"))?,
taptic_keys: [
decode_wav(bundled_sound!("onboarding", "taptic_1"))?,
decode_wav(bundled_sound!("onboarding", "taptic_2"))?,
decode_wav(bundled_sound!("onboarding", "taptic_3"))?,
decode_wav(bundled_sound!("onboarding", "taptic_4"))?,
decode_wav(bundled_sound!("onboarding", "taptic_5"))?,
decode_wav(bundled_sound!("onboarding", "taptic_6"))?,
],
taptic_space: decode_wav(bundled_sound!("onboarding", "taptic_space"))?,
soft_keys: [
decode_wav(bundled_sound!("onboarding", "soft_key_1"))?,
decode_wav(bundled_sound!("onboarding", "soft_key_2"))?,
decode_wav(bundled_sound!("onboarding", "soft_key_3"))?,
decode_wav(bundled_sound!("onboarding", "soft_key_4"))?,
decode_wav(bundled_sound!("onboarding", "soft_key_5"))?,
decode_wav(bundled_sound!("onboarding", "soft_key_6"))?,
],
soft_space: decode_wav(bundled_sound!("onboarding", "soft_key_space"))?,
shortcut_down: decode_wav(bundled_sound!("onboarding", "shortcut_down"))?,
shortcut_up: decode_wav(bundled_sound!("onboarding", "shortcut_up"))?,
hexagon: decode_wav(bundled_sound!("onboarding", "hexagon"))?,
panel_escape: decode_wav(bundled_sound!("onboarding", "panel_escape"))?,
permission_tick: decode_wav(bundled_sound!("onboarding", "permission_tick"))?,
almost_ready: decode_wav(bundled_sound!("onboarding", "almost_ready"))?,
})
}
fn get(&self, cue: OnboardingTone) -> Option<&SamplesBuffer> {
Some(match cue {
OnboardingTone::Key(KeySoundStyle::Silent, _)
| OnboardingTone::KeySpace(KeySoundStyle::Silent)
| OnboardingTone::KeyBackspace(KeySoundStyle::Silent) => return None,
OnboardingTone::Key(KeySoundStyle::Felt, i) => {
&self.felt_keys[usize::from(i) % self.felt_keys.len()]
}
OnboardingTone::Key(KeySoundStyle::Taptic, i) => {
&self.taptic_keys[usize::from(i) % self.taptic_keys.len()]
}
OnboardingTone::Key(KeySoundStyle::Soft, i) => {
&self.soft_keys[usize::from(i) % self.soft_keys.len()]
}
OnboardingTone::KeySpace(KeySoundStyle::Felt) => &self.felt_space,
OnboardingTone::KeySpace(KeySoundStyle::Taptic) => &self.taptic_space,
OnboardingTone::KeySpace(KeySoundStyle::Soft) => &self.soft_space,
OnboardingTone::KeyBackspace(KeySoundStyle::Felt) => &self.felt_backspace,
OnboardingTone::KeyBackspace(KeySoundStyle::Taptic) => &self.taptic_keys[3],
OnboardingTone::KeyBackspace(KeySoundStyle::Soft) => &self.soft_keys[3],
OnboardingTone::ShortcutDown => &self.shortcut_down,
OnboardingTone::ShortcutUp => &self.shortcut_up,
OnboardingTone::Hexagon => &self.hexagon,
OnboardingTone::PanelEscape => &self.panel_escape,
OnboardingTone::PermissionTick => &self.permission_tick,
OnboardingTone::AlmostReady => &self.almost_ready,
})
}
}
/// The decoded sounds the playback worker plays, every set at once so a new
/// choice plays at once.
struct Sounds {
/// In [`SoundSet::ALL`]'s order.
sets: Vec<SetSounds>,
onboarding: OnboardingSounds,
#[cfg(hex_capture)]
capture: [SamplesBuffer; 5],
}
impl Sounds {
fn load() -> Result<Self> {
Ok(Self {
sets: BUNDLED_SETS
.iter()
.map(SetSounds::load)
.collect::<Result<_>>()?,
onboarding: OnboardingSounds::load()?,
#[cfg(hex_capture)]
capture: capture_sounds()?,
})
}
fn set(&self, set: SoundSet) -> &SetSounds {
&self.sets[set as usize]
}
/// The sounds `what` plays of `set`, each with when it starts. Classic's
/// error is macOS Basso, which the worker plays itself.
fn audition(&self, set: SoundSet, what: Audition) -> Vec<(SamplesBuffer, Duration, Cue)> {
let sounds = self.set(set);
what.cues()
.iter()
.filter_map(|&(cue, at)| {
let sound = match cue {
Cue::Start => Some(&sounds.start),
Cue::Stop => Some(&sounds.stop),
Cue::Done => sounds.done.as_ref(),
Cue::Cancel => Some(&sounds.cancel),
Cue::Error => sounds.error.as_ref(),
};
sound.map(|sound| (sound.clone(), at, cue))
})
.collect()
}
/// `tone` in `set`, or `None` when it plays nothing (or a system sound).
fn get(&self, set: SoundSet, tone: Tone) -> Option<&SamplesBuffer> {
let sounds = self.set(set);
Some(match tone {
Tone::DictationStart => &sounds.start,
Tone::DictationStop => &sounds.stop,
Tone::DictationDone => return sounds.done.as_ref(),
Tone::Cancel => &sounds.cancel,
Tone::OnboardingSuccess => {
return sounds.success.as_ref().or(Some(&sounds.stop));
}
Tone::Onboarding(cue) => return self.onboarding.get(cue),
Tone::Error => return sounds.error.as_ref(),
#[cfg(hex_capture)]
Tone::CaptureStart => &self.capture[0],
#[cfg(hex_capture)]
Tone::CaptureStop => &self.capture[1],
#[cfg(hex_capture)]
Tone::CaptureSent => &self.capture[2],
#[cfg(hex_capture)]
Tone::CaptureUndo => &self.capture[3],
#[cfg(hex_capture)]
Tone::CaptureFailed => &self.capture[4],
})
}
}
/// The capture tones, in [`Tone`]'s order: start, stop, sent, undo, failed.
#[cfg(hex_capture)]
fn capture_sounds() -> Result<[SamplesBuffer; 5]> {
macro_rules! sound {
($name:literal) => {
decode(include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/resources/audio/",
$name
)))?
};
}
Ok([
sound!("captureStart.mp3"),
sound!("captureStop.mp3"),
sound!("captureSent.mp3"),
sound!("captureUndo.mp3"),
sound!("captureFailed.mp3"),
])
}
/// Plays the start tone for a shortcut press that may still become a chord or
/// short tap. It sounds after [`CHORD_GRACE`] unless [`retract_start`] arrives
/// first, so modifiers pressed together for another shortcut stay silent.
pub fn play_provisional_start() {
if sounds_enabled() {
enqueue(DICTATION_PLAYER.get(), Request::ProvisionalStart);
}
}
/// Withdraws a provisional start tone: drops it before it sounds, or fades it
/// out over [`RETRACT_FADE`]. Has no effect on a tone that already finished.
pub fn retract_start() {
enqueue(DICTATION_PLAYER.get(), Request::RetractStart);
}
/// Opens the output ahead of a tone expected soon, without playing anything.
pub fn prepare() {
if sounds_enabled() {
enqueue(DICTATION_PLAYER.get(), Request::Prepare);
}
}
fn enqueue(player: Option<&SyncSender<Request>>, request: Request) {
if let Some(player) = player {
let _ = player.try_send(request);
}
}
/// How long a provisional start tone waits before sounding. Modifiers pressed
/// together for another application's shortcut arrive within this window, so
/// those chords stay silent while a deliberate press still sounds at once.
pub(crate) const CHORD_GRACE: Duration = Duration::from_millis(40);
/// How quickly a retracted start tone fades out instead of clicking off.
const RETRACT_FADE: Duration = Duration::from_millis(20);
const OBSERVATION_INTERVAL: Duration = Duration::from_millis(250);
/// The output buffer, about 10 ms at 48 kHz. Rodio's default 50 ms buffer adds
/// that much again to every tone.
const OUTPUT_BUFFER_FRAMES: u32 = 512;
/// The worker's view of the provisional start tone: due while waiting out the
/// chord grace, then retractable while it sounds.
#[derive(Default)]
struct ProvisionalStart {
due: Option<Instant>,
sounding: Option<Arc<AtomicBool>>,
}
impl ProvisionalStart {
fn request(&mut self, at: Instant) {
self.retract();
self.due = Some(at + CHORD_GRACE);
}
/// How long the worker may block before the pending tone is due.
fn wait(&self, now: Instant, observation: Duration) -> Duration {
self.due
.map_or(observation, |due| due.saturating_duration_since(now))
.min(observation)
}
fn is_due(&self, now: Instant) -> bool {
self.due.is_some_and(|due| now >= due)
}
fn sounding(&mut self, retracted: Arc<AtomicBool>) {
self.due = None;
self.sounding = Some(retracted);
}
fn cancel_pending(&mut self) {
self.due = None;
}
fn retract(&mut self) {
self.due = None;
if let Some(retracted) = self.sounding.take() {
retracted.store(true, Ordering::Release);
}
}
}
/// A sound that fades out over [`RETRACT_FADE`] once its flag is set.
struct Retractable<S> {
inner: S,
retracted: Arc<AtomicBool>,
gain: f32,
step: f32,
channel: u16,
}
impl<S: Source> Retractable<S> {
fn new(inner: S) -> (Self, Arc<AtomicBool>) {
Self::with_flag(inner, Arc::new(AtomicBool::new(false)))
}
/// Fades out once `retracted` is set, with every other sound sharing it.
fn with_flag(inner: S, retracted: Arc<AtomicBool>) -> (Self, Arc<AtomicBool>) {
let fade_frames = RETRACT_FADE.as_secs_f32() * inner.sample_rate().get() as f32;
let sound = Self {
inner,
retracted: retracted.clone(),
gain: 1.0,
step: 1.0 / fade_frames.max(1.0),
channel: 0,
};
(sound, retracted)
}
}
impl<S: Source> Iterator for Retractable<S> {
type Item = rodio::Sample;
fn next(&mut self) -> Option<Self::Item> {
let channels = self.inner.channels().get();
if self.channel == 0 && self.retracted.load(Ordering::Acquire) {
if self.gain <= 0.0 {
return None;
}
self.gain = (self.gain - self.step).max(0.0);
}
self.channel = (self.channel + 1) % channels;
self.inner.next().map(|sample| sample * self.gain)
}
}
impl<S: Source> Source for Retractable<S> {
fn current_span_len(&self) -> Option<usize> {
None
}
fn channels(&self) -> rodio::ChannelCount {
self.inner.channels()
}
fn sample_rate(&self) -> rodio::SampleRate {
self.inner.sample_rate()
}
fn total_duration(&self) -> Option<Duration> {
self.inner.total_duration()
}
}
fn open_output() -> Result<MixerDeviceSink> {
let mut sink = DeviceSinkBuilder::from_default_device()
.and_then(|builder| {
builder