fix(client): list only real audio devices and persist the choice by id
The device pickers showed every ALSA PCM plugin (Discard all samples, Rate Converter, JACK, Open Sound System, surround/dmix aliases). Enumeration now goes through a pure filter that keeps the system default, the PipeWire and PulseAudio servers and one entry per hardware endpoint, with technical tails removed and a stable sort. Selections are stored by device id instead of list position, so the filter and hotplug cannot move a saved choice. Indexes saved by older versions are migrated by device name; a missing device falls back to the default. The same preferences change records whether the voice mode was chosen by the person: a profile that only carries the old push-to-talk default now starts in voice activation, explicit choices are kept.
This commit is contained in:
parent
82dd9a324d
commit
3b95df9e9c
17 changed files with 780 additions and 210 deletions
419
src/audio/devices/filter.rs
Normal file
419
src/audio/devices/filter.rs
Normal file
|
|
@ -0,0 +1,419 @@
|
||||||
|
//! Pure device-list policy: which enumerated audio devices a person should see.
|
||||||
|
//!
|
||||||
|
//! ALSA enumerates dozens of PCM "devices" that are plugins or routing aliases
|
||||||
|
//! (`null`, `lavrate`, `jack`, `oss`, `surround51:...`, `dmix:...`). Offering them in a
|
||||||
|
//! picker is noise at best and a silent-microphone trap at worst. This module keeps the
|
||||||
|
//! system default, the sound servers (PipeWire, PulseAudio) and one entry per real
|
||||||
|
//! hardware endpoint, with readable names. It does not touch any audio API, so it is
|
||||||
|
//! fully unit-testable.
|
||||||
|
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
|
/// A device as reported by the audio backend, before any filtering.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RawDevice {
|
||||||
|
/// Stable backend identifier (ALSA PCM name such as `sysdefault:CARD=PCH`).
|
||||||
|
pub id: String,
|
||||||
|
/// Human readable first line of the backend description.
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A device that survived filtering and is offered to the user.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct DeviceEntry {
|
||||||
|
/// Stable backend identifier; this is what gets persisted.
|
||||||
|
pub id: String,
|
||||||
|
/// Display name shown in the picker.
|
||||||
|
pub label: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How an ALSA PCM identifier should be treated.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Class {
|
||||||
|
/// `pipewire` or `pulse` sound server plugin.
|
||||||
|
Server(u8),
|
||||||
|
/// A real endpoint; the number is its preference among aliases of the same endpoint.
|
||||||
|
Hardware(u8),
|
||||||
|
/// Plugins, converters, routing aliases and the default alias itself.
|
||||||
|
Hidden,
|
||||||
|
}
|
||||||
|
|
||||||
|
const PRIORITY_HDMI: u8 = 3;
|
||||||
|
const PRIORITY_SYSDEFAULT: u8 = 3;
|
||||||
|
const PRIORITY_PLUGHW: u8 = 2;
|
||||||
|
const PRIORITY_HW: u8 = 1;
|
||||||
|
|
||||||
|
/// Splits an ALSA PCM id into its prefix and the `CARD=..,DEV=..` selector, if any.
|
||||||
|
fn split_id(id: &str) -> (&str, Option<(&str, u32)>) {
|
||||||
|
let Some((prefix, rest)) = id.split_once(':') else {
|
||||||
|
return (id, None);
|
||||||
|
};
|
||||||
|
let mut card = None;
|
||||||
|
let mut dev = 0u32;
|
||||||
|
for part in rest.split(',') {
|
||||||
|
if let Some(value) = part.strip_prefix("CARD=") {
|
||||||
|
card = Some(value);
|
||||||
|
} else if let Some(value) = part.strip_prefix("DEV=") {
|
||||||
|
dev = value.parse().unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(prefix, card.map(|card| (card, dev)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn classify_alsa(id: &str) -> Class {
|
||||||
|
let (prefix, selector) = split_id(id);
|
||||||
|
match (prefix, selector) {
|
||||||
|
("pipewire", None) => Class::Server(0),
|
||||||
|
("pulse", None) => Class::Server(1),
|
||||||
|
("hdmi", Some(_)) => Class::Hardware(PRIORITY_HDMI),
|
||||||
|
("sysdefault", Some(_)) => Class::Hardware(PRIORITY_SYSDEFAULT),
|
||||||
|
("plughw", Some(_)) => Class::Hardware(PRIORITY_PLUGHW),
|
||||||
|
("hw", Some(_)) => Class::Hardware(PRIORITY_HW),
|
||||||
|
_ => Class::Hidden,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Descriptions of known plugin pseudo-devices that must never be listed, whatever their id.
|
||||||
|
fn looks_like_plugin(name: &str) -> bool {
|
||||||
|
const MARKERS: [&str; 10] = [
|
||||||
|
"discard all samples",
|
||||||
|
"rate converter",
|
||||||
|
"plugin",
|
||||||
|
"jack audio connection kit",
|
||||||
|
"open sound system",
|
||||||
|
"direct sample mixing",
|
||||||
|
"direct sample snooping",
|
||||||
|
"hardware device with all software conversions",
|
||||||
|
"sound server",
|
||||||
|
"default alsa",
|
||||||
|
];
|
||||||
|
let lowered = name.to_lowercase();
|
||||||
|
MARKERS.iter().any(|marker| lowered.contains(marker))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes technical tails and collapses whitespace in a backend device name.
|
||||||
|
pub fn pretty_name(raw: &str) -> String {
|
||||||
|
let mut name = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
for tail in [" (ALSA)", " (alsa)", " (Default Audio Device)"] {
|
||||||
|
if let Some(stripped) = name.strip_suffix(tail) {
|
||||||
|
name = stripped.trim_end().to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name
|
||||||
|
}
|
||||||
|
|
||||||
|
fn server_label(id: &str) -> &'static str {
|
||||||
|
if id == "pipewire" {
|
||||||
|
"PipeWire"
|
||||||
|
} else {
|
||||||
|
"PulseAudio"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compare_labels(a: &str, b: &str) -> Ordering {
|
||||||
|
a.to_lowercase()
|
||||||
|
.cmp(&b.to_lowercase())
|
||||||
|
.then_with(|| a.cmp(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filters `raw` down to the devices worth showing and returns them sorted: sound servers
|
||||||
|
/// first, then hardware alphabetically. Several aliases of one endpoint collapse into the
|
||||||
|
/// most convenient one, and equal display names never appear twice.
|
||||||
|
///
|
||||||
|
/// `alsa` selects the ALSA policy; other backends only drop empty names, because their
|
||||||
|
/// device lists are already limited to real endpoints.
|
||||||
|
pub fn visible_devices(raw: &[RawDevice], alsa: bool) -> Vec<DeviceEntry> {
|
||||||
|
struct Candidate {
|
||||||
|
entry: DeviceEntry,
|
||||||
|
server: Option<u8>,
|
||||||
|
priority: u8,
|
||||||
|
endpoint: Option<(String, u32)>,
|
||||||
|
hdmi: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut candidates: Vec<Candidate> = Vec::new();
|
||||||
|
for device in raw {
|
||||||
|
let name = pretty_name(&device.name);
|
||||||
|
if device.id.is_empty() && name.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let class = if alsa {
|
||||||
|
classify_alsa(&device.id)
|
||||||
|
} else {
|
||||||
|
Class::Hardware(PRIORITY_SYSDEFAULT)
|
||||||
|
};
|
||||||
|
let (server, priority) = match class {
|
||||||
|
Class::Hidden => continue,
|
||||||
|
Class::Server(order) => (Some(order), PRIORITY_SYSDEFAULT),
|
||||||
|
Class::Hardware(priority) => (None, priority),
|
||||||
|
};
|
||||||
|
if server.is_none() && (name.is_empty() || (alsa && looks_like_plugin(&name))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (prefix, selector) = split_id(&device.id);
|
||||||
|
let label = match server {
|
||||||
|
Some(_) => server_label(&device.id).to_string(),
|
||||||
|
None => name,
|
||||||
|
};
|
||||||
|
candidates.push(Candidate {
|
||||||
|
entry: DeviceEntry {
|
||||||
|
id: device.id.clone(),
|
||||||
|
label,
|
||||||
|
},
|
||||||
|
server,
|
||||||
|
priority,
|
||||||
|
endpoint: selector.map(|(card, dev)| (card.to_string(), dev)),
|
||||||
|
hdmi: prefix == "hdmi",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// One entry per physical endpoint: the best alias wins. `hdmi:` endpoints are numbered in
|
||||||
|
// their own space, so they never collapse into `hw:` aliases of the same card.
|
||||||
|
let mut chosen: Vec<Candidate> = Vec::new();
|
||||||
|
for candidate in candidates {
|
||||||
|
let same = |other: &Candidate| {
|
||||||
|
candidate.server.is_some() && other.server == candidate.server
|
||||||
|
|| candidate.endpoint.is_some()
|
||||||
|
&& other.endpoint == candidate.endpoint
|
||||||
|
&& other.hdmi == candidate.hdmi
|
||||||
|
};
|
||||||
|
match chosen.iter().position(same) {
|
||||||
|
Some(index) if chosen[index].priority >= candidate.priority => {}
|
||||||
|
Some(index) => chosen[index] = candidate,
|
||||||
|
None => chosen.push(candidate),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Different ids may still read the same to a person (a card's HDMI jack listed as both
|
||||||
|
// `hdmi:` and `plughw:`); keep the preferred one.
|
||||||
|
let mut unique: Vec<Candidate> = Vec::new();
|
||||||
|
for candidate in chosen {
|
||||||
|
match unique
|
||||||
|
.iter()
|
||||||
|
.position(|other| other.entry.label == candidate.entry.label)
|
||||||
|
{
|
||||||
|
Some(index) if unique[index].priority >= candidate.priority => {}
|
||||||
|
Some(index) => unique[index] = candidate,
|
||||||
|
None => unique.push(candidate),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unique.sort_by(|a, b| match (a.server, b.server) {
|
||||||
|
(Some(x), Some(y)) => x.cmp(&y),
|
||||||
|
(Some(_), None) => Ordering::Less,
|
||||||
|
(None, Some(_)) => Ordering::Greater,
|
||||||
|
(None, None) => compare_labels(&a.entry.label, &b.entry.label),
|
||||||
|
});
|
||||||
|
unique.into_iter().map(|c| c.entry).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index into the UI list (0 is the system default) for a persisted device id.
|
||||||
|
/// Unknown or empty ids select the default, so a removed device never breaks audio.
|
||||||
|
pub fn index_for_id(entries: &[DeviceEntry], saved_id: &str) -> usize {
|
||||||
|
if saved_id.is_empty() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
entries
|
||||||
|
.iter()
|
||||||
|
.position(|entry| entry.id == saved_id)
|
||||||
|
.map_or(0, |position| position + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persisted id for a UI list index (0 is the system default and persists as empty).
|
||||||
|
pub fn id_for_index(entries: &[DeviceEntry], index: usize) -> String {
|
||||||
|
index
|
||||||
|
.checked_sub(1)
|
||||||
|
.and_then(|position| entries.get(position))
|
||||||
|
.map(|entry| entry.id.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps a selection saved by older versions (an index into the unfiltered, name-deduplicated
|
||||||
|
/// list with the default first) to a device id of the new list, matching by device name.
|
||||||
|
pub fn migrate_legacy_index(
|
||||||
|
legacy_names: &[String],
|
||||||
|
legacy_index: usize,
|
||||||
|
entries: &[DeviceEntry],
|
||||||
|
) -> String {
|
||||||
|
let Some(name) = legacy_index
|
||||||
|
.checked_sub(1)
|
||||||
|
.and_then(|position| legacy_names.get(position))
|
||||||
|
else {
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
let wanted = pretty_name(name);
|
||||||
|
entries
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.label == wanted)
|
||||||
|
.map(|entry| entry.id.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn raw(id: &str, name: &str) -> RawDevice {
|
||||||
|
RawDevice {
|
||||||
|
id: id.into(),
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn typical_alsa() -> Vec<RawDevice> {
|
||||||
|
vec![
|
||||||
|
raw(
|
||||||
|
"null",
|
||||||
|
"Discard all samples (playback) or generate zero samples (capture)",
|
||||||
|
),
|
||||||
|
raw(
|
||||||
|
"lavrate",
|
||||||
|
"Rate Converter Plugin Using Libav/FFmpeg Library",
|
||||||
|
),
|
||||||
|
raw(
|
||||||
|
"samplerate",
|
||||||
|
"Rate Converter Plugin Using Samplerate Library",
|
||||||
|
),
|
||||||
|
raw("speexrate", "Rate Converter Plugin Using Speex Resampler"),
|
||||||
|
raw("jack", "JACK Audio Connection Kit"),
|
||||||
|
raw("oss", "Open Sound System"),
|
||||||
|
raw("pipewire", "PipeWire Sound Server"),
|
||||||
|
raw("pulse", "PulseAudio Sound Server"),
|
||||||
|
raw(
|
||||||
|
"default",
|
||||||
|
"Default ALSA Output (currently PipeWire Media Server)",
|
||||||
|
),
|
||||||
|
raw("sysdefault", "Default Audio Device"),
|
||||||
|
raw("sysdefault:CARD=PCH", "HDA Intel PCH, ALC3254 Analog"),
|
||||||
|
raw("front:CARD=PCH,DEV=0", "HDA Intel PCH, ALC3254 Analog"),
|
||||||
|
raw("surround51:CARD=PCH,DEV=0", "HDA Intel PCH, ALC3254 Analog"),
|
||||||
|
raw("hdmi:CARD=NVidia,DEV=0", "HDA NVidia, HDMI 0"),
|
||||||
|
raw("dmix:CARD=PCH,DEV=0", "HDA Intel PCH, ALC3254 Analog"),
|
||||||
|
raw("usbstream:CARD=PCH", "HDA Intel PCH"),
|
||||||
|
raw("hw:CARD=PCH,DEV=0", "HDA Intel PCH, ALC3254 Analog"),
|
||||||
|
raw("plughw:CARD=PCH,DEV=0", "HDA Intel PCH, ALC3254 Analog"),
|
||||||
|
raw("hw:CARD=NVidia,DEV=3", "HDA NVidia, HDMI 0"),
|
||||||
|
raw("plughw:CARD=NVidia,DEV=3", "HDA NVidia, HDMI 0"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn labels(entries: &[DeviceEntry]) -> Vec<&str> {
|
||||||
|
entries.iter().map(|e| e.label.as_str()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pseudo_devices_are_removed_and_hardware_and_servers_stay() {
|
||||||
|
let entries = visible_devices(&typical_alsa(), true);
|
||||||
|
assert_eq!(
|
||||||
|
labels(&entries),
|
||||||
|
vec![
|
||||||
|
"PipeWire",
|
||||||
|
"PulseAudio",
|
||||||
|
"HDA Intel PCH, ALC3254 Analog",
|
||||||
|
"HDA NVidia, HDMI 0"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
for junk in ["Discard", "Rate Converter", "JACK", "Open Sound"] {
|
||||||
|
assert!(entries.iter().all(|e| !e.label.contains(junk)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn best_alias_of_each_endpoint_wins() {
|
||||||
|
let entries = visible_devices(&typical_alsa(), true);
|
||||||
|
let ids: Vec<_> = entries.iter().map(|e| e.id.as_str()).collect();
|
||||||
|
assert!(ids.contains(&"sysdefault:CARD=PCH"));
|
||||||
|
assert!(ids.contains(&"hdmi:CARD=NVidia,DEV=0"));
|
||||||
|
assert!(!ids.iter().any(|id| id.starts_with("hw:")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plughw_is_preferred_over_raw_hw_when_nothing_better_exists() {
|
||||||
|
let entries = visible_devices(
|
||||||
|
&[
|
||||||
|
raw("hw:CARD=USB,DEV=0", "Blue Yeti, USB Audio"),
|
||||||
|
raw("plughw:CARD=USB,DEV=0", "Blue Yeti, USB Audio"),
|
||||||
|
],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert_eq!(entries.len(), 1);
|
||||||
|
assert_eq!(entries[0].id, "plughw:CARD=USB,DEV=0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_descriptions_are_hidden_even_under_card_like_ids() {
|
||||||
|
let entries = visible_devices(
|
||||||
|
&[raw(
|
||||||
|
"hw:CARD=Weird,DEV=0",
|
||||||
|
"Rate Converter Plugin Using Foo",
|
||||||
|
)],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert!(entries.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn names_lose_technical_tails_and_extra_whitespace() {
|
||||||
|
assert_eq!(pretty_name(" Speakers (ALSA) "), "Speakers");
|
||||||
|
assert_eq!(pretty_name("Headset Mic"), "Headset Mic");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn other_backends_keep_real_devices_and_drop_empty_names() {
|
||||||
|
let entries = visible_devices(
|
||||||
|
&[
|
||||||
|
raw("{0.0.0}.{abc}", "Speakers (Realtek)"),
|
||||||
|
raw("{0.0.0}.{def}", ""),
|
||||||
|
raw("{0.0.0}.{ghi}", "Headphones"),
|
||||||
|
],
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert_eq!(labels(&entries), vec!["Headphones", "Speakers (Realtek)"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn list_is_sorted_case_insensitively_after_servers() {
|
||||||
|
let entries = visible_devices(
|
||||||
|
&[
|
||||||
|
raw("sysdefault:CARD=b", "beta card"),
|
||||||
|
raw("sysdefault:CARD=a", "Alpha card"),
|
||||||
|
raw("pulse", "PulseAudio Sound Server"),
|
||||||
|
],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
labels(&entries),
|
||||||
|
vec!["PulseAudio", "Alpha card", "beta card"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn saved_ids_resolve_to_indexes_and_back() {
|
||||||
|
let entries = visible_devices(&typical_alsa(), true);
|
||||||
|
let id = "sysdefault:CARD=PCH";
|
||||||
|
let index = index_for_id(&entries, id);
|
||||||
|
assert_eq!(index, 3);
|
||||||
|
assert_eq!(id_for_index(&entries, index), id);
|
||||||
|
assert_eq!(index_for_id(&entries, "hw:CARD=Gone,DEV=0"), 0);
|
||||||
|
assert_eq!(index_for_id(&entries, ""), 0);
|
||||||
|
assert_eq!(id_for_index(&entries, 0), "");
|
||||||
|
assert_eq!(id_for_index(&entries, 99), "");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_index_selection_migrates_by_name() {
|
||||||
|
let entries = visible_devices(&typical_alsa(), true);
|
||||||
|
let legacy = vec![
|
||||||
|
"Discard all samples (playback) or generate zero samples (capture)".to_string(),
|
||||||
|
"HDA Intel PCH, ALC3254 Analog".to_string(),
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
migrate_legacy_index(&legacy, 2, &entries),
|
||||||
|
"sysdefault:CARD=PCH"
|
||||||
|
);
|
||||||
|
// A legacy choice of a removed pseudo-device falls back to the default.
|
||||||
|
assert_eq!(migrate_legacy_index(&legacy, 1, &entries), "");
|
||||||
|
assert_eq!(migrate_legacy_index(&legacy, 0, &entries), "");
|
||||||
|
assert_eq!(migrate_legacy_index(&legacy, 9, &entries), "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,42 +1,22 @@
|
||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
use cpal::Device;
|
use cpal::Device;
|
||||||
use cpal::traits::{DeviceTrait, HostTrait};
|
use cpal::traits::HostTrait;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
pub fn input_at(index: usize) -> Result<Device> {
|
/// Opens the microphone with persisted id `id`; an empty id is the system default. A saved
|
||||||
|
/// device that has disappeared falls back to the default instead of failing the join.
|
||||||
|
pub fn open_input(id: &str) -> Result<Device> {
|
||||||
let host = cpal::default_host();
|
let host = cpal::default_host();
|
||||||
if index == 0 {
|
if !id.is_empty() {
|
||||||
return host
|
let alsa = super::is_alsa(&host);
|
||||||
.default_input_device()
|
if let Some(device) = super::find_by_id(host.input_devices()?, id, alsa) {
|
||||||
.ok_or_else(|| anyhow!("no default input device"));
|
return Ok(device);
|
||||||
}
|
|
||||||
|
|
||||||
let devices: Vec<Device> = host.input_devices()?.collect();
|
|
||||||
|
|
||||||
let mut names: Vec<String> = Vec::new();
|
|
||||||
for dev in &devices {
|
|
||||||
if let Ok(name) = dev.description().map(|d| d.name().to_string())
|
|
||||||
&& !name.is_empty()
|
|
||||||
&& !names.contains(&name)
|
|
||||||
{
|
|
||||||
names.push(name);
|
|
||||||
}
|
}
|
||||||
|
warn!(
|
||||||
|
device = id,
|
||||||
|
"saved input device not found, using the system default"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
host.default_input_device()
|
||||||
let name = names
|
.ok_or_else(|| anyhow!("no default input device"))
|
||||||
.get(index.saturating_sub(1))
|
|
||||||
.ok_or_else(|| anyhow!("input device index {index} out of range"))?;
|
|
||||||
|
|
||||||
for dev in devices {
|
|
||||||
if dev
|
|
||||||
.description()
|
|
||||||
.map(|d| d.name().to_string())
|
|
||||||
.ok()
|
|
||||||
.as_deref()
|
|
||||||
== Some(name.as_str())
|
|
||||||
{
|
|
||||||
return Ok(dev);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(anyhow!("input device not found: {name}"))
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,120 +1,143 @@
|
||||||
|
//! Audio device enumeration and opening.
|
||||||
|
//!
|
||||||
|
//! The picker shows "System default" followed by the filtered endpoints from
|
||||||
|
//! [`filter::visible_devices`]. Selections are persisted by stable device id, never by list
|
||||||
|
//! position, so changing the filter or plugging hardware does not move a saved choice.
|
||||||
|
|
||||||
|
pub mod filter;
|
||||||
mod input;
|
mod input;
|
||||||
mod output;
|
mod output;
|
||||||
|
|
||||||
pub use input::input_at;
|
pub use filter::{DeviceEntry, RawDevice};
|
||||||
pub use output::output_at;
|
pub use input::open_input;
|
||||||
|
pub use output::open_output;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use cpal::traits::{DeviceTrait, HostTrait};
|
use cpal::traits::{DeviceTrait, HostTrait};
|
||||||
|
|
||||||
const DEFAULT_LABEL: &str = "Default";
|
/// Label of the first picker entry, translated by the UI layer.
|
||||||
|
pub const DEFAULT_LABEL: &str = "System default";
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
/// Devices offered to the user, filtered and sorted. The system default is implicit and is
|
||||||
pub struct DeviceLabel {
|
/// always position 0 in the UI list, so UI index `n` refers to `entries[n - 1]`.
|
||||||
pub display: String,
|
#[derive(Debug, Default, Clone)]
|
||||||
pub raw_name: String,
|
|
||||||
pub host_api: String,
|
|
||||||
pub channels: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct DeviceLists {
|
pub struct DeviceLists {
|
||||||
pub input_labels: Vec<String>,
|
pub input: Vec<DeviceEntry>,
|
||||||
pub output_labels: Vec<String>,
|
pub output: Vec<DeviceEntry>,
|
||||||
pub input_devices: Vec<DeviceLabel>,
|
|
||||||
pub output_devices: Vec<DeviceLabel>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn enumerate() -> Result<DeviceLists> {
|
impl DeviceLists {
|
||||||
let host = cpal::default_host();
|
/// Picker labels with the system default first.
|
||||||
let host_api = host.id().name().to_string();
|
pub fn input_labels(&self) -> Vec<String> {
|
||||||
let (input_labels, input_devices) = list_labels(host.input_devices()?, &host_api);
|
labels(&self.input)
|
||||||
let (output_labels, output_devices) = list_labels(host.output_devices()?, &host_api);
|
}
|
||||||
Ok(DeviceLists {
|
|
||||||
input_labels,
|
/// Picker labels with the system default first.
|
||||||
output_labels,
|
pub fn output_labels(&self) -> Vec<String> {
|
||||||
input_devices,
|
labels(&self.output)
|
||||||
output_devices,
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn labels(entries: &[DeviceEntry]) -> Vec<String> {
|
||||||
|
std::iter::once(DEFAULT_LABEL.to_string())
|
||||||
|
.chain(entries.iter().map(|entry| entry.label.clone()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_alsa(host: &cpal::Host) -> bool {
|
||||||
|
host.id().name().eq_ignore_ascii_case("alsa")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Raw identifier and display name for one device, or `None` when it cannot be described.
|
||||||
|
pub(crate) fn raw_device(device: &cpal::Device, alsa: bool) -> Option<RawDevice> {
|
||||||
|
let description = device.description().ok()?;
|
||||||
|
let id = if alsa {
|
||||||
|
description.driver().map(str::to_owned)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
.or_else(|| device.id().ok().map(|id| id.to_string()))?;
|
||||||
|
Some(RawDevice {
|
||||||
|
id,
|
||||||
|
name: description.name().to_string(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_labels(
|
/// Lists the visible input and output devices of the default host.
|
||||||
devices: impl Iterator<Item = cpal::Device>,
|
pub fn enumerate() -> Result<DeviceLists> {
|
||||||
host_api: &str,
|
let host = cpal::default_host();
|
||||||
) -> (Vec<String>, Vec<DeviceLabel>) {
|
let alsa = is_alsa(&host);
|
||||||
let mut labels = vec![DEFAULT_LABEL.into()];
|
let collect = |devices: Vec<cpal::Device>| {
|
||||||
let mut metadatas = vec![DeviceLabel {
|
let raw: Vec<RawDevice> = devices
|
||||||
display: DEFAULT_LABEL.into(),
|
.iter()
|
||||||
raw_name: String::new(),
|
.filter_map(|device| raw_device(device, alsa))
|
||||||
host_api: host_api.into(),
|
.collect();
|
||||||
channels: 0,
|
filter::visible_devices(&raw, alsa)
|
||||||
}];
|
};
|
||||||
for dev in devices {
|
Ok(DeviceLists {
|
||||||
let Ok(name) = dev.description().map(|d| d.name().to_string()) else {
|
input: collect(host.input_devices()?.collect()),
|
||||||
continue;
|
output: collect(host.output_devices()?.collect()),
|
||||||
};
|
})
|
||||||
if name.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let channels = supported_channel_count(&dev);
|
|
||||||
let display = format!("{} ({})", name, host_api);
|
|
||||||
if metadatas.iter().any(|m| m.raw_name == name) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
labels.push(display.clone());
|
|
||||||
metadatas.push(DeviceLabel {
|
|
||||||
display,
|
|
||||||
raw_name: name,
|
|
||||||
host_api: host_api.into(),
|
|
||||||
channels,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
(labels, metadatas)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn supported_channel_count(dev: &cpal::Device) -> u16 {
|
/// Names of the devices in the order older versions listed them (default excluded, names
|
||||||
if let Ok(cfg) = dev.default_input_config() {
|
/// deduplicated). Only used to translate a legacy saved index to a device id.
|
||||||
return cfg.channels();
|
pub fn legacy_names(input: bool) -> Vec<String> {
|
||||||
|
let host = cpal::default_host();
|
||||||
|
let devices: Vec<cpal::Device> = if input {
|
||||||
|
host.input_devices().map(Iterator::collect)
|
||||||
|
} else {
|
||||||
|
host.output_devices().map(Iterator::collect)
|
||||||
}
|
}
|
||||||
if let Ok(cfg) = dev.default_output_config() {
|
.unwrap_or_default();
|
||||||
return cfg.channels();
|
let mut names: Vec<String> = Vec::new();
|
||||||
|
for device in &devices {
|
||||||
|
if let Ok(name) = device.description().map(|d| d.name().to_string())
|
||||||
|
&& !name.is_empty()
|
||||||
|
&& !names.contains(&name)
|
||||||
|
{
|
||||||
|
names.push(name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if let Ok(configs) = dev.supported_input_configs()
|
names
|
||||||
&& let Some(cfg) = configs.into_iter().next()
|
}
|
||||||
{
|
|
||||||
return cfg.channels();
|
/// Finds the device with `id` among `devices`, or `None` when it is gone.
|
||||||
}
|
pub(crate) fn find_by_id(
|
||||||
if let Ok(configs) = dev.supported_output_configs()
|
devices: impl Iterator<Item = cpal::Device>,
|
||||||
&& let Some(cfg) = configs.into_iter().next()
|
id: &str,
|
||||||
{
|
alsa: bool,
|
||||||
return cfg.channels();
|
) -> Option<cpal::Device> {
|
||||||
}
|
devices
|
||||||
0
|
.into_iter()
|
||||||
|
.find(|device| raw_device(device, alsa).is_some_and(|raw| raw.id == id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Human readable name of a device for logs and diagnostics.
|
||||||
|
pub fn device_name(device: &cpal::Device) -> String {
|
||||||
|
device
|
||||||
|
.description()
|
||||||
|
.map(|d| d.name().to_owned())
|
||||||
|
.unwrap_or_else(|_| "unknown device".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn default_is_first_label() {
|
fn picker_labels_start_with_the_system_default() {
|
||||||
let lists = enumerate().unwrap_or_default();
|
let lists = DeviceLists {
|
||||||
if !lists.input_labels.is_empty() {
|
input: vec![DeviceEntry {
|
||||||
assert_eq!(lists.input_labels[0], "Default");
|
id: "sysdefault:CARD=PCH".into(),
|
||||||
}
|
label: "HDA Intel PCH".into(),
|
||||||
if !lists.output_labels.is_empty() {
|
}],
|
||||||
assert_eq!(lists.output_labels[0], "Default");
|
output: Vec::new(),
|
||||||
}
|
};
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn default_meta_is_sentinel() {
|
|
||||||
let lists = enumerate().unwrap_or_default();
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
lists.input_devices.first().map(|m| m.raw_name.as_str()),
|
lists.input_labels(),
|
||||||
Some("")
|
vec!["System default", "HDA Intel PCH"]
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
lists.output_devices.first().map(|m| m.raw_name.as_str()),
|
|
||||||
Some("")
|
|
||||||
);
|
);
|
||||||
|
assert_eq!(lists.output_labels(), vec!["System default"]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,22 @@
|
||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
use cpal::Device;
|
use cpal::Device;
|
||||||
use cpal::traits::{DeviceTrait, HostTrait};
|
use cpal::traits::HostTrait;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
pub fn output_at(index: usize) -> Result<Device> {
|
/// Opens the output with persisted id `id`; an empty id is the system default. A saved
|
||||||
|
/// device that has disappeared falls back to the default instead of failing the join.
|
||||||
|
pub fn open_output(id: &str) -> Result<Device> {
|
||||||
let host = cpal::default_host();
|
let host = cpal::default_host();
|
||||||
if index == 0 {
|
if !id.is_empty() {
|
||||||
return host
|
let alsa = super::is_alsa(&host);
|
||||||
.default_output_device()
|
if let Some(device) = super::find_by_id(host.output_devices()?, id, alsa) {
|
||||||
.ok_or_else(|| anyhow!("no default output device"));
|
return Ok(device);
|
||||||
}
|
|
||||||
|
|
||||||
let devices: Vec<Device> = host.output_devices()?.collect();
|
|
||||||
|
|
||||||
let mut names: Vec<String> = Vec::new();
|
|
||||||
for dev in &devices {
|
|
||||||
if let Ok(name) = dev.description().map(|d| d.name().to_string())
|
|
||||||
&& !name.is_empty()
|
|
||||||
&& !names.contains(&name)
|
|
||||||
{
|
|
||||||
names.push(name);
|
|
||||||
}
|
}
|
||||||
|
warn!(
|
||||||
|
device = id,
|
||||||
|
"saved output device not found, using the system default"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
host.default_output_device()
|
||||||
let name = names
|
.ok_or_else(|| anyhow!("no default output device"))
|
||||||
.get(index.saturating_sub(1))
|
|
||||||
.ok_or_else(|| anyhow!("output device index {index} out of range"))?;
|
|
||||||
|
|
||||||
for dev in devices {
|
|
||||||
if dev
|
|
||||||
.description()
|
|
||||||
.map(|d| d.name().to_string())
|
|
||||||
.ok()
|
|
||||||
.as_deref()
|
|
||||||
== Some(name.as_str())
|
|
||||||
{
|
|
||||||
return Ok(dev);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(anyhow!("output device not found: {name}"))
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ pub mod devices;
|
||||||
mod pipeline;
|
mod pipeline;
|
||||||
mod processing;
|
mod processing;
|
||||||
|
|
||||||
pub use devices::{DeviceLabel, DeviceLists};
|
pub use devices::{DeviceEntry, DeviceLists};
|
||||||
pub use pipeline::JitterConfig;
|
pub use pipeline::JitterConfig;
|
||||||
pub use pipeline::{AudioPipeline, MediaMixer};
|
pub use pipeline::{AudioPipeline, MediaMixer};
|
||||||
pub use processing::{DenoiseState, TransmitGate};
|
pub use processing::{DenoiseState, TransmitGate};
|
||||||
|
|
@ -25,8 +25,10 @@ pub struct AudioSync {
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct PipelineConfig {
|
pub struct PipelineConfig {
|
||||||
pub channel_key: u64,
|
pub channel_key: u64,
|
||||||
pub mic_device_index: usize,
|
/// Persisted microphone id; empty is the system default.
|
||||||
pub output_device_index: usize,
|
pub mic_device_id: String,
|
||||||
|
/// Persisted output device id; empty is the system default.
|
||||||
|
pub output_device_id: String,
|
||||||
pub voice_bitrate_kbps: f32,
|
pub voice_bitrate_kbps: f32,
|
||||||
pub packet_interval: usize,
|
pub packet_interval: usize,
|
||||||
}
|
}
|
||||||
|
|
@ -34,8 +36,8 @@ pub struct PipelineConfig {
|
||||||
impl PartialEq for PipelineConfig {
|
impl PartialEq for PipelineConfig {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
self.channel_key == other.channel_key
|
self.channel_key == other.channel_key
|
||||||
&& self.mic_device_index == other.mic_device_index
|
&& self.mic_device_id == other.mic_device_id
|
||||||
&& self.output_device_index == other.output_device_index
|
&& self.output_device_id == other.output_device_id
|
||||||
&& self.packet_interval == other.packet_interval
|
&& self.packet_interval == other.packet_interval
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ mod media;
|
||||||
pub use media::MediaMixer;
|
pub use media::MediaMixer;
|
||||||
mod playback;
|
mod playback;
|
||||||
|
|
||||||
use cpal::traits::DeviceTrait;
|
|
||||||
use std::sync::{
|
use std::sync::{
|
||||||
Arc, Mutex,
|
Arc, Mutex,
|
||||||
atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
|
atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
|
||||||
|
|
@ -110,18 +109,12 @@ impl AudioPipeline {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(cfg: PipelineConfig) -> anyhow::Result<AudioPipeline> {
|
pub fn start(cfg: PipelineConfig) -> anyhow::Result<AudioPipeline> {
|
||||||
let input = devices::input_at(cfg.mic_device_index)?;
|
let input = devices::open_input(&cfg.mic_device_id)?;
|
||||||
let output = devices::output_at(cfg.output_device_index)?;
|
let output = devices::open_output(&cfg.output_device_id)?;
|
||||||
info!(
|
info!(
|
||||||
"audio in: {} out: {}",
|
"audio in: {} out: {}",
|
||||||
input
|
devices::device_name(&input),
|
||||||
.description()
|
devices::device_name(&output)
|
||||||
.map(|d| d.name().to_owned())
|
|
||||||
.unwrap_or_default(),
|
|
||||||
output
|
|
||||||
.description()
|
|
||||||
.map(|d| d.name().to_owned())
|
|
||||||
.unwrap_or_default()
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let in_cfg = config::AudioConfig::find(&input, true)?;
|
let in_cfg = config::AudioConfig::find(&input, true)?;
|
||||||
|
|
|
||||||
40
src/main.rs
40
src/main.rs
|
|
@ -69,7 +69,7 @@ fn main() -> Result<()> {
|
||||||
}
|
}
|
||||||
let window = MainWindow::new()?;
|
let window = MainWindow::new()?;
|
||||||
window.set_address_input(state.borrow().ui.connect_input.as_str().into());
|
window.set_address_input(state.borrow().ui.connect_input.as_str().into());
|
||||||
refresh_devices(&window);
|
refresh_devices(&window, &mut state.borrow_mut().ui);
|
||||||
|
|
||||||
let webhook_net = state.borrow().net.clone();
|
let webhook_net = state.borrow().net.clone();
|
||||||
state.borrow_mut().webhooks = Some(Rc::new(ui::webhooks::WebhookUi::new(Rc::new(
|
state.borrow_mut().webhooks = Some(Rc::new(ui::webhooks::WebhookUi::new(Rc::new(
|
||||||
|
|
@ -144,22 +144,27 @@ fn load_identity() -> Result<Option<identity::Identity>> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refresh_devices(window: &MainWindow) {
|
fn refresh_devices(window: &MainWindow, ui: &mut UiState) {
|
||||||
let devices = vnox_client::audio::devices::enumerate().unwrap_or_default();
|
crate::ui::devices::refresh(ui);
|
||||||
let model = |mut items: Vec<String>| {
|
let model = |items: Vec<String>| {
|
||||||
if items.is_empty() {
|
|
||||||
items.push(crate::ui::i18n::text("Default"));
|
|
||||||
}
|
|
||||||
Rc::new(slint::VecModel::from(
|
Rc::new(slint::VecModel::from(
|
||||||
items
|
items
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(slint::SharedString::from)
|
.enumerate()
|
||||||
|
.map(|(index, label)| {
|
||||||
|
// Position 0 is always the system default.
|
||||||
|
slint::SharedString::from(if index == 0 {
|
||||||
|
crate::ui::i18n::text("System default")
|
||||||
|
} else {
|
||||||
|
label
|
||||||
|
})
|
||||||
|
})
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
))
|
))
|
||||||
.into()
|
.into()
|
||||||
};
|
};
|
||||||
window.set_input_devices(model(devices.input_labels));
|
window.set_input_devices(model(ui.device_lists.input_labels()));
|
||||||
window.set_output_devices(model(devices.output_labels));
|
window.set_output_devices(model(ui.device_lists.output_labels()));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
|
fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
|
||||||
|
|
@ -220,9 +225,10 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
|
||||||
let state = state.clone();
|
let state = state.clone();
|
||||||
let weak = window.as_weak();
|
let weak = window.as_weak();
|
||||||
window.on_open_settings(move || {
|
window.on_open_settings(move || {
|
||||||
state.borrow_mut().ui.settings_open = true;
|
let mut s = state.borrow_mut();
|
||||||
|
s.ui.settings_open = true;
|
||||||
if let Some(window) = weak.upgrade() {
|
if let Some(window) = weak.upgrade() {
|
||||||
refresh_devices(&window);
|
refresh_devices(&window, &mut s.ui);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -242,10 +248,14 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
|
||||||
let state = state.clone();
|
let state = state.clone();
|
||||||
window.on_audio_settings_changed(move |input, output, bitrate, mode, volume| {
|
window.on_audio_settings_changed(move |input, output, bitrate, mode, volume| {
|
||||||
let mut s = state.borrow_mut();
|
let mut s = state.borrow_mut();
|
||||||
s.ui.mic_device = input.max(0) as usize;
|
crate::ui::devices::select(&mut s.ui, input.max(0) as usize, output.max(0) as usize);
|
||||||
s.ui.output_device = output.max(0) as usize;
|
|
||||||
s.ui.voice_bitrate = bitrate.clamp(8.0, 128.0);
|
s.ui.voice_bitrate = bitrate.clamp(8.0, 128.0);
|
||||||
s.ui.vad_mode = mode.clamp(0, 2) as usize;
|
let mode = mode.clamp(0, 2) as usize;
|
||||||
|
if mode != s.ui.vad_mode {
|
||||||
|
// Only a real change counts as the person's own choice.
|
||||||
|
s.ui.vad_mode_chosen = true;
|
||||||
|
}
|
||||||
|
s.ui.vad_mode = mode;
|
||||||
s.ui.output_volume = volume.clamp(0.0, 100.0);
|
s.ui.output_volume = volume.clamp(0.0, 100.0);
|
||||||
if let Err(error) = crate::ui::preferences::save(&s.ui) {
|
if let Err(error) = crate::ui::preferences::save(&s.ui) {
|
||||||
s.ui.status_msg = Some(ui::i18n::Message::with(
|
s.ui.status_msg = Some(ui::i18n::Message::with(
|
||||||
|
|
|
||||||
69
src/ui/devices.rs
Normal file
69
src/ui/devices.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
//! Bridges the persisted device ids and the positions of the settings pickers.
|
||||||
|
use vnox_client::audio::devices::{self, filter};
|
||||||
|
|
||||||
|
use super::state::UiState;
|
||||||
|
|
||||||
|
/// Recomputes the picker positions from the persisted ids and the last enumeration.
|
||||||
|
pub fn sync_indexes(ui: &mut UiState) {
|
||||||
|
ui.mic_device = filter::index_for_id(&ui.device_lists.input, &ui.mic_device_id);
|
||||||
|
ui.output_device = filter::index_for_id(&ui.device_lists.output, &ui.output_device_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enumerates devices again (hardware may have changed) and keeps the saved choices.
|
||||||
|
pub fn refresh(ui: &mut UiState) {
|
||||||
|
match devices::enumerate() {
|
||||||
|
Ok(lists) => ui.device_lists = lists,
|
||||||
|
Err(error) => tracing::warn!(%error, "cannot enumerate audio devices"),
|
||||||
|
}
|
||||||
|
sync_indexes(ui);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies picker positions chosen by the person, storing the matching stable ids.
|
||||||
|
pub fn select(ui: &mut UiState, input_index: usize, output_index: usize) {
|
||||||
|
ui.mic_device_id = filter::id_for_index(&ui.device_lists.input, input_index);
|
||||||
|
ui.output_device_id = filter::id_for_index(&ui.device_lists.output, output_index);
|
||||||
|
sync_indexes(ui);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use vnox_client::audio::devices::{DeviceEntry, DeviceLists};
|
||||||
|
|
||||||
|
fn entry(id: &str, label: &str) -> DeviceEntry {
|
||||||
|
DeviceEntry {
|
||||||
|
id: id.into(),
|
||||||
|
label: label.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state() -> UiState {
|
||||||
|
UiState {
|
||||||
|
device_lists: DeviceLists {
|
||||||
|
input: vec![entry("a", "Mic A"), entry("b", "Mic B")],
|
||||||
|
output: vec![entry("x", "Out X")],
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn selection_is_stored_by_id_and_survives_list_changes() {
|
||||||
|
let mut ui = state();
|
||||||
|
select(&mut ui, 2, 1);
|
||||||
|
assert_eq!((ui.mic_device_id.as_str(), ui.mic_device), ("b", 2));
|
||||||
|
assert_eq!((ui.output_device_id.as_str(), ui.output_device), ("x", 1));
|
||||||
|
// A new device appears before the saved one; the choice follows the id.
|
||||||
|
ui.device_lists.input.insert(0, entry("new", "Aaa"));
|
||||||
|
sync_indexes(&mut ui);
|
||||||
|
assert_eq!(ui.mic_device, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_device_falls_back_to_default_position() {
|
||||||
|
let mut ui = state();
|
||||||
|
ui.mic_device_id = "unplugged".into();
|
||||||
|
sync_indexes(&mut ui);
|
||||||
|
assert_eq!(ui.mic_device, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
pub mod appearance;
|
pub mod appearance;
|
||||||
pub mod avatar;
|
pub mod avatar;
|
||||||
pub mod bridge;
|
pub mod bridge;
|
||||||
|
pub mod devices;
|
||||||
pub mod i18n;
|
pub mod i18n;
|
||||||
pub mod media;
|
pub mod media;
|
||||||
pub mod preferences;
|
pub mod preferences;
|
||||||
|
|
|
||||||
|
|
@ -2,15 +2,25 @@ use std::path::PathBuf;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::state::UiState;
|
use super::state::{DEFAULT_VOICE_MODE, UiState};
|
||||||
|
use vnox_client::audio::devices::{self, filter};
|
||||||
|
|
||||||
#[derive(Default, Serialize, Deserialize)]
|
#[derive(Default, Serialize, Deserialize)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
struct AudioPreferences {
|
struct AudioPreferences {
|
||||||
|
/// Legacy position in the old, unfiltered device list. Read only to migrate.
|
||||||
input_device: usize,
|
input_device: usize,
|
||||||
|
/// Legacy position in the old, unfiltered device list. Read only to migrate.
|
||||||
output_device: usize,
|
output_device: usize,
|
||||||
|
/// Stable id of the chosen microphone; empty or missing is the system default.
|
||||||
|
input_device_id: Option<String>,
|
||||||
|
/// Stable id of the chosen output; empty or missing is the system default.
|
||||||
|
output_device_id: Option<String>,
|
||||||
bitrate: Option<f32>,
|
bitrate: Option<f32>,
|
||||||
mode: usize,
|
mode: usize,
|
||||||
|
/// True once the person picked the voice input mode. Files from older versions lack it and
|
||||||
|
/// stored `mode: 0` for everybody, so an unmarked push-to-talk is not a real choice.
|
||||||
|
mode_chosen: bool,
|
||||||
volume: Option<f32>,
|
volume: Option<f32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -20,17 +30,42 @@ fn path() -> PathBuf {
|
||||||
.join("vnox/audio.json")
|
.join("vnox/audio.json")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolves the voice mode to use: an explicit choice is kept, and so is any non-default mode
|
||||||
|
/// written by older versions (those could only come from the person), but a legacy file that
|
||||||
|
/// merely records the old push-to-talk default becomes voice activation.
|
||||||
|
fn resolve_mode(prefs: &AudioPreferences) -> (usize, bool) {
|
||||||
|
let stored = prefs.mode.min(2);
|
||||||
|
if prefs.mode_chosen || stored != 0 {
|
||||||
|
(stored, true)
|
||||||
|
} else {
|
||||||
|
(DEFAULT_VOICE_MODE, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn load(state: &mut UiState) {
|
pub fn load(state: &mut UiState) {
|
||||||
let Ok(text) = std::fs::read_to_string(path()) else {
|
let prefs = std::fs::read_to_string(path())
|
||||||
return;
|
.ok()
|
||||||
};
|
.and_then(|text| serde_json::from_str::<AudioPreferences>(&text).ok())
|
||||||
let Ok(prefs) = serde_json::from_str::<AudioPreferences>(&text) else {
|
.unwrap_or_default();
|
||||||
return;
|
let lists = devices::enumerate().unwrap_or_default();
|
||||||
};
|
state.mic_device_id = prefs.input_device_id.clone().unwrap_or_else(|| {
|
||||||
state.mic_device = prefs.input_device;
|
filter::migrate_legacy_index(
|
||||||
state.output_device = prefs.output_device;
|
&devices::legacy_names(true),
|
||||||
|
prefs.input_device,
|
||||||
|
&lists.input,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
state.output_device_id = prefs.output_device_id.clone().unwrap_or_else(|| {
|
||||||
|
filter::migrate_legacy_index(
|
||||||
|
&devices::legacy_names(false),
|
||||||
|
prefs.output_device,
|
||||||
|
&lists.output,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
state.device_lists = lists;
|
||||||
|
super::devices::sync_indexes(state);
|
||||||
state.voice_bitrate = prefs.bitrate.unwrap_or(64.0).clamp(8.0, 128.0);
|
state.voice_bitrate = prefs.bitrate.unwrap_or(64.0).clamp(8.0, 128.0);
|
||||||
state.vad_mode = prefs.mode.min(2);
|
(state.vad_mode, state.vad_mode_chosen) = resolve_mode(&prefs);
|
||||||
state.output_volume = prefs.volume.unwrap_or(90.0).clamp(0.0, 100.0);
|
state.output_volume = prefs.volume.unwrap_or(90.0).clamp(0.0, 100.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -40,12 +75,52 @@ pub fn save(state: &UiState) -> anyhow::Result<()> {
|
||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
let preferences = AudioPreferences {
|
let preferences = AudioPreferences {
|
||||||
input_device: state.mic_device,
|
input_device: 0,
|
||||||
output_device: state.output_device,
|
output_device: 0,
|
||||||
|
input_device_id: Some(state.mic_device_id.clone()),
|
||||||
|
output_device_id: Some(state.output_device_id.clone()),
|
||||||
bitrate: Some(state.voice_bitrate),
|
bitrate: Some(state.voice_bitrate),
|
||||||
mode: state.vad_mode,
|
mode: state.vad_mode,
|
||||||
|
mode_chosen: state.vad_mode_chosen,
|
||||||
volume: Some(state.output_volume),
|
volume: Some(state.output_volume),
|
||||||
};
|
};
|
||||||
std::fs::write(path, serde_json::to_vec_pretty(&preferences)?)?;
|
std::fs::write(path, serde_json::to_vec_pretty(&preferences)?)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn parse(text: &str) -> AudioPreferences {
|
||||||
|
serde_json::from_str(text).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fresh_profile_uses_voice_activation() {
|
||||||
|
assert_eq!(resolve_mode(&parse("{}")), (1, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_push_to_talk_default_becomes_voice_activation() {
|
||||||
|
assert_eq!(
|
||||||
|
resolve_mode(&parse(r#"{"mode":0,"volume":50.0}"#)),
|
||||||
|
(1, false)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_push_to_talk_is_kept() {
|
||||||
|
assert_eq!(
|
||||||
|
resolve_mode(&parse(r#"{"mode":0,"mode_chosen":true}"#)),
|
||||||
|
(0, true)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_non_default_modes_are_kept() {
|
||||||
|
assert_eq!(resolve_mode(&parse(r#"{"mode":1}"#)), (1, true));
|
||||||
|
assert_eq!(resolve_mode(&parse(r#"{"mode":2}"#)), (2, true));
|
||||||
|
assert_eq!(resolve_mode(&parse(r#"{"mode":9}"#)), (2, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -82,7 +82,7 @@ export component MainWindow inherits Window {
|
||||||
in-out property <string> voice-input-device: "";
|
in-out property <string> voice-input-device: "";
|
||||||
in-out property <string> voice-output-device: "";
|
in-out property <string> voice-output-device: "";
|
||||||
in-out property <float> voice-bitrate: 64.0;
|
in-out property <float> voice-bitrate: 64.0;
|
||||||
in-out property <int> vad-mode: 0;
|
in-out property <int> vad-mode: 1;
|
||||||
in-out property <float> volume: 100.0;
|
in-out property <float> volume: 100.0;
|
||||||
in-out property <string> language-choice: "system";
|
in-out property <string> language-choice: "system";
|
||||||
callback language-selected(string);
|
callback language-selected(string);
|
||||||
|
|
|
||||||
|
|
@ -33,13 +33,17 @@ impl Default for UiState {
|
||||||
mic_enabled: true,
|
mic_enabled: true,
|
||||||
ptt_held: false,
|
ptt_held: false,
|
||||||
deafen: false,
|
deafen: false,
|
||||||
vad_mode: 0,
|
vad_mode: crate::ui::state::DEFAULT_VOICE_MODE,
|
||||||
voice_bitrate: 64.0,
|
voice_bitrate: 64.0,
|
||||||
packet_interval: 1,
|
packet_interval: 1,
|
||||||
mic_device: 0,
|
mic_device: 0,
|
||||||
|
mic_device_id: String::new(),
|
||||||
|
|
||||||
output_device: 0,
|
output_device: 0,
|
||||||
|
output_device_id: String::new(),
|
||||||
output_volume: 90.0,
|
output_volume: 90.0,
|
||||||
|
device_lists: Default::default(),
|
||||||
|
vad_mode_chosen: false,
|
||||||
|
|
||||||
auto_reconnect: true,
|
auto_reconnect: true,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,9 @@ pub use types::{ConnState, TrustPrompt, TrustPromptKind, UiState, VoiceUiState};
|
||||||
|
|
||||||
use models::bookmark_label_from_address;
|
use models::bookmark_label_from_address;
|
||||||
|
|
||||||
|
/// Voice input mode of a fresh profile: 0 push to talk, 1 voice activation, 2 open microphone.
|
||||||
|
pub const DEFAULT_VOICE_MODE: usize = 1;
|
||||||
|
|
||||||
impl UiState {
|
impl UiState {
|
||||||
pub fn remove_bookmark(&mut self, index: usize) {
|
pub fn remove_bookmark(&mut self, index: usize) {
|
||||||
if index < self.bookmarks.len() {
|
if index < self.bookmarks.len() {
|
||||||
|
|
|
||||||
|
|
@ -77,10 +77,20 @@ pub struct UiState {
|
||||||
pub vad_mode: usize,
|
pub vad_mode: usize,
|
||||||
pub voice_bitrate: f32,
|
pub voice_bitrate: f32,
|
||||||
pub packet_interval: usize,
|
pub packet_interval: usize,
|
||||||
|
/// Picker position of the microphone (0 is the system default).
|
||||||
pub mic_device: usize,
|
pub mic_device: usize,
|
||||||
|
/// Persisted microphone id; empty is the system default.
|
||||||
|
pub mic_device_id: String,
|
||||||
|
|
||||||
|
/// Picker position of the output device (0 is the system default).
|
||||||
pub output_device: usize,
|
pub output_device: usize,
|
||||||
|
/// Persisted output device id; empty is the system default.
|
||||||
|
pub output_device_id: String,
|
||||||
pub output_volume: f32,
|
pub output_volume: f32,
|
||||||
|
/// Devices behind the picker positions, as of the last enumeration.
|
||||||
|
pub device_lists: vnox_client::audio::DeviceLists,
|
||||||
|
/// True once the person picked a voice input mode themselves.
|
||||||
|
pub vad_mode_chosen: bool,
|
||||||
|
|
||||||
pub auto_reconnect: bool,
|
pub auto_reconnect: bool,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -865,8 +865,8 @@ fn status_handle(ui: &mut UiState, _net: &NetHandle, event: NetEvent) {
|
||||||
pub fn pipeline_config(channel_id: &str, state: &AppState) -> PipelineConfig {
|
pub fn pipeline_config(channel_id: &str, state: &AppState) -> PipelineConfig {
|
||||||
PipelineConfig {
|
PipelineConfig {
|
||||||
channel_key: vnox_client::net::voice::channel_key(channel_id),
|
channel_key: vnox_client::net::voice::channel_key(channel_id),
|
||||||
mic_device_index: state.ui.mic_device,
|
mic_device_id: state.ui.mic_device_id.clone(),
|
||||||
output_device_index: state.ui.output_device,
|
output_device_id: state.ui.output_device_id.clone(),
|
||||||
voice_bitrate_kbps: state.ui.voice_bitrate,
|
voice_bitrate_kbps: state.ui.voice_bitrate,
|
||||||
packet_interval: state.ui.packet_interval,
|
packet_interval: state.ui.packet_interval,
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -230,6 +230,7 @@
|
||||||
"Idle": "Нет на месте",
|
"Idle": "Нет на месте",
|
||||||
"Do not disturb": "Не беспокоить",
|
"Do not disturb": "Не беспокоить",
|
||||||
"Default": "По умолчанию",
|
"Default": "По умолчанию",
|
||||||
|
"System default": "По умолчанию (системное)",
|
||||||
"Reply to {}": "Ответ {}",
|
"Reply to {}": "Ответ {}",
|
||||||
"Members — {}": "Участники — {}",
|
"Members — {}": "Участники — {}",
|
||||||
"Zoom {}%": "Масштаб {}%",
|
"Zoom {}%": "Масштаб {}%",
|
||||||
|
|
|
||||||
|
|
@ -543,7 +543,7 @@ msgid "Stop watching"
|
||||||
msgstr "Закрыть просмотр"
|
msgstr "Закрыть просмотр"
|
||||||
|
|
||||||
msgid "System default"
|
msgid "System default"
|
||||||
msgstr "Как в системе"
|
msgstr "По умолчанию (системное)"
|
||||||
|
|
||||||
msgid "System output"
|
msgid "System output"
|
||||||
msgstr "Системный звук"
|
msgstr "Системный звук"
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue