mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-27 07:58:01 +01:00
859 lines
31 KiB
Rust
859 lines
31 KiB
Rust
//! 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);
|
||
}
|
||
}
|