Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 120 additions & 13 deletions crates/mediad/src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,17 @@
//! 440 Hz tone (`tone:550` another pitch, so two tones in one mix cannot cancel), `onset` hears that tone once a second, each time led in by 40 ms too quiet to
//! count as speech, `unplugged` is a machine with no microphone at all, and none of them opens a
//! device. `TINYCLIENT_MEDIAD_SINK` names a file that then takes
//! what would have been played, as raw 48 kHz stereo `i16`.
//! what would have been played, as raw 48 kHz stereo `i16`. `TINYCLIENT_MEDIAD_DEVICES` names a
//! file that lists devices in the system's place, for a test that needs one no machine has.

use crate::pick::{self, Backoff, Endpoint, Host, Pick};
use crate::ring::{ring, Consumer, Producer};
use crate::{rt, CHANNELS, FRAME_SAMPLES, RATE};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{DeviceType, InterfaceType};
use protocol::settings::DeviceChoice;
use protocol::AudioDevice;
use serde::Deserialize;
use std::fs::File;
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
Expand Down Expand Up @@ -474,25 +477,28 @@ impl Host for Snapshot {
}
}

/// What a device is, for choosing it. `None` for one that went while it was being read.
fn endpoint(device: &cpal::Device) -> Option<Endpoint> {
use cpal::{DeviceType, InterfaceType};
let description = device.description().ok()?;
let name = description.name().to_owned();
// Without an id (a backend that has none) the name stands in, as it did before ids.
let id = device.id().map(|id| id.to_string()).unwrap_or_else(|_| name.clone());
let is_virtual = description.device_type() == DeviceType::Virtual
|| pick::is_virtual(&name)
|| description.driver().is_some_and(pick::is_virtual);
let rank = match (description.device_type(), description.interface_type()) {
/// What a device is, for choosing it, from what the system says of it: its name, its driver,
/// its form factor (`kind`) and how it connects (`via`).
fn described(id: String, name: String, driver: Option<&str>, kind: DeviceType, via: InterfaceType) -> Endpoint {
let is_virtual = kind == DeviceType::Virtual || pick::is_virtual(&name) || driver.is_some_and(pick::is_virtual);
let rank = match (kind, via) {
// A monitor's or receiver's digital input: often nothing is plugged into it.
(_, InterfaceType::Hdmi | InterfaceType::DisplayPort | InterfaceType::Spdif) => 8,
(DeviceType::Headset, _) => 0,
(DeviceType::Headphones | DeviceType::Handset | DeviceType::Earpiece, _) => 1,
(DeviceType::Speaker | DeviceType::Microphone, _) => 2,
_ => 5,
};
Some(Endpoint { id, name, is_virtual, rank })
Endpoint { id, name, is_virtual, rank }
}

/// What a device is, for choosing it. `None` for one that went while it was being read.
fn endpoint(device: &cpal::Device) -> Option<Endpoint> {
let description = device.description().ok()?;
let name = description.name().to_owned();
// Without an id (a backend that has none) the name stands in, as it did before ids.
let id = device.id().map(|id| id.to_string()).unwrap_or_else(|_| name.clone());
Some(described(id, name, description.driver(), description.device_type(), description.interface_type()))
}

impl Host for System {
Expand All @@ -512,6 +518,71 @@ impl Host for System {
}
}

/// The devices a test lists in the system's place, from the file `TINYCLIENT_MEDIAD_DEVICES`
/// names: `inputs` and `outputs`, each device by its `id` and `name` and, as Windows gives one
/// in brackets, its `driver`; then the ids of `default_input` and `default_output`. No lab
/// machine has a headset whose name says "virtual", and a test's file has one. The device menu
/// and the automatic choice are made over it as over the system's own list. It says nothing of
/// form factors, as ALSA says nothing of them, and a call's streams are not its: they are the
/// system's devices, or what `TINYCLIENT_MEDIAD_AUDIO` stands in for them.
#[derive(Deserialize)]
struct StandIn {
#[serde(default)]
inputs: Vec<StandInDevice>,
#[serde(default)]
outputs: Vec<StandInDevice>,
#[serde(default)]
default_input: String,
#[serde(default)]
default_output: String,
}

#[derive(Deserialize)]
struct StandInDevice {
id: String,
name: String,
#[serde(default)]
driver: Option<String>,
}

/// A [`StandIn`] from the text of its file. `Err` says what is wrong with the text, for the log.
fn stand_in_file(text: &str) -> Result<StandIn, String> {
serde_json::from_str(text).map_err(|e| e.to_string())
}

impl Host for StandIn {
fn endpoints(&self, input: bool) -> Vec<Endpoint> {
let devices = if input { &self.inputs } else { &self.outputs };
devices
.iter()
.map(|device| described(device.id.clone(), device.name.clone(), device.driver.as_deref(), DeviceType::Unknown, InterfaceType::Unknown))
.collect()
}

fn default_id(&self, input: bool) -> Option<String> {
let id = if input { &self.default_input } else { &self.default_output };
(!id.is_empty()).then(|| id.clone())
}
}

/// The listing of the file `TINYCLIENT_MEDIAD_DEVICES` names; `None` when it names none. A file
/// that cannot be read or understood lists nothing and the log says why: the system's devices
/// are never put in its place.
fn stand_in_listing() -> Option<Listing> {
let path = crate::out::var_os("TINYCLIENT_MEDIAD_DEVICES")?;
Some(match std::fs::read_to_string(path).map_err(|e| e.to_string()).and_then(|text| stand_in_file(&text)) {
Ok(listed) => {
let (inputs, default_input) = devices_of(&listed, true);
let (outputs, default_output) = devices_of(&listed, false);
Listing { inputs, outputs, default_input, default_output }
}
Err(why) => {
tracing::warn!("mediad: the file TINYCLIENT_MEDIAD_DEVICES names lists no device: {why}");
Listing::default()
}
})
}

/// One kind of device for the menu: what is listed, which is the default, which a call left to
/// choose by itself would use.
fn devices_of(system: &dyn Host, input: bool) -> (Vec<AudioDevice>, String) {
Expand All @@ -534,6 +605,9 @@ fn devices_of(system: &dyn Host, input: bool) -> (Vec<AudioDevice>, String) {

/// Asks the system what exists. Opens nothing.
pub fn listing() -> Listing {
if let Some(listing) = stand_in_listing() {
return listing;
}
if let Ok(kind) = crate::out::var("TINYCLIENT_MEDIAD_AUDIO").ok_or(()) {
let stand_in = |name: &str| AudioDevice { id: name.to_owned(), name: name.to_owned(), default: true, auto: true, ..AudioDevice::default() };
let unplugged = kind == "unplugged";
Expand Down Expand Up @@ -2091,4 +2165,37 @@ mod tests {
assert!((55..75).contains(&speech), "{speech}");
assert_eq!(full, 99);
}

/// A USB sound adapter with a headset on it is hardware, whatever its name and its driver
/// say: Linux lists one as "Virtual 7.1 Ch Sound". Before, "virtual" in either made it
/// software.
#[test]
fn a_device_is_software_by_its_driver_as_by_its_name_and_virtual_alone_is_not() {
let adapter = described("hw:CARD=1,DEV=0".into(), "Virtual 7.1 Ch Sound, USB Audio".into(), Some("hw:CARD=1,DEV=0"), DeviceType::Unknown, InterfaceType::Unknown);
assert!(!adapter.is_virtual, "{adapter:?}");
// A cable its person renamed: nothing in the name, the software in its driver.
let cable = described("cable".into(), "Microphone".into(), Some("VB-Audio Virtual Cable"), DeviceType::Unknown, InterfaceType::Unknown);
assert!(cable.is_virtual, "{cable:?}");
// What the system says a device is comes before any name.
assert!(described(String::new(), "Anything".into(), None, DeviceType::Virtual, InterfaceType::Virtual).is_virtual);
}

/// The stand-in file gives each side's devices by id, name and driver, and the default of
/// each side. The driver is read as the name is. Text that is not such a file is refused.
#[test]
fn a_stand_in_file_gives_the_devices_and_the_default_of_each_side() {
let file = r#"{
"inputs": [{"id": "cable-in", "name": "Microphone", "driver": "VB-Audio Virtual Cable"}],
"outputs": [{"id": "adapter", "name": "Virtual 7.1 Ch Sound, USB Audio"}],
"default_input": "cable-in"
}"#;
let listed = stand_in_file(file).unwrap();
assert!(listed.endpoints(true)[0].is_virtual, "by its driver, as by its name");
assert!(!listed.endpoints(false)[0].is_virtual, "a headset whose name says virtual");
assert_eq!(listed.default_id(true).as_deref(), Some("cable-in"));
assert_eq!(listed.default_id(false), None, "nothing is named");
// A device is at least an id and a name.
assert!(stand_in_file(r#"{"inputs": [{"id": "in"}]}"#).is_err());
assert!(stand_in_file("{").is_err());
}
}
52 changes: 46 additions & 6 deletions crates/mediad/src/pick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
//! What is never picked for the user: a virtual device (Krisp, VB-Cable, Voicemeeter, NVIDIA
//! Broadcast, Steam Streaming, ...). Those carry sound only while their app runs and routes it,
//! so a call that lands on one by itself is a call nobody hears. They are used when the user
//! picked one, or picked "System default" while one is the default.
//! picked one, or picked "System default" while one is the default. A real headset that says
//! "virtual" is told from them by what follows: it is named for the surround its own dongle
//! simulates ("Virtual Surround Sound", "Virtual 7.1 Ch Sound"). Any other "virtual" is software.
//!
//! Everything here is pure over a [`Host`], so the choice, the fallback and the switch back
//! when a device returns are tested against a fake one.
Expand Down Expand Up @@ -86,11 +88,16 @@ const VIRTUAL: &[&str] = &[
"monitor of ",
];

/// What a real device says after "virtual": the surround its own dongle simulates. A HyperX
/// Cloud II is "HyperX Virtual Surround Sound", a USB sound adapter "Virtual 7.1 Ch Sound".
/// Software says what it is ("Line 1 (Virtual Audio Cable)", "Headset Microphone (Oculus
/// Virtual Audio Device)"), so "virtual" with any other word stays software: a call must never
/// land on one of those by itself.
const VIRTUAL_HARDWARE: &[&str] = &["virtual surround", "virtual 7.1", "virtual 5.1"];

/// True for software devices: a call never lands on one unless the user picked it.
pub fn is_virtual(name: &str) -> bool {
// "Virtual surround" is a feature of real headsets (a common USB gaming headset is named
// for it), not a software device.
let name = name.to_lowercase().replace("virtual surround", "");
let name = VIRTUAL_HARDWARE.iter().fold(name.to_lowercase(), |name, hardware| name.replace(hardware, " "));
VIRTUAL.iter().any(|mark| name.contains(mark))
}

Expand Down Expand Up @@ -268,6 +275,10 @@ mod tests {

const HEADSET_MIC: &str = "Headset Microphone (CORSAIR HS55 Wireless Core Receiver)";
const HEADSET_EAR: &str = "Headset Earphone (CORSAIR HS55 Wireless Core Receiver)";
/// A USB sound adapter with a headset on it, as Linux lists it. Hardware, by any word.
const ADAPTER: &str = "Virtual 7.1 Ch Sound, USB Audio";
const CABLE_IN: &str = "CABLE Input (VB-Audio Virtual Cable)";
const CABLE_OUT: &str = "CABLE Output (VB-Audio Virtual Cable)";

fn fake() -> Fake {
Fake {
Expand Down Expand Up @@ -304,14 +315,43 @@ mod tests {

#[test]
fn the_krisp_and_cable_kinds_are_virtual_and_hardware_is_not() {
for name in ["Krisp Speaker (Krisp Audio)", "CABLE Input (VB-Audio Virtual Cable)", "VoiceMeeter Input (VB-Audio VoiceMeeter VAIO)", "Microphone (NVIDIA Broadcast)", "Speakers (Steam Streaming Speakers)"] {
for name in ["Krisp Speaker (Krisp Audio)", CABLE_IN, "VoiceMeeter Input (VB-Audio VoiceMeeter VAIO)", "Microphone (NVIDIA Broadcast)", "Speakers (Steam Streaming Speakers)", "Line 1 (Virtual Audio Cable)", "Headset Microphone (Oculus Virtual Audio Device)", "Speakers (NVIDIA Virtual Audio Device (Wave Extensible) (WDM))", "Virtual Bus (A Mixer)"] {
assert!(is_virtual(name), "{name}");
}
for name in [HEADSET_MIC, HEADSET_EAR, "Headset Earphone (HyperX Virtual Surround Sound)", "Speakers (2- USB Audio Device)", "LG ULTRAGEAR (NVIDIA High Definition Audio)", "Realtek Digital Output (Realtek(R) Audio)"] {
for name in [HEADSET_MIC, HEADSET_EAR, "Headset Earphone (HyperX Virtual Surround Sound)", ADAPTER, "Speakers (2- USB Audio Device)", "LG ULTRAGEAR (NVIDIA High Definition Audio)", "Realtek Digital Output (Realtek(R) Audio)"] {
assert!(!is_virtual(name), "{name}");
}
}

/// Before, "virtual" by itself marked software, so the adapter was passed over for the
/// webcam and the speakers. A cable is software still: never chosen for the user, and used
/// when the user picked "System default" while it is the default.
#[test]
fn a_headset_whose_name_says_virtual_is_kept_when_nobody_chose_and_a_cable_is_not() {
let host = Fake {
inputs: RefCell::new(vec![
endpoint("in-adapter", ADAPTER, 5),
endpoint("in-webcam", "Microphone (USB Video Device)", 5),
endpoint("in-cable", CABLE_IN, 0),
]),
outputs: RefCell::new(vec![
endpoint("out-adapter", ADAPTER, 5),
endpoint("out-realtek", "Speakers (Realtek(R) Audio)", 2),
endpoint("out-cable", CABLE_OUT, 0),
]),
default_input: RefCell::new(Some("in-adapter".into())),
default_output: RefCell::new(Some("out-adapter".into())),
};
assert_eq!(id(&host, &DeviceChoice::Auto, true), "in-adapter");
assert_eq!(id(&host, &DeviceChoice::Auto, false), "out-adapter");
*host.default_input.borrow_mut() = Some("in-cable".into());
*host.default_output.borrow_mut() = Some("out-cable".into());
assert_eq!(id(&host, &DeviceChoice::Auto, true), "in-adapter", "the best hardware there is");
assert_eq!(id(&host, &DeviceChoice::Auto, false), "out-realtek", "ranked over the adapter of the same list");
assert_eq!(id(&host, &DeviceChoice::System, true), "in-cable");
assert_eq!(id(&host, &DeviceChoice::System, false), "out-cable");
}

#[test]
fn nobody_chose_so_a_virtual_default_is_passed_over_for_the_headset() {
let host = fake();
Expand Down
41 changes: 41 additions & 0 deletions crates/mediad/tests/voice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ impl Mediad {
.env_remove("TINYCLIENT_DIR")
.env_remove("TINYCLIENT_VOICE_TRUST")
.env_remove("TINYCLIENT_MEDIAD_SCREEN")
.env_remove("TINYCLIENT_MEDIAD_DEVICES")
.env_remove("TINYCLIENT_SHARE_AUDIO")
.env(home, tls().dir.join("home"))
.env("TINYCLIENT_MEDIAD_AUDIO", hears)
Expand Down Expand Up @@ -1433,6 +1434,46 @@ fn devices_are_listed_at_start_and_the_meter_runs_only_while_asked_for() {
assert_eq!(mediad.hang_up().0.code(), Some(0));
}

/// A headset whose name says "virtual" is hardware, so with nobody choosing it is what a call
/// uses, and the cable beside it is software still. No test machine has such a headset, so the
/// devices come from a file (`TINYCLIENT_MEDIAD_DEVICES`): a USB sound adapter with a headset on
/// it, which Linux lists as "Virtual 7.1 Ch Sound", is the system default on both sides; a
/// webcam and a VB-Audio cable are beside it. A build that does not read the file lists the
/// stand-in alone and never names the headset.
#[test]
fn a_headset_whose_name_says_virtual_is_what_a_call_uses_when_nobody_chose() {
let file = tls().dir.join("devices.json");
std::fs::write(&file, r#"{
"inputs": [
{"id": "adapter", "name": "Virtual 7.1 Ch Sound, USB Audio", "driver": "hw:CARD=1,DEV=0"},
{"id": "webcam", "name": "Microphone (USB Video Device)"},
{"id": "cable-in", "name": "CABLE Input (VB-Audio Virtual Cable)", "driver": "VB-Audio Virtual Cable"}
],
"outputs": [
{"id": "adapter", "name": "Virtual 7.1 Ch Sound, USB Audio", "driver": "hw:CARD=1,DEV=0"},
{"id": "cable-out", "name": "CABLE Output (VB-Audio Virtual Cable)", "driver": "VB-Audio Virtual Cable"}
],
"default_input": "adapter",
"default_output": "adapter"
}"#).unwrap();
let mut mediad = Mediad::start_in("null", None, &[("TINYCLIENT_MEDIAD_DEVICES", &file)]);
let hardware = |id: &str, name: &str, default: bool| AudioDevice { id: id.into(), name: name.into(), default, auto: default, ..AudioDevice::default() };
let software = |id: &str, name: &str| AudioDevice { id: id.into(), name: name.into(), is_virtual: true, ..AudioDevice::default() };
let adapter = "Virtual 7.1 Ch Sound, USB Audio";
let listed = MediaResponse::DeviceList {
inputs: vec![hardware("adapter", adapter, true), hardware("webcam", "Microphone (USB Video Device)", false), software("cable-in", "CABLE Input (VB-Audio Virtual Cable)")],
outputs: vec![hardware("adapter", adapter, true), software("cable-out", "CABLE Output (VB-Audio Virtual Cable)")],
cameras: Vec::new(),
};
// At start, and again when the device menu opens.
mediad.event("DeviceList", |e| *e == listed);
assert_eq!(mediad.ask(MediaRequest::Meter { on: true }), MediaResponse::Done);
mediad.event("DeviceList", |e| *e == listed);
assert_eq!(mediad.ask(MediaRequest::Meter { on: false }), MediaResponse::Done);
assert_eq!(mediad.hang_up().0.code(), Some(0));
let _ = std::fs::remove_file(file);
}

/// The soft start of a word is under the gate. It is sent anyway, ahead of the frame that
/// opened the gate and stamped with the time it was heard.
#[test]
Expand Down
9 changes: 9 additions & 0 deletions e2e/scenarios/auto-device-virtual-name/drive.linux.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# auto-device-virtual-name on Linux. The lab runs this with bash while ffmpeg films the display.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
if command -v python3 >/dev/null 2>&1; then
exec python3 "$HERE/drive.py"
fi
echo "python3 is not on PATH" >&2
exit 1
9 changes: 9 additions & 0 deletions e2e/scenarios/auto-device-virtual-name/drive.macos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# auto-device-virtual-name on macOS. The lab runs this with bash while ffmpeg films the display.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
if command -v python3 >/dev/null 2>&1; then
exec python3 "$HERE/drive.py"
fi
echo "python3 is not on PATH" >&2
exit 1
Loading
Loading