hex/src/rune_ui/fun.rs
Kit Langton fedab81d81
feat(voice filter): preview effects without changing your call (#1906)
* feat(voice filter): preview effects without changing the call (t1598)

* test(voice filter): check pass-through after the preset fade (t1598)

* test(voice filter): refresh the setup and preview goldens (t1598)

* chore(voice filter): finish the preview checks (t1598)
2026-11-16 15:37:31 -08:00

752 lines
26 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! The Voice Filter pane (macOS and Linux, in Labs, or while the Hex
//! Microphone driver is installed): the virtual microphone (macOS's driver,
//! or Linux's PipeWire source), the filter mode and its key sliders, comfort
//! noise, and "Try it": record five seconds or use the example clip, then
//! compare your voice with what the call hears on two waveforms drawn with
//! Rune shapes. Voice Filter is a dev-build Lab: a stable build shows the
//! pane only while the macOS driver is installed, with Uninstall alone.
//! The driver, the live filter, and the demo audio stay with the
//! host (`PlatformState::{hex_microphone, tuning, demo}`, `PlatformRequest::
//! {SetTuning, HexMicrophoneDemo}`).
use rune::{El, LineCap, Shape, canvas, col, row, text};
use super::Ui;
use super::controls::{
ButtonKind, DESCRIPTION, METRICS, Paint, button, card, page, pulsing_dot, segmented,
setting_row, toggle_row,
};
use super::lists::{Tone, slider, small_button, tone_tag};
use super::platform::{DemoRequest, PlatformRequest};
use crate::audio::hex_microphone::{
DemoPlaybackTrack, DemoSnapshot, DemoSourceKind, DriverActionState, HexMicrophoneStatus,
TunedFilterConfig,
};
use crate::audio::voice_filter::{DictationSpan, VoiceFilterMode};
use crate::desktop::i18n::{tr, tr_fill};
const SLIDER_WIDTH: f32 = 300.0;
const WAVE_HEIGHT: f32 = 28.0;
/// A tunable of the live filter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tunable {
Strength,
MuffledWall,
MuffledRoom,
MuffledLevel,
QuietLevel,
MutedRoomTone,
ChipmunkPitch,
RobotCarrier,
WalkieCrunch,
UnderwaterDepth,
FarRoom,
}
impl Tunable {
fn key(self) -> &'static str {
match self {
Self::Strength => "fun-slider-strength",
Self::MuffledWall => "fun-slider-wall",
Self::MuffledRoom => "fun-slider-room",
Self::MuffledLevel => "fun-slider-level",
Self::QuietLevel => "fun-slider-quiet",
Self::MutedRoomTone => "fun-slider-room-tone",
Self::ChipmunkPitch => "fun-slider-pitch",
Self::RobotCarrier => "fun-slider-carrier",
Self::WalkieCrunch => "fun-slider-crunch",
Self::UnderwaterDepth => "fun-slider-depth",
Self::FarRoom => "fun-slider-far-room",
}
}
/// Where the value sits on the slider, and how it reads.
fn position(self, cfg: &TunedFilterConfig) -> (f32, String) {
let norm = |v: f64, min: f64, max: f64| ((v - min) / (max - min)).clamp(0.0, 1.0) as f32;
match self {
Self::Strength => (
cfg.strength.clamp(0.0, 1.0),
format!("{:.0}%", cfg.strength * 100.0),
),
Self::MuffledWall => (
norm(cfg.muffled_wall_hz, 150.0, 3000.0),
format!("{:.0} Hz", cfg.muffled_wall_hz),
),
Self::MuffledRoom => (
norm(cfg.muffled_room_mix, 0.0, 0.8),
format!("{:.0}%", cfg.muffled_room_mix * 100.0),
),
Self::MuffledLevel => (
norm(cfg.muffled_level_db, -24.0, 0.0),
format!("{:.0} dB", cfg.muffled_level_db),
),
Self::QuietLevel => (
norm(cfg.quiet_level_db, -36.0, -6.0),
format!("{:.0} dB", cfg.quiet_level_db),
),
Self::MutedRoomTone => (
norm(cfg.muted_room_tone_db, -80.0, -42.0),
format!("{:.0} dB", cfg.muted_room_tone_db),
),
Self::ChipmunkPitch => (
norm(cfg.chipmunk_semitones, 2.0, 12.0),
format!("+{:.1} st", cfg.chipmunk_semitones),
),
Self::RobotCarrier => (
norm(cfg.robot_carrier_hz, 30.0, 180.0),
format!("{:.0} Hz", cfg.robot_carrier_hz),
),
Self::WalkieCrunch => (
norm(cfg.walkie_crunch, 1.0, 8.0),
format!("{:.1}x", cfg.walkie_crunch),
),
Self::UnderwaterDepth => (
norm(cfg.underwater_depth_hz, 160.0, 900.0),
format!("{:.0} Hz", cfg.underwater_depth_hz),
),
Self::FarRoom => (
norm(cfg.far_distance_mix, 0.2, 0.95),
format!("{:.0}%", cfg.far_distance_mix * 100.0),
),
}
}
/// Sets the value from a slider position, rounded to the tunable's step.
fn apply(self, cfg: &mut TunedFilterConfig, position: f32) {
let t = f64::from(position.clamp(0.0, 1.0));
let lerp = |min: f64, max: f64| min + (max - min) * t;
match self {
Self::Strength => cfg.strength = t as f32,
Self::MuffledWall => cfg.muffled_wall_hz = lerp(150.0, 3000.0).round(),
Self::MuffledRoom => cfg.muffled_room_mix = (lerp(0.0, 0.8) * 100.0).round() / 100.0,
Self::MuffledLevel => cfg.muffled_level_db = lerp(-24.0, 0.0).round(),
Self::QuietLevel => cfg.quiet_level_db = lerp(-36.0, -6.0).round(),
Self::MutedRoomTone => cfg.muted_room_tone_db = lerp(-80.0, -42.0).round(),
Self::ChipmunkPitch => cfg.chipmunk_semitones = (lerp(2.0, 12.0) * 2.0).round() / 2.0,
Self::RobotCarrier => cfg.robot_carrier_hz = lerp(30.0, 180.0).round(),
Self::WalkieCrunch => cfg.walkie_crunch = (lerp(1.0, 8.0) * 10.0).round() / 10.0,
Self::UnderwaterDepth => cfg.underwater_depth_hz = lerp(160.0, 900.0).round(),
Self::FarRoom => cfg.far_distance_mix = (lerp(0.2, 0.95) * 100.0).round() / 100.0,
}
}
}
pub(super) fn mode_label(mode: VoiceFilterMode) -> &'static str {
match mode {
VoiceFilterMode::Muffled => tr("Muffled"),
VoiceFilterMode::Muted => tr("Muted"),
VoiceFilterMode::Quiet => tr("Quiet"),
VoiceFilterMode::Normal => tr("Normal"),
VoiceFilterMode::Chipmunk => tr("Chipmunk"),
VoiceFilterMode::Robot => tr("Robot"),
VoiceFilterMode::Walkie => tr("Walkie"),
VoiceFilterMode::Underwater => tr("Underwater"),
VoiceFilterMode::Far => tr("Far"),
}
}
/// Saves a mode, comfort noise, or strength and applies the tuning live.
pub(super) fn set_tuning(ui: &mut Ui, change: impl FnOnce(&mut TunedFilterConfig), save: bool) {
let mut cfg = ui.platform.tuning.clone();
change(&mut cfg);
if save {
let (mode, comfort, strength) = (cfg.mode, cfg.comfort_noise, cfg.strength);
ui.update(|settings| {
settings.experimental.hex_microphone_mode = mode;
settings.experimental.hex_microphone_comfort_noise = comfort;
settings.experimental.hex_microphone_strength = strength;
});
}
ui.platform.tuning = cfg.clone();
ui.ask(PlatformRequest::SetTuning(cfg));
}
fn ask_demo(ui: &mut Ui, request: DemoRequest) {
ui.ask(PlatformRequest::HexMicrophoneDemo(request));
}
/// Hex Microphone's state where Hex creates it rather than a driver
/// (`Capabilities::hex_microphone` off): starting, available, or failed.
fn source_state(status: &HexMicrophoneStatus) -> (&'static str, Tone) {
match &status.action_state {
DriverActionState::Failed(_) => (tr("Unavailable"), Tone::Danger),
_ if status.driver_loaded => (tr("Available"), Tone::Success),
_ => (tr("Starting…"), Tone::Neutral),
}
}
/// Hex Microphone as a virtual input Hex creates (Linux): what to do with
/// it, or why it could not start. The header shows its state.
fn source_row(ui: &Ui, p: Paint) -> El {
let title = tr("Hex Microphone");
let Some(status) = &ui.platform.hex_microphone else {
return setting_row(
p,
"hex-mic-source",
title,
Some(tr("Checking…")),
row().key("none"),
);
};
let description = match &status.action_state {
DriverActionState::Failed(reason) => tr_fill("Could not start Hex Microphone: {}", reason),
_ if status.driver_loaded => {
tr("Select Hex Microphone as the input in your call app").to_string()
}
_ => tr("Starting Hex Microphone…").to_string(),
};
setting_row(
p,
"hex-mic-source",
title,
Some(&description),
tone_tag(
p,
"source-state",
source_state(status).0,
source_state(status).1,
),
)
}
fn tunable(ui: &Ui, p: Paint, which: Tunable, label: &str) -> El {
let (position, display) = which.position(&ui.platform.tuning);
slider(
p,
which.key(),
label,
position,
display,
SLIDER_WIDTH,
move |ui, position, done| {
// Strength is a setting; the per-mode values live with the filter.
set_tuning(
ui,
|cfg| which.apply(cfg, position),
done && which == Tunable::Strength,
);
},
)
}
/// Whether the Voice Filter pane shows: in a dev build, while the filter
/// runs (`app_settings::voice_filter_enabled`: its switch is on, or the host
/// found its driver installed); in a stable build, only while the driver is
/// installed, so it can be uninstalled.
pub(super) fn running(ui: &Ui) -> bool {
(crate::labs::Feature::VoiceFilter.shipped() && ui.settings.experimental.hex_microphone)
|| driver_installed(ui)
}
/// A stable build has no Voice Filter: its pane offers only the installed
/// driver's Uninstall.
fn uninstall_only() -> bool {
!crate::labs::Feature::VoiceFilter.shipped()
}
/// The Hex Microphone driver is installed: apps may use it, so the Voice
/// Filter stays on until it is uninstalled.
pub(super) fn driver_installed(ui: &Ui) -> bool {
ui.platform
.hex_microphone
.as_ref()
.is_some_and(|status| status.driver_bundle_installed)
}
pub(super) fn pane(ui: &Ui, p: Paint) -> El {
let mut content = page("content");
if uninstall_only() {
content = content.child(card(p, "fun-hex-microphone", vec![uninstall_row(ui, p)]));
} else {
let setup = if ui.platform.caps.hex_microphone {
super::platform_settings::driver_row(ui, p)
} else {
source_row(ui, p)
};
content = content
.child(super::controls::section(
p,
"effect",
tr("What callers hear"),
vec![effect_grid(ui, p), try_it(ui, p)],
))
.child(card(p, "fun-hex-microphone", vec![setup]));
if ui.platform.tuning.mode != VoiceFilterMode::Normal {
content = content.child(super::general::disclosure_toggle(
ui,
p,
super::Pane::VoiceFilter,
tr("Adjust effect"),
));
if super::general::advanced_open(ui, super::Pane::VoiceFilter) {
content = content.child(tuning_card(ui, p));
}
}
}
super::scroll_body(p.k, "fun-scroll", content)
}
fn effect_grid(ui: &Ui, p: Paint) -> El {
let c = &p.k.c;
let mut grid = row().key("fun-mode").gap(8.0).flex_wrap();
for mode in VoiceFilterMode::ALL {
let label = mode_label(mode);
let applied = ui.platform.tuning.mode == mode;
let track = DemoPlaybackTrack::Effect(mode);
let playing = ui
.platform
.demo
.as_ref()
.is_some_and(|d| d.playing == Some(track));
let mut choice = row()
.key("apply")
.role("radio")
.label(label)
.checked(applied)
.grow(1.0)
.shrink()
.px(10.0)
.min_h(36.0)
.gap(6.0)
.center_y()
.focusable(true)
.focus_ring(2.0, 0.0, c.border_focus)
.hover(c.hover)
.press(c.pressed)
.radius(p.k.radius.md)
.on_press(move |ui: &mut Ui| set_tuning(ui, |cfg| cfg.mode = mode, true))
.child(
text(label)
.key("name")
.font(p.k.ty.ui)
.color(p.text())
.wrap(),
);
if applied {
choice = choice.child(
rune::icon(&rune_theme_opencode::icons::CHECK_SMALL, 16.0)
.key("check")
.color(p.accent()),
);
}
let mut tile = row()
.key(mode.id())
.min_w(180.0)
.grow(1.0)
.center_y()
.pr(4.0)
.border(p.hair, if applied { p.accent() } else { c.border_weak })
.radius(p.k.radius.md)
.fill(if applied { c.layer_01 } else { c.bg_base })
.child(choice);
if ui.platform.demo.is_some() {
let action = if playing { tr("Stop") } else { tr("Play") };
let play = rune_kit::IconButton::new(if playing {
&rune_theme_opencode::icons::STOP
} else {
&super::controls::PLAY
})
.variant(rune_kit::IconButtonVariant::Neutral)
.control_size(rune_kit::ControlSize::Regular)
.label(format!("{action}: {label}"))
.on_press(move |ui: &mut Ui| {
ask_demo(
ui,
if playing {
DemoRequest::StopPlayback
} else {
DemoRequest::Play(track)
},
)
})
.build(p.k)
.key("play");
tile = tile.child(play);
}
grid = grid.child(tile);
}
col().key("effects").px(METRICS.row_px).py(12.0).gap(12.0)
.child(text(tr("Select an effect for dictation. Play previews it without changing your call. Your voice sounds normal between dictations.")).key("description").font(DESCRIPTION).color(p.muted()).wrap()).child(grid)
}
fn tuning_card(ui: &Ui, p: Paint) -> El {
let cfg = &ui.platform.tuning;
let mode = cfg.mode;
let (primary, primary_label) = match mode {
VoiceFilterMode::Muffled | VoiceFilterMode::Normal => (Tunable::MuffledWall, tr("Wall")),
VoiceFilterMode::Muted => (Tunable::MutedRoomTone, tr("Room tone")),
VoiceFilterMode::Quiet => (Tunable::QuietLevel, tr("Level")),
VoiceFilterMode::Chipmunk => (Tunable::ChipmunkPitch, tr("Pitch")),
VoiceFilterMode::Robot => (Tunable::RobotCarrier, tr("Carrier")),
VoiceFilterMode::Walkie => (Tunable::WalkieCrunch, tr("Crunch")),
VoiceFilterMode::Underwater => (Tunable::UnderwaterDepth, tr("Depth")),
VoiceFilterMode::Far => (Tunable::FarRoom, tr("Room")),
};
let mut tuning = col()
.key("tuning")
.px(METRICS.row_px)
.py(10.0)
.gap(12.0)
.child(
row()
.key("mode-heading")
.gap(16.0)
.center_y()
.justify_between()
.child(
text(mode_label(mode))
.key("mode")
.font(p.k.ty.ui)
.color(p.text()),
)
.child(small_button(
p,
"fun-reset-tuning",
tr("Reset"),
|ui: &mut Ui, _| {
set_tuning(
ui,
|cfg| {
let mode = cfg.mode;
*cfg = TunedFilterConfig::default();
cfg.mode = mode;
cfg.comfort_noise = true;
},
true,
);
},
)),
);
if mode != VoiceFilterMode::Normal {
tuning = tuning.child(
row()
.key("sliders")
.gap(16.0)
.flex_wrap()
.child(tunable(ui, p, primary, primary_label))
.child(tunable(ui, p, Tunable::Strength, tr("Effect strength"))),
);
}
if mode == VoiceFilterMode::Muffled {
tuning = tuning.child(
row()
.key("muffled-sliders")
.gap(16.0)
.flex_wrap()
.child(tunable(ui, p, Tunable::MuffledRoom, tr("Room")))
.child(tunable(ui, p, Tunable::MuffledLevel, tr("Level"))),
);
}
let mut rows = vec![tuning];
if mode == VoiceFilterMode::Muted {
rows.push(toggle_row(
p,
"fun-comfort-noise",
tr("Comfort noise"),
tr("Keeps a quiet room tone while muted so callers know the line is live"),
cfg.comfort_noise,
|ui: &mut Ui| {
let enabled = !ui.platform.tuning.comfort_noise;
set_tuning(ui, |cfg| cfg.comfort_noise = enabled, true);
},
));
}
card(p, "adjustments", rows)
}
/// A stable build's only Voice Filter row: Uninstall the driver it left.
fn uninstall_row(ui: &Ui, p: Paint) -> El {
let status = ui.platform.hex_microphone.as_ref();
let uninstalling = ui
.platform
.hex_microphone
.as_ref()
.is_some_and(|status| matches!(status.action_state, DriverActionState::Uninstalling));
let control = if uninstalling {
tone_tag(p, "state", tr("Uninstalling…"), Tone::Neutral)
} else {
button(
p,
"uninstall",
tr("Uninstall"),
ButtonKind::Secondary,
|ui: &mut Ui, _| ui.ask(PlatformRequest::UninstallHexMicrophone),
)
};
let hint = match status.map(|s| &s.action_state) {
Some(DriverActionState::Failed(reason)) => format!("{} · {}", tr("Failed"), reason),
Some(DriverActionState::Cancelled) => tr("Uninstall cancelled").into(),
_ => tr("Voice Filter isn't in this version of Hex. Uninstall its driver to remove Hex Microphone from your inputs.").into(),
};
setting_row(
p,
"hex-mic-driver",
tr("Virtual microphone driver"),
Some(&hint),
row().key("controls").gap(8.0).center_y().child(control),
)
}
/// Record or pick a clip, see both tracks, and play either one.
fn try_it(ui: &Ui, p: Paint) -> El {
let Some(demo) = &ui.platform.demo else {
return setting_row(
p,
"fun-try-it",
tr("Try it"),
Some(tr(
"Compare your raw microphone with what the call hears during dictation",
)),
text(tr("Checking…"))
.key("loading")
.font(DESCRIPTION)
.color(p.muted()),
);
};
let mut controls = row().key("demo-controls").gap(8.0).center_y();
if demo.has_recording {
controls = controls.child(segmented(
p,
"fun-demo-source",
&[tr("Example"), tr("Your voice")],
usize::from(demo.source == DemoSourceKind::Recording),
|ui, index| {
let source = if index == 1 {
DemoSourceKind::Recording
} else {
DemoSourceKind::Example
};
ask_demo(ui, DemoRequest::SelectSource(source));
},
));
}
if !demo.has_recording {
controls = controls.child(
text(tr("Example"))
.key("source")
.font(p.k.ty.ui)
.color(p.text()),
);
}
let original = demo.playing == Some(DemoPlaybackTrack::You);
controls = controls.child(small_button(
p,
"fun-play-you",
if original {
tr("Stop")
} else {
tr("Play original")
},
move |ui, _| {
ask_demo(
ui,
if original {
DemoRequest::StopPlayback
} else {
DemoRequest::Play(DemoPlaybackTrack::You)
},
)
},
));
let mut record = row().key("record").center_y().gap(8.0).child(
text(tr("Stays in memory"))
.key("memory")
.font(p.k.ty.small)
.color(p.muted()),
);
if demo.is_recording {
record = record.child(pulsing_dot(p.danger()));
}
let recording = demo.is_recording;
record = record.child(small_button(
p,
"fun-demo-record",
if recording {
tr("Stop recording")
} else {
tr("Record 5s")
},
move |ui, _| {
ask_demo(
ui,
if recording {
DemoRequest::StopRecording
} else {
DemoRequest::Record
},
)
},
));
col()
.key("fun-try-it")
.px(METRICS.row_px)
.py(10.0)
.gap(10.0)
.child(
row()
.key("sources")
.justify_between()
.center_y()
.gap(8.0)
.flex_wrap()
.child(controls)
.child(record),
)
.child(waveforms(p, demo, ui.platform.tuning.mode))
}
/// The clip's two tracks as bars, the dictated span highlighted, and the
/// recording or playback progress under them.
fn waveforms(p: Paint, demo: &DemoSnapshot, applied: VoiceFilterMode) -> El {
let c = &p.k.c;
let clip = tr("While dictating");
let effect = match demo.playing {
Some(DemoPlaybackTrack::Effect(mode)) => mode,
_ => applied,
};
let span = format!(
"{:.1}s – {:.1}s",
demo.span.start_ms / 1000.0,
demo.span.end_ms / 1000.0
);
let track = |key: &str, label: &str, accent: bool, peaks: &[f32]| {
row()
.key(key)
.gap(12.0)
.center_y()
.child(
text(label)
.key("label")
.font(if accent {
p.k.ty.small_medium
} else {
p.k.ty.small
})
.color(if accent { p.accent() } else { p.faint() })
.w(80.0),
)
.child(
canvas(bars(p, peaks, &demo.span, demo.duration_ms, accent))
.key("wave")
.grow(1.0)
.shrink()
.h(WAVE_HEIGHT)
.radius(p.k.radius.sm)
.fill(c.layer_01),
)
};
let active = demo.is_recording || demo.playing.is_some();
let progress = if demo.is_recording {
demo.recording_progress
} else {
demo.playback_progress
}
.clamp(0.0, 1.0);
let mut card = col()
.key("fun-waveform")
.padding(12.0)
.gap(10.0)
.radius(p.k.radius.md)
.border(p.hair, c.border_weak)
.fill(c.bg_base)
.child(
row()
.key("clip")
.gap(8.0)
.center_y()
.justify_between()
.child(
row()
.key("quote")
.gap(8.0)
.center_y()
.shrink()
.child(
text(clip)
.key("text")
.font(DESCRIPTION)
.color(p.muted())
.truncate(),
)
.child(tone_tag(p, "span", &span, Tone::Accent)),
)
.child(
text(format!("{:.1}s", demo.duration_ms as f64 / 1000.0))
.key("duration")
.font(p.k.ty.mono)
.color(p.faint()),
),
)
.child(track("you", tr("Original"), false, &demo.peaks_you))
.child(track("call", mode_label(effect), true, &demo.peaks_call));
if active {
card = card.child(
rune_kit::Progress::new(Some(progress))
.build(p.k)
.key("progress"),
);
}
card
}
/// One bar per peak, `WAVE_HEIGHT` tall at full scale, in a view box the
/// canvas stretches to its width.
fn bars(p: Paint, peaks: &[f32], span: &DictationSpan, duration_ms: u32, accent: bool) -> Shape {
let c = &p.k.c;
let (inside, outside) = if accent {
(p.accent(), c.text_muted)
} else {
(c.text_base, c.text_faint)
};
let count = peaks.len().max(1);
let width = count as f32 * 4.0;
let mid = WAVE_HEIGHT / 2.0;
let duration = f64::from(duration_ms.max(1));
let mut shape = Shape::new();
for (index, peak) in peaks.iter().enumerate() {
let at = (index as f64 + 0.5) / count as f64 * duration;
let color = if at >= span.start_ms && at <= span.end_ms {
inside
} else {
outside
};
let half = peak.clamp(0.06, 1.0) * (mid - 4.0);
let x = index as f32 * 4.0 + 2.0;
shape = shape.line([x, mid - half], [x, mid + half], 2.0, LineCap::Round, color);
}
shape.view_box(width, WAVE_HEIGHT)
}
/// Deterministic demo state for scenes: the example clip with both tracks.
pub(super) fn preview_demo(recording: bool, playing: Option<DemoPlaybackTrack>) -> DemoSnapshot {
let peaks = |seed: f32, damp: f32| -> Vec<f32> {
(0..96)
.map(|i| {
let x = i as f32;
let voice = ((x * 0.37 + seed).sin() * 0.5 + (x * 0.11).sin() * 0.35).abs();
let speaking = (x > 18.0 && x < 70.0) as u8 as f32;
(0.08
+ voice
* (0.3 + 0.7 * speaking)
* if (24.0..64.0).contains(&x) { damp } else { 1.0 })
.min(1.0)
})
.collect()
};
DemoSnapshot {
source: DemoSourceKind::Example,
has_recording: true,
is_recording: recording,
recording_progress: 0.4,
playing,
playback_progress: 0.55,
duration_ms: 5_200,
span: DictationSpan {
start_ms: 1_300.0,
end_ms: 3_450.0,
},
peaks_you: peaks(0.0, 1.0),
peaks_call: peaks(0.0, 0.25),
}
}