Repository navigation
Expand file tree
/
Copy pathindicator.rs
More file actions
859 lines (804 loc) · 30.7 KB
/
Copy pathindicator.rs
File metadata and controls
859 lines (804 loc) · 30.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
//! The dictation HUD's lifecycle and animation, the same on every OS: the
//! event vocabulary the listener reports, the phase and job bookkeeping, and
//! Dot scope's simulation. Each step yields the dots to draw; `rune_hud`
//! draws them with `rune_hud.wgsl` through a Rune overlay.
//!
//! Time is passed in, never read, so a recorded schedule replays exactly
//! (`rune_hud`'s frame captures).
use std::collections::BTreeSet;
use std::time::{Duration, Instant};
use crate::rune_hud::dot_scope::{self, Pose, Scope, Stage, Tuning};
use crate::rune_hud::hud_placement::Island;
/// The loudness before any meter arrives, dBFS.
const SILENT: f32 = -120.0;
/// The shortest processing look: a fast transcription still shows the field
/// turning blue before done clears it.
const PROCESSING_MIN_DURATION: Duration = Duration::from_millis(200);
/// How long done shows before the HUD collapses: a third into done's
/// 0.3 s wipe, so the collapse and the wipe end together.
const COMPLETED_VISIBLE_DURATION: Duration = Duration::from_millis(100);
/// How long the notch indicator holds its checkmark before folding back,
/// as long as a system confirmation stays up.
const EARS_COMPLETED_VISIBLE_DURATION: Duration = Duration::from_millis(700);
const FAILED_VISIBLE_DURATION: Duration = Duration::from_millis(600);
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
#[derive(Clone, Debug)]
pub enum DictationIndicatorEvent {
Reset,
/// HUD Lab's or a playground story's tuning.
ConfigureDotScope(dot_scope::Tuning),
/// HUD Lab: Dot scope follows a synthetic voice instead of the meter
/// until the next `Reset`.
DemoVoice,
Started,
Meter {
average: f32,
// Dot scope follows `average`; the window's meters read
// `input_level` instead.
#[allow(dead_code)]
peak: f32,
},
Submitted {
job_id: u64,
},
Transcribing {
// `Submitted` already enters `Transcribing`; `job_id` stays on the
// event for listener parity and diagnostics.
#[allow(dead_code)]
job_id: u64,
},
Processing {
#[allow(dead_code)]
job_id: u64,
},
Discarded,
Cancelled,
JobCompleted {
job_id: u64,
},
#[cfg_attr(target_os = "macos", allow(dead_code))]
JobCancelled {
job_id: u64,
},
JobFailed {
job_id: u64,
/// Why it failed, for Labs › Failure notices; the HUD ignores it.
message: Option<String>,
},
Failed {
/// Why it failed, for Labs › Failure notices; the HUD ignores it.
message: Option<String>,
},
}
impl DictationIndicatorEvent {
/// A `Meter` event from captured samples: their RMS and absolute peak
/// around the chunk's mean, so a microphone's DC offset never reads as
/// loudness; `None` for no samples.
pub fn meter(samples: &[f32]) -> Option<Self> {
if samples.is_empty() {
return None;
}
let count = samples.len() as f32;
let mean = samples.iter().sum::<f32>() / count;
let mut sum_of_squares = 0.0;
let mut peak = 0.0_f32;
for sample in samples {
let centered = sample - mean;
sum_of_squares += centered * centered;
peak = peak.max(centered.abs());
}
Some(Self::Meter {
average: (sum_of_squares / count).sqrt(),
peak,
})
}
}
#[cfg(target_os = "macos")]
pub use macos::*;
/// macOS reports through a channel the main thread's pump drains into the
/// HUD (`rune_hud::macos`).
#[cfg(target_os = "macos")]
mod macos {
use std::sync::mpsc::{self, Receiver, Sender};
use super::DictationIndicatorEvent;
#[derive(Clone)]
pub struct DictationIndicatorSender(Sender<DictationIndicatorEvent>);
impl DictationIndicatorSender {
pub fn send(&self, event: DictationIndicatorEvent) {
if self.0.send(event).is_ok() {
// The pump idles between events; this wakes it at once.
crate::macos_rune::wake_pump();
}
}
}
pub fn channel() -> (DictationIndicatorSender, Receiver<DictationIndicatorEvent>) {
let (sender, receiver) = mpsc::channel();
(DictationIndicatorSender(sender), receiver)
}
}
/// The HUD's explicit lifecycle state: active capture, pending jobs, minimum
/// processing dwell, and terminal outcomes live in one variant so illegal
/// combinations are unrepresentable.
#[derive(Debug, Eq, PartialEq)]
enum HudState {
/// Idle and hidden; the scope may still be fading out its last look.
Hidden,
/// Actively capturing audio; earlier accepted jobs may still be running.
Recording { jobs: BTreeSet<u64> },
/// No active capture, with at least one transcription/processing job in
/// flight.
Transcribing {
jobs: BTreeSet<u64>,
working_since: Instant,
},
/// The last job completed before [`PROCESSING_MIN_DURATION`] elapsed; holds
/// the processing look until then before entering [`Self::Completed`].
Completing { working_since: Instant },
/// Showing the done look until its visible duration elapses, then hidden.
Completed { started: Instant },
/// Showing the failed look until [`FAILED_VISIBLE_DURATION`] elapses, then
/// hidden.
Failed { started: Instant },
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum JobOutcome {
Completed,
Cancelled,
Failed,
}
impl HudState {
fn take_jobs(&mut self) -> BTreeSet<u64> {
match self {
Self::Recording { jobs } | Self::Transcribing { jobs, .. } => std::mem::take(jobs),
Self::Hidden
| Self::Completing { .. }
| Self::Completed { .. }
| Self::Failed { .. } => BTreeSet::new(),
}
}
fn status(&self) -> Option<&'static str> {
match self {
Self::Recording { .. } => Some("Recording"),
Self::Transcribing { .. } | Self::Completing { .. } => Some("Transcribing"),
Self::Failed { .. } => Some("Failed"),
Self::Hidden | Self::Completed { .. } => None,
}
}
/// The look this state shows; `None` keeps the last one as it fades.
fn stage(&self) -> Option<Stage> {
match self {
Self::Recording { .. } => Some(Stage::Recording),
Self::Transcribing { .. } | Self::Completing { .. } => Some(Stage::Processing),
Self::Completed { .. } => Some(Stage::Done),
Self::Failed { .. } => Some(Stage::Failed),
Self::Hidden => None,
}
}
}
/// One Dot scope frame: the plate's pose and every dot's light.
#[derive(Clone, Debug, PartialEq)]
pub struct DotFrame {
pub pose: Pose,
pub tuning: Tuning,
pub columns: usize,
pub rows: usize,
/// (brightness, freshness) per dot, row by row, as normalized u16s.
pub dots: Vec<[u16; 2]>,
}
/// The middle of `rune_hud.wgsl`'s fade of dots near the field's edge
/// (1.4 to 4.6 pt in): a row or column nearer than this barely shows.
const FIELD_EDGE_FADE: f32 = 3.0;
/// How far in from the top and bottom the outermost row that shows sits.
fn field_edge(tuning: &Tuning) -> f32 {
let outer = (tuning.height - (tuning.rows - 1.0) * tuning.spacing) / 2.0;
if outer < FIELD_EDGE_FADE && tuning.rows > 2.0 {
outer + tuning.spacing
} else {
outer
}
}
/// The tuning that fills an island: the field as wide as the island less
/// its padding, recording and processing alike, at the same dot spacing.
/// The width snaps to whole columns, with the outer columns as far in from
/// the ends as the outermost rows that show are from the top and bottom,
/// so the island (which follows the field) is even all round. The notch
/// indicator's ears draw no field, so they leave the tuning alone.
fn fill_island(tuning: Tuning, island: Option<Island>) -> Tuning {
let Some(island) = island.filter(|island| !island.ears) else {
return tuning;
};
let pitch = tuning.spacing;
let edge = field_edge(&tuning);
let columns = tuning.columns_in(island.plate_width(), edge);
let width = (columns - 1.0) * pitch + 2.0 * edge;
Tuning {
columns,
width,
processing_width: width,
..tuning
}
}
/// The HUD's state: what the listener reported and Dot scope's simulation.
pub struct IndicatorModel {
state: HudState,
scope: Scope,
stage: Stage,
/// The tuning as set, before [`fill_island`].
tuning: Tuning,
/// The notch island the HUD sits in, if any.
island: Option<Island>,
/// The microphone's loudness, dBFS.
loudness: f32,
/// HUD Lab's synthetic voice and how far into it Dot scope is.
demo_voice: Option<f32>,
/// Since an event, until a step finds everything settled out of sight.
active: bool,
}
impl IndicatorModel {
pub fn new(tuning: Tuning, _now: Instant) -> Self {
Self {
state: HudState::Hidden,
scope: Scope::new(tuning),
stage: Stage::Recording,
tuning,
island: None,
loudness: SILENT,
demo_voice: None,
active: false,
}
}
/// Whether the HUD wants frames: from an event until a step finds it
/// settled out of sight.
pub fn active(&self) -> bool {
self.active
}
/// Whether the HUD is recording a capture: the one phase whose only events
/// are meters, so the only one a recovery re-ask may act on (#1793).
#[cfg(any(target_os = "windows", test))]
pub fn recording(&self) -> bool {
matches!(self.state, HudState::Recording { .. })
}
/// The meter's loudness, dBFS: tests check that a meter still updates it
/// when the update draws no frame of its own.
#[cfg(test)]
pub fn loudness(&self) -> f32 {
self.loudness
}
/// What the HUD says to assistive technology: Recording, Transcribing,
/// or Failed, in English (callers translate it); `None` while nothing
/// shows or the HUD fades out.
pub fn status(&self) -> Option<&'static str> {
self.state.status()
}
/// Dot scope's tuning, as set.
#[cfg(target_os = "macos")]
pub fn tuning(&self) -> Tuning {
self.tuning
}
/// Spreads the field over `room` pt from its `hold` end, as the island
/// spreads it across a notch, but at once and keeping every dot that
/// stays ([`Scope::span`]): for a field whose room follows a moving edge.
pub fn span(&mut self, room: f32, hold: dot_scope::Hold) {
self.scope.span(room, hold);
}
/// The frame as it stands, without advancing.
pub fn frame(&self) -> DotFrame {
DotFrame {
pose: self.scope.pose(),
tuning: self.scope.tuning(),
columns: self.scope.columns(),
rows: self.scope.rows(),
dots: self
.scope
.dots()
.iter()
.map(|value| value.map(|v| (v.clamp(0.0, 1.0) * 65535.0).round() as u16))
.collect(),
}
}
/// Spreads Dot scope's field across the notch island it now sits in.
#[cfg(any(target_os = "macos", test))]
pub fn set_island(&mut self, island: Option<Island>) {
if self.island != island {
self.island = island;
self.scope.tune(fill_island(self.tuning, island));
}
}
pub fn handle(&mut self, event: DictationIndicatorEvent, now: Instant, reduce: bool) {
self.active = true;
match event {
DictationIndicatorEvent::Reset => {
self.state = HudState::Hidden;
self.loudness = SILENT;
self.demo_voice = None;
}
DictationIndicatorEvent::ConfigureDotScope(tuning) => {
self.tuning = tuning;
self.scope.tune(fill_island(tuning, self.island));
}
DictationIndicatorEvent::DemoVoice => {
self.demo_voice = Some(0.0);
}
DictationIndicatorEvent::Started => {
// HUD Lab and the playground send `DemoVoice` after this.
self.demo_voice = None;
let jobs = self.state.take_jobs();
self.state = HudState::Recording { jobs };
self.loudness = SILENT;
self.stage = Stage::Recording;
self.scope.restart(reduce);
}
DictationIndicatorEvent::Meter { average, .. } => {
self.loudness = dot_scope::loudness(average);
}
DictationIndicatorEvent::Submitted { job_id } => {
let working_since = match self.state {
HudState::Transcribing { working_since, .. }
| HudState::Completing { working_since } => working_since,
_ => now,
};
let mut jobs = self.state.take_jobs();
jobs.insert(job_id);
self.state = HudState::Transcribing {
jobs,
working_since,
};
}
DictationIndicatorEvent::Transcribing { .. }
| DictationIndicatorEvent::Processing { .. } => {}
DictationIndicatorEvent::Discarded | DictationIndicatorEvent::Cancelled => {
self.finish_capture(now, false);
}
DictationIndicatorEvent::JobCompleted { job_id } => {
self.finish_job(job_id, now, JobOutcome::Completed);
}
DictationIndicatorEvent::JobCancelled { job_id } => {
self.finish_job(job_id, now, JobOutcome::Cancelled);
}
DictationIndicatorEvent::JobFailed { job_id, .. } => {
self.finish_job(job_id, now, JobOutcome::Failed);
}
DictationIndicatorEvent::Failed { .. } => {
self.finish_capture(now, true);
}
}
}
fn finish_capture(&mut self, now: Instant, failed: bool) {
match std::mem::replace(&mut self.state, HudState::Hidden) {
HudState::Recording { jobs } if !jobs.is_empty() => {
self.state = HudState::Transcribing {
jobs,
working_since: now,
};
}
HudState::Transcribing {
jobs,
working_since,
} => {
self.state = HudState::Transcribing {
jobs,
working_since,
};
}
_ => {
self.state = if failed {
HudState::Failed { started: now }
} else {
HudState::Hidden
};
}
}
}
fn finish_job(&mut self, job_id: u64, now: Instant, outcome: JobOutcome) {
match &mut self.state {
HudState::Recording { jobs } => {
jobs.remove(&job_id);
}
HudState::Transcribing {
jobs,
working_since,
} => {
if !jobs.remove(&job_id) || !jobs.is_empty() {
return;
}
let working_since = *working_since;
self.state = match outcome {
JobOutcome::Completed => HudState::Completing { working_since },
JobOutcome::Cancelled => HudState::Hidden,
JobOutcome::Failed => HudState::Failed { started: now },
};
}
HudState::Hidden
| HudState::Completing { .. }
| HudState::Completed { .. }
| HudState::Failed { .. } => {}
}
}
/// Advances `dt` seconds to `now` and returns what to draw. Once
/// everything has settled out of sight, [`Self::active`] turns false.
pub fn step(&mut self, now: Instant, dt: f32, reduce: bool) -> DotFrame {
let dt = dt.clamp(1.0 / 240.0, 1.0 / 20.0);
let ears = self.island.is_some_and(|island| island.ears);
let completed_duration = if ears {
EARS_COMPLETED_VISIBLE_DURATION
} else {
COMPLETED_VISIBLE_DURATION
};
match self.state {
HudState::Completing { working_since }
if now.saturating_duration_since(working_since) >= PROCESSING_MIN_DURATION =>
{
self.state = HudState::Completed { started: now };
}
HudState::Completed { started }
if now.saturating_duration_since(started) >= completed_duration =>
{
self.state = HudState::Hidden;
}
HudState::Failed { started }
if now.saturating_duration_since(started) >= FAILED_VISIBLE_DURATION =>
{
self.state = HudState::Hidden;
}
_ => {}
}
let visible = !matches!(self.state, HudState::Hidden);
if let Some(stage) = self.state.stage() {
self.stage = stage;
}
let loudness = match &mut self.demo_voice {
Some(time) => {
*time += dt;
dot_scope::demo_loudness(*time)
}
None => self.loudness,
};
self.scope.advance(
dt,
dot_scope::Frame {
stage: self.stage,
visible,
loudness,
reduce_motion: reduce,
},
);
self.active = visible || !self.scope.settled();
self.frame()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn meter_reports_rms_and_peak() {
let Some(DictationIndicatorEvent::Meter { average, peak }) =
DictationIndicatorEvent::meter(&[-0.5, 0.5])
else {
panic!("expected a meter event");
};
assert!((average - 0.5).abs() < f32::EPSILON);
assert!((peak - 0.5).abs() < f32::EPSILON);
assert!(DictationIndicatorEvent::meter(&[]).is_none());
}
/// Some microphones (a Ryzen built-in digital microphone, #841) carry a
/// constant DC offset louder than the speech; the meter measures around
/// each chunk's mean, as the dictation silence gate does.
#[test]
fn a_dc_offset_never_reads_as_loudness() {
let Some(DictationIndicatorEvent::Meter { average, peak }) =
DictationIndicatorEvent::meter(&[0.2; 512])
else {
panic!("expected a meter event");
};
assert!(
average < 1e-5,
"a constant offset reads as silence: {average}"
);
assert!(peak < 1e-5, "and has no peak: {peak}");
let Some(DictationIndicatorEvent::Meter { average, peak }) =
DictationIndicatorEvent::meter(&[0.7, -0.3])
else {
panic!("expected a meter event");
};
assert!((average - 0.5).abs() < 1e-6);
assert!((peak - 0.5).abs() < 1e-6);
}
#[test]
fn an_island_spreads_the_field_across_it_at_the_same_spacing() {
let tuning = Tuning::default();
assert_eq!(fill_island(tuning, None), tuning);
let island = Island {
notch: [185.0, 32.0],
bar: 0.0,
width: 241.0,
top: -64.0,
ears: false,
};
let filled = fill_island(tuning, Some(island)).clamped();
assert_eq!((filled.columns, filled.rows), (84.0, tuning.rows));
assert_eq!(filled.width, filled.processing_width);
// The outer columns sit as far in from the ends as the outermost
// rows that show from the top and bottom (the faint outer row
// doesn't), within the island less its padding.
let side = (filled.width - (filled.columns - 1.0) * filled.spacing) / 2.0;
assert!((side - field_edge(&filled)).abs() < 1e-3);
assert!((field_edge(&filled) - 5.2).abs() < 1e-3);
assert!(
filled.width <= island.plate_width()
&& island.plate_width() - filled.width < filled.spacing
);
}
#[test]
fn meter_helper_reports_rms_and_peak() {
let Some(DictationIndicatorEvent::Meter { average, peak }) =
DictationIndicatorEvent::meter(&[-0.5, 0.5])
else {
panic!("expected meter event");
};
assert!((average - 0.5).abs() < f32::EPSILON);
assert!((peak - 0.5).abs() < f32::EPSILON);
assert!(DictationIndicatorEvent::meter(&[]).is_none());
}
/// The HUD's status for screen readers follows the capture and its job,
/// and says nothing once the HUD fades out.
#[test]
fn the_status_says_recording_then_transcribing() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
assert_eq!(model.status(), None);
model.handle(DictationIndicatorEvent::Started, start, false);
assert_eq!(model.status(), Some("Recording"));
model.handle(
DictationIndicatorEvent::Submitted { job_id: 1 },
start,
false,
);
assert_eq!(model.status(), Some("Transcribing"));
model.handle(
DictationIndicatorEvent::JobFailed {
job_id: 1,
message: None,
},
start,
false,
);
assert_eq!(model.status(), Some("Failed"));
model.handle(DictationIndicatorEvent::Started, start, false);
model.handle(DictationIndicatorEvent::Discarded, start, false);
assert_eq!(model.status(), None);
}
/// Only the recording phase reports nothing but meters, so it is the only
/// phase a recovery re-ask may act on: `active` stays true through the
/// transcribing, done and failed looks, which draw their own frames (#1793).
#[test]
fn only_the_recording_phase_is_recording() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
assert!(!model.recording());
model.handle(DictationIndicatorEvent::Started, start, false);
assert!(model.recording());
model.handle(
DictationIndicatorEvent::Submitted { job_id: 1 },
start,
false,
);
assert!(!model.recording(), "transcribing draws its own frames");
model.handle(
DictationIndicatorEvent::JobFailed {
job_id: 1,
message: None,
},
start,
false,
);
assert!(!model.recording());
model.handle(DictationIndicatorEvent::Started, start, false);
assert!(model.recording());
model.handle(
DictationIndicatorEvent::Failed { message: None },
start,
false,
);
assert!(!model.recording());
model.handle(DictationIndicatorEvent::Started, start, false);
model.handle(DictationIndicatorEvent::Cancelled, start, false);
assert!(!model.recording());
model.handle(DictationIndicatorEvent::Reset, start, false);
assert!(!model.recording());
}
fn at(start: Instant, seconds: f32) -> Instant {
start + Duration::from_secs_f32(seconds)
}
fn run(model: &mut IndicatorModel, start: Instant, from: f32, seconds: f32) -> Vec<DotFrame> {
(0..(seconds * 60.0) as usize)
.map(|n| model.step(at(start, from + n as f32 / 60.0), 1.0 / 60.0, false))
.collect()
}
fn lit(frame: &DotFrame) -> u32 {
frame.dots.iter().map(|[power, _]| u32::from(*power)).sum()
}
/// A hot Linux microphone speaks near −18 dBFS RMS, which a fixed gain
/// pins at full, so the HUD sat still: the auto level keeps it moving.
#[test]
fn a_hot_microphone_still_moves_the_scope() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
model.handle(DictationIndicatorEvent::Started, start, false);
let mut levels = Vec::new();
for n in 0..360 {
let t = n as f32 / 60.0;
let now = at(start, t);
// Syllables at 4 Hz between −24 and −12 dBFS.
let db = -18.0 + 6.0 * (t * 4.0 * std::f32::consts::TAU).sin();
let rms = 10_f32.powf(db / 20.0);
model.handle(
DictationIndicatorEvent::Meter {
average: rms,
peak: (rms * 3.0).min(1.0),
},
now,
false,
);
model.step(now, 1.0 / 60.0, false);
if t > 2.0 {
levels.push(model.scope.level());
}
}
let low = levels.iter().copied().fold(f32::MAX, f32::min);
let high = levels.iter().copied().fold(0.0, f32::max);
assert!(high - low > 0.35, "the level swings {low}..{high}");
}
#[test]
fn a_dictation_records_processes_finishes_and_settles() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
model.handle(DictationIndicatorEvent::Started, start, false);
model.handle(DictationIndicatorEvent::DemoVoice, start, false);
let frames = run(&mut model, start, 0.0, 1.0);
let frame = frames.last().unwrap();
assert_eq!(frame.dots.len(), frame.columns * frame.rows);
assert!(frame.dots.iter().any(|[power, _]| *power > 30_000));
assert!(frame.pose.opacity > 0.98 && frame.pose.cool < 0.01);
// A fast transcription: the job finishes as soon as it is submitted.
model.handle(
DictationIndicatorEvent::Submitted { job_id: 1 },
at(start, 1.0),
false,
);
model.handle(
DictationIndicatorEvent::JobCompleted { job_id: 1 },
at(start, 1.0),
false,
);
run(&mut model, start, 1.0, 0.15);
assert_eq!(model.stage, Stage::Processing, "processing shows briefly");
run(&mut model, start, 1.15, 0.1);
assert_eq!(model.stage, Stage::Done);
run(&mut model, start, 1.25, 2.0);
assert!(!model.active(), "settled out of sight");
}
#[test]
fn processing_that_ran_long_enough_finishes_at_once() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
model.handle(DictationIndicatorEvent::Started, start, false);
model.handle(
DictationIndicatorEvent::Submitted { job_id: 1 },
at(start, 0.5),
false,
);
run(&mut model, start, 0.5, 0.5);
model.handle(
DictationIndicatorEvent::JobCompleted { job_id: 1 },
at(start, 1.0),
false,
);
run(&mut model, start, 1.0, 1.0 / 60.0);
assert_eq!(model.stage, Stage::Done);
}
#[test]
fn the_notch_indicator_holds_done_for_its_checkmark() {
// How shown the HUD is `seconds` after done begins.
let shown_after = |island: Option<Island>, seconds: f32| {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
model.set_island(island);
model.handle(DictationIndicatorEvent::Started, start, false);
run(&mut model, start, 0.0, 0.5);
for event in [
DictationIndicatorEvent::Submitted { job_id: 1 },
DictationIndicatorEvent::JobCompleted { job_id: 1 },
] {
model.handle(event, at(start, 0.5), false);
}
// Processing shows for its 0.2 s minimum first.
let frames = run(&mut model, start, 0.5, 0.2 + seconds);
let pose = frames.last().unwrap().pose;
assert_eq!(pose.done, 1.0);
pose.opacity
};
let ears = Island {
notch: [185.0, 32.0],
bar: 34.0,
width: 253.0,
top: -64.0,
ears: true,
};
assert!(
shown_after(Some(ears), 0.6) > 0.95,
"the checkmark stays up"
);
assert!(
shown_after(Some(ears), 1.3) < 0.05,
"then the ears fold back"
);
assert!(
shown_after(None, 0.6) < 0.05,
"Dot scope still collapses at once"
);
}
#[test]
fn a_failure_turns_coral_and_a_cancel_just_fades() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
model.handle(DictationIndicatorEvent::Started, start, false);
run(&mut model, start, 0.0, 0.5);
model.handle(
DictationIndicatorEvent::Failed { message: None },
at(start, 0.5),
false,
);
let failed = run(&mut model, start, 0.5, 0.5);
assert!(failed.last().unwrap().pose.fail > 0.9);
run(&mut model, start, 1.0, 1.5);
assert!(!model.active());
model.handle(DictationIndicatorEvent::Started, at(start, 3.0), false);
run(&mut model, start, 3.0, 0.5);
model.handle(DictationIndicatorEvent::Cancelled, at(start, 3.5), false);
let cancelled = run(&mut model, start, 3.5, 1.5);
assert!(cancelled.iter().all(|frame| frame.pose.fail < 0.01));
assert!(lit(cancelled.last().unwrap()) == 0 || !model.active());
assert!(!model.active());
}
#[test]
fn pending_completion_cannot_replace_a_new_recording_phase() {
let start = Instant::now();
let mut model = IndicatorModel::new(Tuning::default(), start);
model.handle(DictationIndicatorEvent::Started, start, false);
model.handle(
DictationIndicatorEvent::Submitted { job_id: 1 },
at(start, 0.2),
false,
);
// Start a second recording while job 1 is still transcribing.
model.handle(DictationIndicatorEvent::Started, at(start, 0.3), false);
assert!(model.recording());
assert_eq!(model.status(), Some("Recording"));
// Job 1 completing must not replace the active recording with Done.
model.handle(
DictationIndicatorEvent::JobCompleted { job_id: 1 },
at(start, 0.35),
false,
);
run(&mut model, start, 0.35, 0.4);
assert!(model.recording());
assert_eq!(model.stage, Stage::Recording);
// Discarding a new capture while an earlier job is still in flight
// returns to Transcribing rather than hiding.
model.handle(
DictationIndicatorEvent::Submitted { job_id: 2 },
at(start, 0.8),
false,
);
model.handle(DictationIndicatorEvent::Started, at(start, 0.9), false);
model.handle(DictationIndicatorEvent::Discarded, at(start, 1.0), false);
assert!(!model.recording());
assert_eq!(model.status(), Some("Transcribing"));
model.handle(
DictationIndicatorEvent::JobCancelled { job_id: 2 },
at(start, 1.1),
false,
);
assert_eq!(model.status(), None);
}
}