From 413de5c8e9b07ea4838b1234566314d55aeee83c Mon Sep 17 00:00:00 2001 From: unRekable Date: Sat, 5 Dec 2026 15:20:46 +0100 Subject: [PATCH] Treat a headset named for the surround it simulates, like Virtual 7.1, as hardware and every other "virtual" device as software --- crates/mediad/src/audio.rs | 133 ++++++++- crates/mediad/src/pick.rs | 52 +++- crates/mediad/tests/voice.rs | 41 +++ .../auto-device-virtual-name/drive.linux.sh | 9 + .../auto-device-virtual-name/drive.macos.sh | 9 + .../auto-device-virtual-name/drive.py | 262 ++++++++++++++++++ .../drive.windows.ps1 | 17 ++ .../auto-device-virtual-name/scenario.json | 12 + 8 files changed, 516 insertions(+), 19 deletions(-) create mode 100644 e2e/scenarios/auto-device-virtual-name/drive.linux.sh create mode 100644 e2e/scenarios/auto-device-virtual-name/drive.macos.sh create mode 100644 e2e/scenarios/auto-device-virtual-name/drive.py create mode 100644 e2e/scenarios/auto-device-virtual-name/drive.windows.ps1 create mode 100644 e2e/scenarios/auto-device-virtual-name/scenario.json diff --git a/crates/mediad/src/audio.rs b/crates/mediad/src/audio.rs index aea9e880..dfcb3979 100644 --- a/crates/mediad/src/audio.rs +++ b/crates/mediad/src/audio.rs @@ -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}; @@ -474,17 +477,11 @@ 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 { - 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, @@ -492,7 +489,16 @@ fn endpoint(device: &cpal::Device) -> Option { (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 { + 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 { @@ -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, + #[serde(default)] + outputs: Vec, + #[serde(default)] + default_input: String, + #[serde(default)] + default_output: String, +} + +#[derive(Deserialize)] +struct StandInDevice { + id: String, + name: String, + #[serde(default)] + driver: Option, +} + +/// 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 { + serde_json::from_str(text).map_err(|e| e.to_string()) +} + +impl Host for StandIn { + fn endpoints(&self, input: bool) -> Vec { + 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 { + 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 { + 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, String) { @@ -534,6 +605,9 @@ fn devices_of(system: &dyn Host, input: bool) -> (Vec, 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"; @@ -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()); + } } diff --git a/crates/mediad/src/pick.rs b/crates/mediad/src/pick.rs index a6ee39e3..20fc0be4 100644 --- a/crates/mediad/src/pick.rs +++ b/crates/mediad/src/pick.rs @@ -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. @@ -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)) } @@ -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 { @@ -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(); diff --git a/crates/mediad/tests/voice.rs b/crates/mediad/tests/voice.rs index f4ba3398..c89b2014 100644 --- a/crates/mediad/tests/voice.rs +++ b/crates/mediad/tests/voice.rs @@ -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) @@ -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] diff --git a/e2e/scenarios/auto-device-virtual-name/drive.linux.sh b/e2e/scenarios/auto-device-virtual-name/drive.linux.sh new file mode 100644 index 00000000..92b4cad6 --- /dev/null +++ b/e2e/scenarios/auto-device-virtual-name/drive.linux.sh @@ -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 diff --git a/e2e/scenarios/auto-device-virtual-name/drive.macos.sh b/e2e/scenarios/auto-device-virtual-name/drive.macos.sh new file mode 100644 index 00000000..38e75592 --- /dev/null +++ b/e2e/scenarios/auto-device-virtual-name/drive.macos.sh @@ -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 diff --git a/e2e/scenarios/auto-device-virtual-name/drive.py b/e2e/scenarios/auto-device-virtual-name/drive.py new file mode 100644 index 00000000..07cb3e48 --- /dev/null +++ b/e2e/scenarios/auto-device-virtual-name/drive.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""A headset whose name says "virtual" is hardware: a call where nobody chose uses it. + +Starts this build's mediad the way chatd does (frames on stdin and stdout) and reads the device +list it hands chatd for the device menu: once at start, and once more when the menu opens. No +lab machine has a headset whose name says "virtual", so the driver writes a list and names it +in TINYCLIENT_MEDIAD_DEVICES, the stand-in for the system's list. Nothing is opened: the sound +is the usual stand-in (TINYCLIENT_MEDIAD_AUDIO=null). + +The list is as systems give real devices. A USB sound adapter with a headset plugged into 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. + +Passes only when the adapter is listed as hardware and is the one device on each side that a +call uses when nobody chose, the cable is still listed as software, and the open menu lists the +same again. On a build from before the fix the word "virtual" alone made the adapter software, +and such a build does not read the stand-in either: its list never names the headset, so this +driver fails there on the step that looks for it. + +What it does not prove: a real adapter carrying a real call. The stand-in is a list, not a +device. The flag the menu shows is set by the same choice a call makes over the system's list. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +import json +import os +import queue +import struct +import subprocess +import sys +import threading +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +PATIENCE = 20.0 + +FAILED = False +STEPS = "" + +ADAPTER = "Virtual 7.1 Ch Sound, USB Audio" + +# The system's list, as Linux and Windows name these devices: the adapter a headset is plugged +# into, a webcam, and a cable. +DEVICES = { + "inputs": [ + {"id": "adapter", "name": ADAPTER, "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": ADAPTER, "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", +} + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def mediad_bin(app_dir): + name = "mediad.exe" if sys.platform == "win32" else "mediad" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "mediad") + return os.path.join(app_dir, name) + + +class Mediad: + """mediad as chatd runs it: a length and a JSON frame each way.""" + + def __init__(self, binary, env, log): + kwargs = {"env": env, "stdin": subprocess.PIPE, "stdout": subprocess.PIPE, "stderr": log} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + self.proc = subprocess.Popen([binary, "1"], **kwargs) + self.frames = queue.Queue() + self.seen = [] + threading.Thread(target=self.read, daemon=True).start() + + def read(self): + out = self.proc.stdout + while True: + head = out.read(4) + if len(head) < 4: + return + body = out.read(struct.unpack(">I", head)[0]) + try: + self.frames.put(json.loads(body.decode("utf-8"))) + except ValueError: + return + + def ask(self, request): + body = json.dumps(request).encode("utf-8") + try: + self.proc.stdin.write(struct.pack(">I", len(body)) + body) + self.proc.stdin.flush() + except OSError: + return False + return True + + def take(self): + """Everything mediad has said so far.""" + while True: + try: + self.seen.append(self.frames.get_nowait()) + except queue.Empty: + return self.seen + + def said(self, kind): + return [frame for frame in self.take() if frame.get("media") == kind] + + def wait(self, kind, within=PATIENCE): + deadline = time.time() + within + while time.time() < deadline: + found = self.said(kind) + if found: + return found[0] + if self.said("failed") and kind != "failed": + return None + time.sleep(0.02) + return None + + def hang_up(self): + """Closing stdin is the hang-up. The exit code, or None when it did not go.""" + try: + self.proc.stdin.close() + except OSError: + pass + try: + return self.proc.wait(timeout=10) + except subprocess.TimeoutExpired: + return None + + def kill(self): + if self.proc.poll() is None: + self.proc.kill() + self.proc.wait(timeout=5) + + +def answered(mediad, request): + """Sends a request and waits for one more reply than mediad has given. True when it was done.""" + count, done = len(mediad.said("done")) + len(mediad.said("refused")), len(mediad.said("done")) + if not mediad.ask(request): + return False + deadline = time.time() + PATIENCE + while time.time() < deadline: + replies, dones = len(mediad.said("done")) + len(mediad.said("refused")), len(mediad.said("done")) + if replies > count: + return dones > done + time.sleep(0.02) + return False + + +def device(listed, side, wanted): + """The device with this id on one side of a device list, or None when it is not there.""" + return next((one for one in listed.get(side) or [] if one.get("id") == wanted), None) + + +def chosen(listed, side): + """The ids on one side that a call uses when nobody chose.""" + return [one.get("id") for one in listed.get(side) or [] if one.get("auto")] + + +def check(listed, what): + """The steps on one device list: what it says of the headset and of the cable.""" + adapter_in, adapter_out = device(listed, "inputs", "adapter"), device(listed, "outputs", "adapter") + cable_in, cable_out = device(listed, "inputs", "cable-in"), device(listed, "outputs", "cable-out") + both = adapter_in is not None and adapter_out is not None + step("%s: the headset adapter is listed as hardware on both sides" % what, + both and not adapter_in.get("virtual") and not adapter_out.get("virtual")) + # Only the adapter: the cable beside it is passed over, as software always is. + step("%s: with nobody choosing, the headset adapter is the microphone and the speaker" % what, + both and chosen(listed, "inputs") == ["adapter"] and chosen(listed, "outputs") == ["adapter"]) + step("%s: the cable is still listed as software" % what, + cable_in is not None and cable_out is not None and cable_in.get("virtual") and cable_out.get("virtual")) + + +def listed_again(mediad, before): + """A device list beyond the `before` ones already read, or None when none comes.""" + deadline = time.time() + PATIENCE + while time.time() < deadline: + found = mediad.said("devicelist") + if len(found) > before: + return found[-1] + if mediad.said("failed"): + return None + time.sleep(0.02) + return None + + +def run(binary): + data = os.path.join(OUT, "data") + os.makedirs(data, exist_ok=True) + devices = os.path.join(data, "devices.json") + with open(devices, "w", encoding="utf-8") as handle: + json.dump(DEVICES, handle, indent=1) + env = os.environ.copy() + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_MEDIAD_AUDIO"] = "null" + env["TINYCLIENT_MEDIAD_DEVICES"] = devices + env["TINYCLIENT_LOG_LEVEL"] = "info" + with open(os.path.join(OUT, "app.err.log"), "w", encoding="utf-8") as log: + mediad = Mediad(binary, env, log) + try: + step("mediad starts", mediad.wait("ready") is not None) + first = mediad.wait("devicelist") + step("the device list arrives at start", first is not None) + if first is not None: + print("devices at start: %s" % json.dumps(first, sort_keys=True), flush=True) + check(first, "at start") + # The device menu opens, as it does from Settings: the list comes again at once. + before = len(mediad.said("devicelist")) + step("the device menu opens", answered(mediad, {"media": "meter", "on": True})) + again = listed_again(mediad, before) + step("the open device menu lists the devices again", again is not None) + if again is not None: + check(again, "from the open menu") + step("the device menu closes", answered(mediad, {"media": "meter", "on": False})) + step("hanging up ends it cleanly", mediad.hang_up() == 0) + finally: + mediad.kill() + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = mediad_bin(APP) + if not os.path.isfile(binary): + step("mediad is in E2E_APP_DIR", False) + return 1 + try: + run(binary) + except Exception as err: # A driver that crashes is a failed step, not a pass. + step("the driver ran to its end (%s)" % type(err).__name__, False) + print(repr(err), flush=True) + return 1 if FAILED else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/auto-device-virtual-name/drive.windows.ps1 b/e2e/scenarios/auto-device-virtual-name/drive.windows.ps1 new file mode 100644 index 00000000..47b30b4e --- /dev/null +++ b/e2e/scenarios/auto-device-virtual-name/drive.windows.ps1 @@ -0,0 +1,17 @@ +# auto-device-virtual-name on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/auto-device-virtual-name/scenario.json b/e2e/scenarios/auto-device-virtual-name/scenario.json new file mode 100644 index 00000000..cd96436c --- /dev/null +++ b/e2e/scenarios/auto-device-virtual-name/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "auto-device-virtual-name", + "title": "A headset whose name says virtual is hardware, so a call where nobody chose a device uses it", + "platforms": ["windows", "linux", "macos"], + "not_applicable": { + "android": "The phone proof build does not start desktop mediad. The same device code is in the library the phone links.", + "ios": "The phone proof build does not start desktop mediad. The same device code is in the library the phone links." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}