Repository navigation
Expand file tree
/
Copy pathhex_microphone.rs
More file actions
2316 lines (2125 loc) · 83.4 KB
/
Copy pathhex_microphone.rs
File metadata and controls
2316 lines (2125 loc) · 83.4 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::cell::UnsafeCell;
use std::io::Cursor;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
use crate::voice_filter::{DictationSpan, HexMicEngine, ModeSpec, StageSpec, VoiceFilterMode};
const HEX_MICROPHONE_NAME: &str = "Hex Microphone";
const HEX_MICROPHONE_UID: &str = "anomaly.hex.microphone";
const HEX_MICROPHONE_SINK_NAME: &str = "Hex Microphone (Internal Sink)";
const HEX_MICROPHONE_SINK_UID: &str = "anomaly.hex.microphone.sink";
const HEX_MICROPHONE_SAMPLE_RATE: u32 = 48_000;
/// Capacity of the lock-free capture-to-sink ring buffer in 48 kHz mono samples (~341 ms).
const RING_CAPACITY: usize = 16_384;
const RING_MASK: usize = RING_CAPACITY - 1;
/// Queued frames, beyond one producer burst and one consumer pull, before the
/// consumer skips ahead to bound added latency (16 ms).
const MAX_RING_LATENCY_FRAMES: usize = 768;
/// Upper bound on the producer burst the latency cap makes room for (~85 ms).
const MAX_PRODUCER_BURST_FRAMES: usize = RING_CAPACITY / 4;
/// A smaller callback closes 1/N of the gap to a feed's recorded burst, so one
/// coalesced callback widens the latency cap for about a second, not for good.
const BURST_DECAY_CALLBACKS: usize = 32;
pub fn is_hex_virtual_device_name(name: &str) -> bool {
let trimmed = name.trim();
trimmed.eq_ignore_ascii_case(HEX_MICROPHONE_NAME)
|| trimmed.eq_ignore_ascii_case(HEX_MICROPHONE_SINK_NAME)
|| trimmed.to_ascii_lowercase().starts_with("hex microphone")
}
/// Lock-free single-producer single-consumer ring buffer for real-time audio handoff.
struct HexMicRingBuffer {
buffer: [UnsafeCell<f32>; RING_CAPACITY],
write_pos: AtomicUsize,
read_pos: AtomicUsize,
underflows: AtomicU64,
overflows: AtomicU64,
/// The active feed's recent largest capture callback, in frames.
producer_burst: AtomicUsize,
}
unsafe impl Sync for HexMicRingBuffer {}
impl HexMicRingBuffer {
const fn new() -> Self {
Self {
buffer: [const { UnsafeCell::new(0.0) }; RING_CAPACITY],
write_pos: AtomicUsize::new(0),
read_pos: AtomicUsize::new(0),
underflows: AtomicU64::new(0),
overflows: AtomicU64::new(0),
producer_burst: AtomicUsize::new(0),
}
}
fn clear(&self) {
let w = self.write_pos.load(Ordering::Relaxed);
self.read_pos.store(w, Ordering::Release);
self.producer_burst.store(0, Ordering::Relaxed);
}
/// Sets the frames the latency cap leaves room for: one whole capture
/// callback. A device delivering 20 ms at a time (a 24 kHz Bluetooth
/// headset) would otherwise lose audio on every callback.
fn set_producer_burst(&self, frames: usize) {
self.producer_burst
.store(frames.min(MAX_PRODUCER_BURST_FRAMES), Ordering::Relaxed);
}
fn counters(&self) -> (u64, u64) {
(
self.underflows.load(Ordering::Relaxed),
self.overflows.load(Ordering::Relaxed),
)
}
/// Pushes samples from the producer without blocking or allocating.
fn push_slice(&self, samples: &[f32]) {
if samples.is_empty() {
return;
}
let slice = if samples.len() > RING_CAPACITY {
&samples[samples.len() - RING_CAPACITY..]
} else {
samples
};
let count = slice.len();
let write = self.write_pos.load(Ordering::Relaxed);
let read = self.read_pos.load(Ordering::Acquire);
let available = write.wrapping_sub(read);
if available + count > RING_CAPACITY {
let new_read = write.wrapping_add(count).wrapping_sub(RING_CAPACITY);
self.read_pos.store(new_read, Ordering::Release);
self.overflows.fetch_add(1, Ordering::Relaxed);
}
for (i, &sample) in slice.iter().enumerate() {
let idx = write.wrapping_add(i) & RING_MASK;
// SAFETY: Bounded by RING_CAPACITY; producer is the sole writer.
unsafe {
*self.buffer[idx].get() = sample;
}
}
self.write_pos
.store(write.wrapping_add(count), Ordering::Release);
}
/// Pulls `dst.len()` samples for the real-time consumer without blocking.
/// Zero-fills on underflow and skips ahead once more than
/// `MAX_RING_LATENCY_FRAMES` beyond one producer burst are queued.
fn pop_slice(&self, dst: &mut [f32]) -> usize {
let needed = dst.len();
if needed == 0 {
return 0;
}
let write = self.write_pos.load(Ordering::Acquire);
let mut read = self.read_pos.load(Ordering::Relaxed);
let mut available = write.wrapping_sub(read);
let burst = self.producer_burst.load(Ordering::Relaxed);
let slack = MAX_RING_LATENCY_FRAMES / 2;
let limit = MAX_RING_LATENCY_FRAMES.max(burst + slack) + needed;
if available > RING_CAPACITY {
read = write;
available = 0;
} else if available > limit {
let keep = limit - slack;
read = write.wrapping_sub(keep);
available = keep;
self.overflows.fetch_add(1, Ordering::Relaxed);
}
let to_copy = available.min(needed);
for (i, out) in dst.iter_mut().take(to_copy).enumerate() {
let idx = read.wrapping_add(i) & RING_MASK;
// SAFETY: Consumer reads within [read, write).
*out = unsafe { *self.buffer[idx].get() };
}
if to_copy < needed {
dst[to_copy..].fill(0.0);
self.underflows.fetch_add(1, Ordering::Relaxed);
}
self.read_pos
.store(read.wrapping_add(to_copy), Ordering::Release);
to_copy
}
#[cfg(test)]
fn producer_burst(&self) -> usize {
self.producer_burst.load(Ordering::Relaxed)
}
#[cfg(any(test, target_os = "linux"))]
fn queued_frames(&self) -> usize {
let write = self.write_pos.load(Ordering::Acquire);
let read = self.read_pos.load(Ordering::Acquire);
write.wrapping_sub(read).min(RING_CAPACITY)
}
#[cfg(test)]
fn underflows(&self) -> u64 {
self.underflows.load(Ordering::Relaxed)
}
}
static CAPTURE_RING: HexMicRingBuffer = HexMicRingBuffer::new();
static SINK_STREAMING: AtomicBool = AtomicBool::new(false);
static SUPERVISOR_STARTED: AtomicBool = AtomicBool::new(false);
static SERVICE_HOSTED: AtomicBool = AtomicBool::new(false);
static PENDING_ENGINE_SWAP: AtomicBool = AtomicBool::new(false);
static PENDING_ENGINE: OnceLock<Mutex<Option<HexMicEngine>>> = OnceLock::new();
// Tunable per-mode parameters for the live engine and Voice Filter pane sliders.
#[derive(Debug, Clone, PartialEq)]
pub struct TunedFilterConfig {
pub mode: VoiceFilterMode,
pub comfort_noise: bool,
pub strength: f32,
pub muffled_wall_hz: f64,
pub muffled_room_mix: f64,
pub muffled_level_db: f64,
pub quiet_level_db: f64,
pub muted_room_tone_db: f64,
pub chipmunk_semitones: f64,
pub robot_carrier_hz: f64,
pub walkie_crunch: f64,
pub underwater_depth_hz: f64,
pub far_distance_mix: f64,
}
impl Default for TunedFilterConfig {
fn default() -> Self {
Self {
mode: VoiceFilterMode::Muffled,
comfort_noise: true,
strength: 1.0,
muffled_wall_hz: 480.0,
muffled_room_mix: 0.3,
muffled_level_db: -9.0,
quiet_level_db: -24.0,
muted_room_tone_db: -68.0,
chipmunk_semitones: 7.0,
robot_carrier_hz: 70.0,
walkie_crunch: 4.0,
underwater_depth_hz: 380.0,
far_distance_mix: 0.75,
}
}
}
impl TunedFilterConfig {
pub fn build_mode_spec(&self) -> ModeSpec {
let mut spec = self.mode.spec_with_options(self.comfort_noise);
match self.mode {
VoiceFilterMode::Normal => {}
VoiceFilterMode::Muffled => {
if let Some(StageSpec::Lowpass { hz, .. }) = spec.stages.get_mut(0) {
*hz = self.muffled_wall_hz;
}
if let Some(StageSpec::Reverb { mix, .. }) = spec.stages.get_mut(2) {
*mix = self.muffled_room_mix;
}
if let Some(StageSpec::Gain { db }) = spec.stages.get_mut(3) {
*db = self.muffled_level_db;
}
}
VoiceFilterMode::Quiet => {
if let Some(StageSpec::Gain { db }) = spec.stages.get_mut(1) {
*db = self.quiet_level_db;
}
}
VoiceFilterMode::Muted => {
if let Some(StageSpec::Noise { db, .. }) = spec.stages.get_mut(1) {
*db = if self.comfort_noise {
self.muted_room_tone_db
} else {
-120.0
};
}
}
VoiceFilterMode::Chipmunk => {
if let Some(StageSpec::Pitch { semitones, .. }) = spec.stages.get_mut(0) {
*semitones = self.chipmunk_semitones;
}
}
VoiceFilterMode::Robot => {
if let Some(StageSpec::Ringmod { hz, .. }) = spec.stages.get_mut(0) {
*hz = self.robot_carrier_hz;
}
}
VoiceFilterMode::Walkie => {
if let Some(StageSpec::Drive { amount }) = spec.stages.get_mut(3) {
*amount = self.walkie_crunch;
}
}
VoiceFilterMode::Underwater => {
if let Some(StageSpec::Wobble { hz, .. }) = spec.stages.get_mut(0) {
*hz = self.underwater_depth_hz;
}
}
VoiceFilterMode::Far => {
if let Some(StageSpec::Reverb { mix, .. }) = spec.stages.get_mut(2) {
*mix = self.far_distance_mix;
}
}
}
spec
}
fn build_engine(&self) -> HexMicEngine {
let spec = self.build_mode_spec();
let mut engine = HexMicEngine::new(f64::from(HEX_MICROPHONE_SAMPLE_RATE), &spec);
engine.set_strength(f64::from(self.strength));
engine
}
}
static TUNED_CONFIG: OnceLock<Mutex<TunedFilterConfig>> = OnceLock::new();
fn tuned_config_lock() -> &'static Mutex<TunedFilterConfig> {
TUNED_CONFIG.get_or_init(|| Mutex::new(TunedFilterConfig::default()))
}
fn pending_engine_lock() -> &'static Mutex<Option<HexMicEngine>> {
PENDING_ENGINE.get_or_init(|| Mutex::new(None))
}
pub fn current_tuned_config() -> TunedFilterConfig {
tuned_config_lock()
.lock()
.map(|g| g.clone())
.unwrap_or_default()
}
pub fn update_tuned_config(mutate: impl FnOnce(&mut TunedFilterConfig)) {
let next_engine = {
let Ok(mut guard) = tuned_config_lock().lock() else {
return;
};
mutate(&mut guard);
guard.build_engine()
};
if let Ok(mut slot) = pending_engine_lock().lock() {
*slot = Some(next_engine);
PENDING_ENGINE_SWAP.store(true, Ordering::Release);
}
if DEMO_BUFFERS.get().is_some() {
schedule_demo_recompute();
}
}
pub fn sync_from_settings(mode: VoiceFilterMode, comfort_noise: bool, strength: f32) {
update_tuned_config(|cfg| {
cfg.mode = mode;
cfg.comfort_noise = comfort_noise;
cfg.strength = strength.clamp(0.0, 1.0);
});
if crate::app_settings::hex_microphone_enabled() {
ensure_service_started();
}
}
/// Whether a dictation is past its hold threshold, so the filter applies.
#[cfg(target_os = "macos")]
fn dictating() -> bool {
crate::recording_environment::intentional_recording_active()
}
#[cfg(target_os = "linux")]
fn dictating() -> bool {
DICTATIONS.load(Ordering::Acquire) > 0
}
#[cfg(target_os = "linux")]
static DICTATIONS: AtomicUsize = AtomicUsize::new(0);
/// An intentional dictation the Voice Filter applies to until dropped, where
/// no recording environment session marks one (Linux).
#[cfg(target_os = "linux")]
pub struct Dictation(());
#[cfg(target_os = "linux")]
impl Dictation {
pub fn begin() -> Self {
DICTATIONS.fetch_add(1, Ordering::AcqRel);
Self(())
}
}
#[cfg(target_os = "linux")]
impl Drop for Dictation {
fn drop(&mut self) {
DICTATIONS.fetch_sub(1, Ordering::AcqRel);
}
}
/// Fills `out` with the next Hex Microphone audio, from the sink's
/// real-time callback: adopts a retuned engine, follows the dictation, and
/// filters the microphone audio queued in the ring.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn render(engine: &mut HexMicEngine, out: &mut [f32]) {
if PENDING_ENGINE_SWAP.load(Ordering::Acquire)
&& let Ok(mut guard) = pending_engine_lock().try_lock()
{
if let Some(mut next_engine) = guard.take() {
next_engine.set_dictating(engine.is_dictating());
*engine = next_engine;
}
PENDING_ENGINE_SWAP.store(false, Ordering::Release);
}
engine.set_dictating(dictating());
CAPTURE_RING.pop_slice(out);
engine.process_in_place(out);
}
/// One microphone stream's connection to Hex Microphone. Every capture stream
/// has one, but only the dictation listener's current stream switches it on
/// (`CaptureFeedSwitch`): the ring has a single producer, and a second stream
/// on the same microphone, such as a meeting recording's, would interleave a
/// duplicate of every callback into it.
pub struct CaptureFeed {
enabled: Arc<AtomicBool>,
resampler: Option<LinearResampler>,
/// This feed's recent largest callback, decaying; zero while inactive,
/// so a newly active feed never inherits another microphone's burst.
burst: usize,
}
/// Turns one stream's `CaptureFeed` on or off from outside the audio callback.
#[derive(Clone)]
pub struct CaptureFeedSwitch(Arc<AtomicBool>);
impl CaptureFeedSwitch {
pub fn set(&self, on: bool) {
self.0.store(on, Ordering::Release);
}
#[cfg(test)]
pub fn is_on(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
/// A switched-off feed for a capture stream delivering `sample_rate` audio.
pub fn capture_feed(sample_rate: u32) -> (CaptureFeed, CaptureFeedSwitch) {
let enabled = Arc::new(AtomicBool::new(false));
let feed = CaptureFeed {
enabled: enabled.clone(),
resampler: (sample_rate != HEX_MICROPHONE_SAMPLE_RATE && sample_rate > 0)
.then(|| LinearResampler::new(sample_rate)),
burst: 0,
};
(feed, CaptureFeedSwitch(enabled))
}
impl CaptureFeed {
/// Called from the capture callback. Never blocks, never allocates.
pub fn push(&mut self, samples: &[f32]) {
let sink_active = SINK_STREAMING.load(Ordering::Relaxed);
let demo_recording = DEMO_RECORDING_ACTIVE.load(Ordering::Relaxed);
self.push_to(
sink_active.then_some(&CAPTURE_RING),
demo_recording,
samples,
);
}
fn push_to(&mut self, ring: Option<&HexMicRingBuffer>, demo: bool, samples: &[f32]) {
if samples.is_empty() || !self.enabled.load(Ordering::Acquire) || (ring.is_none() && !demo)
{
if let Some(resampler) = &mut self.resampler {
resampler.reset();
}
self.burst = 0;
return;
}
let deliver = |chunk: &[f32]| {
if let Some(ring) = ring {
ring.push_slice(chunk);
}
if demo {
append_demo_recording_samples(chunk);
}
};
let frames = match &mut self.resampler {
None => {
deliver(samples);
samples.len()
}
Some(resampler) => resampler.process(samples, deliver),
};
self.burst = if frames >= self.burst {
frames
} else {
self.burst - (self.burst - frames).div_ceil(BURST_DECAY_CALLBACKS)
};
if let Some(ring) = ring {
ring.set_producer_burst(self.burst);
}
}
}
/// Linear interpolation to 48 kHz that carries its phase and last sample
/// across callbacks, so block boundaries neither step nor gain or lose frames.
struct LinearResampler {
/// Input frames per output frame.
step: f64,
/// Next output position in input frames, relative to the current block;
/// -1 is the previous block's last sample.
position: f64,
previous: f32,
primed: bool,
}
impl LinearResampler {
fn new(sample_rate: u32) -> Self {
Self {
step: f64::from(sample_rate) / f64::from(HEX_MICROPHONE_SAMPLE_RATE),
position: 0.0,
previous: 0.0,
primed: false,
}
}
fn reset(&mut self) {
self.primed = false;
}
/// Resamples `input` in stack chunks handed to `emit`; returns the frames emitted.
fn process(&mut self, input: &[f32], mut emit: impl FnMut(&[f32])) -> usize {
let Some(&last) = input.last() else {
return 0;
};
if !self.primed {
self.previous = input[0];
self.position = -1.0;
self.primed = true;
}
let end = (input.len() - 1) as f64;
let mut chunk = [0.0_f32; 512];
let mut filled = 0;
let mut total = 0;
while self.position < end {
let floor = self.position.floor();
let frac = (self.position - floor) as f32;
let index = floor as isize;
let a = if index < 0 {
self.previous
} else {
input[index as usize]
};
let b = input[(index + 1) as usize];
chunk[filled] = a + (b - a) * frac;
filled += 1;
if filled == chunk.len() {
emit(&chunk);
total += filled;
filled = 0;
}
self.position += self.step;
}
if filled > 0 {
emit(&chunk[..filled]);
total += filled;
}
self.position -= input.len() as f64;
self.previous = last;
total
}
}
// ── Status, Bundled Driver Discovery, and Privileged Install/Uninstall ──────
const INSTALLED_DRIVER_PATH: &str = "/Library/Audio/Plug-Ins/HAL/HexMicrophone.driver";
const EXPECTED_DRIVER_BUNDLE_ID: &str = "anomaly.hex.microphone.driver";
/// Fixed AppleScript for driver installation. No user input is ever interpolated
/// into this script; `osascript` receives the verified bundled `.driver` path
/// via `argv` and quotes it with `quoted form of (item 1 of argv)`.
#[cfg(target_os = "macos")]
const INSTALL_DRIVER_APPLESCRIPT: &str = r#"on run argv
set srcPath to quoted form of (item 1 of argv)
set dstDir to "'/Library/Audio/Plug-Ins/HAL'"
set dstPath to "'/Library/Audio/Plug-Ins/HAL/HexMicrophone.driver'"
set tmpPath to "'/Library/Audio/Plug-Ins/HAL/.HexMicrophone.driver.staging'"
do shell script "/bin/mkdir -p " & dstDir & " && /bin/rm -rf " & tmpPath & " && /usr/bin/ditto " & srcPath & " " & tmpPath & " && /usr/sbin/chown -R root:wheel " & tmpPath & " && /bin/chmod -R a+rX " & tmpPath & " && /bin/rm -rf " & dstPath & " && /bin/mv " & tmpPath & " " & dstPath & " && (/bin/launchctl kickstart -k system/com.apple.audio.coreaudiod || /usr/bin/killall coreaudiod)" with administrator privileges
end run"#;
/// Fixed AppleScript for driver removal. Takes no arguments and touches only
/// `/Library/Audio/Plug-Ins/HAL/HexMicrophone.driver`.
#[cfg(target_os = "macos")]
const UNINSTALL_DRIVER_APPLESCRIPT: &str = r#"do shell script "/bin/rm -rf '/Library/Audio/Plug-Ins/HAL/HexMicrophone.driver' '/Library/Audio/Plug-Ins/HAL/.HexMicrophone.driver.staging' && (/bin/launchctl kickstart -k system/com.apple.audio.coreaudiod || /usr/bin/killall coreaudiod)" with administrator privileges"#;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DriverActionState {
Idle,
Installing,
Uninstalling,
DoneInstalled(String),
DoneUninstalled,
Cancelled,
Failed(String),
}
static DRIVER_ACTION_STATE: OnceLock<Mutex<DriverActionState>> = OnceLock::new();
fn driver_action_lock() -> &'static Mutex<DriverActionState> {
DRIVER_ACTION_STATE.get_or_init(|| Mutex::new(DriverActionState::Idle))
}
fn set_driver_action_state(state: DriverActionState) {
let mut guard = driver_action_lock()
.lock()
.unwrap_or_else(|e| e.into_inner());
*guard = state;
}
fn current_driver_action_state() -> DriverActionState {
driver_action_lock()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
fn driver_action_in_progress() -> bool {
matches!(
current_driver_action_state(),
DriverActionState::Installing | DriverActionState::Uninstalling
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HexMicrophoneStatus {
pub driver_bundle_installed: bool,
pub driver_loaded: bool,
pub installed_version: Option<String>,
pub bundled_version: String,
pub sink_streaming: bool,
pub mic_in_use: bool,
pub active_apps: Vec<String>,
pub action_state: DriverActionState,
}
impl HexMicrophoneStatus {
pub fn needs_update(&self) -> bool {
self.driver_bundle_installed
&& self.installed_version.as_deref() != Some(self.bundled_version.as_str())
}
#[cfg(test)]
pub fn is_up_to_date(&self) -> bool {
self.driver_loaded && !self.needs_update()
}
}
pub fn driver_bundle_installed() -> bool {
std::path::Path::new(INSTALLED_DRIVER_PATH).exists()
}
fn plist_string_value(plist_xml: &str, key: &str) -> Option<String> {
let needle = format!("<key>{key}</key>");
let after_key = &plist_xml[plist_xml.find(&needle)? + needle.len()..];
let start = after_key.find("<string>")? + "<string>".len();
let end = after_key[start..].find("</string>")?;
let value = after_key[start..start + end].trim();
(!value.is_empty()).then(|| value.to_string())
}
fn read_driver_bundle_version(bundle_dir: &std::path::Path) -> Option<String> {
let plist_path = bundle_dir.join("Contents/Info.plist");
let xml = std::fs::read_to_string(plist_path).ok()?;
if let Some(bundle_id) = plist_string_value(&xml, "CFBundleIdentifier")
&& bundle_id != EXPECTED_DRIVER_BUNDLE_ID
{
return None;
}
plist_string_value(&xml, "CFBundleShortVersionString")
}
fn validate_driver_bundle(bundle_dir: &std::path::Path) -> Result<String, String> {
if bundle_dir.file_name().and_then(|s| s.to_str()) != Some("HexMicrophone.driver") {
return Err("Invalid driver bundle name".into());
}
let binary = bundle_dir.join("Contents/MacOS/HexMicrophoneDriver");
if !binary.is_file() {
return Err("Driver executable is missing from bundle".into());
}
read_driver_bundle_version(bundle_dir)
.ok_or_else(|| "Driver Info.plist is missing or invalid".into())
}
fn bundled_driver_path() -> Option<PathBuf> {
let mut candidates = Vec::new();
if let Ok(exe) = std::env::current_exe()
&& let Some(contents_dir) = exe.parent().and_then(|p| p.parent())
{
candidates.push(contents_dir.join("Library/HexMicrophone.driver"));
candidates.push(contents_dir.join("Resources/HexMicrophone.driver"));
}
if let Some(home) = dirs::home_dir() {
candidates.push(home.join("Library/Caches/hex-mic/HexMicrophone.driver"));
}
candidates.push(PathBuf::from(
"/Applications/Hex.app/Contents/Library/HexMicrophone.driver",
));
candidates
.into_iter()
.find(|candidate| validate_driver_bundle(candidate).is_ok())
}
fn bundled_driver_version() -> String {
static CACHED: OnceLock<String> = OnceLock::new();
CACHED
.get_or_init(|| {
bundled_driver_path()
.and_then(|path| read_driver_bundle_version(&path))
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
})
.clone()
}
fn installed_driver_version() -> Option<String> {
read_driver_bundle_version(std::path::Path::new(INSTALLED_DRIVER_PATH))
}
#[cfg(target_os = "macos")]
fn classify_osascript_failure(stderr: &str, stdout: &str) -> DriverActionState {
let combined = format!("{stderr}\n{stdout}");
let lower = combined.to_ascii_lowercase();
if lower.contains("user canceled")
|| lower.contains("user cancelled")
|| lower.contains("(-128)")
{
return DriverActionState::Cancelled;
}
let detail = combined
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or("Authorization or Core Audio restart failed");
let cleaned = detail
.rsplit_once("execution error: ")
.map(|(_, tail)| tail)
.unwrap_or(detail);
DriverActionState::Failed(cleaned.chars().take(140).collect())
}
#[cfg(target_os = "macos")]
fn run_driver_osascript(
script: &str,
arg: Option<&std::path::Path>,
settled: impl Fn(&HexMicrophoneStatus) -> bool,
done: impl FnOnce() -> DriverActionState,
) -> DriverActionState {
let mut command = std::process::Command::new("/usr/bin/osascript");
command.arg("-e").arg(script);
if let Some(arg) = arg {
command.arg(arg);
}
match command.output() {
Ok(out) if out.status.success() => {
crate::audio::notify_audio_service_restarted();
let deadline = Instant::now() + Duration::from_secs(4);
while Instant::now() < deadline {
if settled(&status()) {
break;
}
thread::sleep(Duration::from_millis(100));
}
crate::audio::notify_audio_service_restarted();
done()
}
Ok(out) => classify_osascript_failure(
&String::from_utf8_lossy(&out.stderr),
&String::from_utf8_lossy(&out.stdout),
),
Err(error) => DriverActionState::Failed(error.to_string()),
}
}
pub fn install_driver_async() {
#[cfg(target_os = "macos")]
{
if driver_action_in_progress() {
return;
}
set_driver_action_state(DriverActionState::Installing);
let _ = thread::Builder::new()
.name("hex-mic-install".into())
.spawn(|| {
let Some(src_bundle) = bundled_driver_path() else {
set_driver_action_state(DriverActionState::Failed(
"Bundled HexMicrophone.driver was not found in Hex.app".into(),
));
return;
};
let version = match validate_driver_bundle(&src_bundle) {
Ok(v) => v,
Err(reason) => {
set_driver_action_state(DriverActionState::Failed(reason));
return;
}
};
let state = run_driver_osascript(
INSTALL_DRIVER_APPLESCRIPT,
Some(&src_bundle),
|st| st.driver_loaded,
|| {
DriverActionState::DoneInstalled(
installed_driver_version().unwrap_or(version),
)
},
);
set_driver_action_state(state);
// An installed driver turns the Voice Filter on by itself.
ensure_service_started();
});
}
}
pub fn uninstall_driver_async() {
#[cfg(target_os = "macos")]
{
if driver_action_in_progress() {
return;
}
set_driver_action_state(DriverActionState::Uninstalling);
let _ = thread::Builder::new()
.name("hex-mic-uninstall".into())
.spawn(|| {
let state = run_driver_osascript(
UNINSTALL_DRIVER_APPLESCRIPT,
None,
|st| !st.driver_bundle_installed && !st.driver_loaded,
|| DriverActionState::DoneUninstalled,
);
set_driver_action_state(state);
});
}
}
#[cfg(target_os = "macos")]
pub fn status() -> HexMicrophoneStatus {
let mic_id = macos_hal::translate_uid_to_device(HEX_MICROPHONE_UID);
let sink_id = macos_hal::translate_uid_to_device(HEX_MICROPHONE_SINK_UID);
let driver_loaded = mic_id.is_some() && sink_id.is_some();
let mic_in_use = mic_id.is_some_and(macos_hal::device_is_running_somewhere);
let my_pid = std::process::id() as i32;
let active_apps: Vec<String> = crate::microphone_activity::active_microphone_applications()
.unwrap_or_default()
.into_iter()
.filter(|proc| proc.pid != my_pid && !proc.name.eq_ignore_ascii_case("hex"))
.map(|proc| proc.name)
.collect();
HexMicrophoneStatus {
driver_bundle_installed: driver_bundle_installed(),
driver_loaded,
installed_version: installed_driver_version(),
bundled_version: bundled_driver_version(),
sink_streaming: SINK_STREAMING.load(Ordering::Acquire),
mic_in_use,
active_apps,
action_state: current_driver_action_state(),
}
}
/// Linux has no driver: Hex Microphone exists while the Voice Filter runs
/// (`pipewire_source`).
#[cfg(target_os = "linux")]
pub fn status() -> HexMicrophoneStatus {
let streaming = SINK_STREAMING.load(Ordering::Acquire);
HexMicrophoneStatus {
driver_bundle_installed: false,
driver_loaded: streaming,
installed_version: None,
bundled_version: env!("CARGO_PKG_VERSION").to_string(),
sink_streaming: streaming,
mic_in_use: false,
active_apps: Vec::new(),
action_state: current_driver_action_state(),
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn status() -> HexMicrophoneStatus {
HexMicrophoneStatus {
driver_bundle_installed: false,
driver_loaded: false,
installed_version: None,
bundled_version: env!("CARGO_PKG_VERSION").to_string(),
sink_streaming: false,
mic_in_use: false,
active_apps: Vec::new(),
action_state: DriverActionState::Idle,
}
}
/// Makes this process the Hex Microphone host, starting the sink whenever
/// the Voice Filter is on (`app_settings::hex_microphone_enabled`). Only the listener hosts it, so CLI commands that load
/// settings never start the pipeline.
pub fn host_service() {
SERVICE_HOSTED.store(true, Ordering::Release);
ensure_service_started();
}
fn ensure_service_started() {
#[cfg(any(target_os = "macos", target_os = "linux"))]
{
if !SERVICE_HOSTED.load(Ordering::Acquire) || !crate::app_settings::hex_microphone_enabled()
{
return;
}
if SUPERVISOR_STARTED.swap(true, Ordering::AcqRel) {
return;
}
#[cfg(target_os = "macos")]
let supervisor = macos_hal::run_sink_supervisor;
#[cfg(target_os = "linux")]
let supervisor = pipewire_source::run_supervisor;
let _ = thread::Builder::new()
.name("hex-mic-sink".to_string())
.spawn(supervisor);
}
}
// ── "Try it" Demo Recording & Playback (in-memory only) ──────────────────────
const DEMO_RECORD_MAX_SAMPLES: usize = (HEX_MICROPHONE_SAMPLE_RATE as usize) * 5; // 5.0 seconds
const WAVEFORM_BARS: usize = 48;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DemoSourceKind {
Example,
Recording,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DemoPlaybackTrack {
CallHears,
You,
}
#[derive(Debug, Clone)]
pub struct DemoSnapshot {
pub source: DemoSourceKind,
pub has_recording: bool,
pub is_recording: bool,
pub recording_progress: f32,
pub playing: Option<DemoPlaybackTrack>,
pub playback_progress: f32,
pub duration_ms: u32,
pub span: DictationSpan,
pub peaks_you: Vec<f32>,
pub peaks_call: Vec<f32>,
}
static DEMO_RECORDING_ACTIVE: AtomicBool = AtomicBool::new(false);
static DEMO_RECORDED_LEN: AtomicUsize = AtomicUsize::new(0);
static DEMO_PLAYBACK_GEN: AtomicU64 = AtomicU64::new(0);
static DEMO_PLAYING_TRACK: AtomicU32 = AtomicU32::new(0); // 0 = none, 1 = CallHears, 2 = You
static DEMO_PLAYBACK_PROGRESS_BITS: AtomicU32 = AtomicU32::new(0.0_f32.to_bits());
static DEMO_CLOCK_EPOCH: OnceLock<Instant> = OnceLock::new();
static DEMO_PLAYBACK_START_NS: AtomicU64 = AtomicU64::new(0);
static DEMO_PLAYBACK_DURATION_NS: AtomicU64 = AtomicU64::new(0);
static DEMO_RECORDING_START_NS: AtomicU64 = AtomicU64::new(0);
static DEMO_RECOMPUTE_RUNNING: AtomicBool = AtomicBool::new(false);
static DEMO_RECOMPUTE_DIRTY: AtomicBool = AtomicBool::new(false);
fn demo_now_ns() -> u64 {
let epoch = DEMO_CLOCK_EPOCH.get_or_init(Instant::now);
epoch.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
}
pub fn demo_is_busy() -> bool {
DEMO_RECORDING_ACTIVE.load(Ordering::Acquire) || DEMO_PLAYING_TRACK.load(Ordering::Acquire) != 0
}
pub fn demo_recompute_is_running() -> bool {
DEMO_RECOMPUTE_RUNNING.load(Ordering::Acquire) || DEMO_RECOMPUTE_DIRTY.load(Ordering::Acquire)
}
fn schedule_demo_recompute() {
DEMO_RECOMPUTE_DIRTY.store(true, Ordering::Release);
if DEMO_RECOMPUTE_RUNNING.swap(true, Ordering::AcqRel) {
return;
}
let _ = thread::Builder::new()
.name("hex-mic-demo-dsp".into())
.spawn(|| {
while DEMO_RECOMPUTE_DIRTY.swap(false, Ordering::AcqRel) {
let cfg = current_tuned_config();
let Some((source, active_samples)) = ({
let Ok(guard) = demo_buffers_lock().lock() else {
break;
};
if guard.cached_mode.as_ref() == Some(&cfg)
&& guard.cached_source == Some(guard.source)
{
None
} else {
Some((guard.source, guard.active_samples().to_vec()))
}
}) else {
continue;
};
let span = span_for_source(source, active_samples.len());
let spec = cfg.build_mode_spec();
let processed_samples = crate::voice_filter::render(
&active_samples,
f64::from(HEX_MICROPHONE_SAMPLE_RATE),
&spec,
&[span],
f64::from(cfg.strength),
);
let peaks_you = compute_peaks(&active_samples, WAVEFORM_BARS);
let peaks_call = compute_peaks(&processed_samples, WAVEFORM_BARS);
if let Ok(mut guard) = demo_buffers_lock().lock()
&& guard.source == source
{
guard.processed_samples = processed_samples;
guard.peaks_you = peaks_you;
guard.peaks_call = peaks_call;
guard.cached_mode = Some(cfg);
guard.cached_source = Some(source);
}
}
DEMO_RECOMPUTE_RUNNING.store(false, Ordering::Release);
});
}
struct DemoBuffers {