feat: volume sliders, output device switching, About credits (1.1.0)
- Per-app volume slider and a system volume card (slider + mute) - Default output device picker; per-app output device picker (Windows via IPolicyConfig / IAudioPolicyConfigFactory, Linux via sink moves; macOS has no per-app routing API) - Slider commands are coalesced on the audio thread - Fix the Windows title-bar and taskbar icon (set via winit attributes) - About: "by X4Lo" and a GitHub link - README: app icon above the title - --list prints output devices and system volume - CI: run on master and on manual dispatch
This commit is contained in:
1 parent
8f476dbe52
commit
c5cb407481
20 files changed
+1440
-138
No files matched your search
+119
-3
@@ -3,12 +3,14 @@
|
||||
//!
|
||||
//! Every playback stream an app opens is a *sink input*; that includes paused/corked
|
||||
//! streams, so idle-but-registered apps show up too. Full per-app volume and mute are
|
||||
//! natively supported.
|
||||
//! natively supported. Output devices are *sinks*: system volume is the default sink's
|
||||
//! volume, and per-app routing moves the app's sink inputs (PulseAudio's stream-restore
|
||||
//! module, and PipeWire, remember the choice per app).
|
||||
//!
|
||||
//! Uses the single-threaded standard mainloop driven synchronously from the audio worker
|
||||
//! thread: each call issues an operation and iterates the loop until it completes.
|
||||
|
||||
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities};
|
||||
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, MasterVolume, OutputDevice};
|
||||
use libpulse_binding as pulse;
|
||||
use pulse::callbacks::ListResult;
|
||||
use pulse::context::{Context, FlagSet, State};
|
||||
@@ -29,6 +31,17 @@ struct Input {
|
||||
muted: bool,
|
||||
volume: f32,
|
||||
channels: u8,
|
||||
sink: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Sink {
|
||||
index: u32,
|
||||
name: String,
|
||||
description: String,
|
||||
volume: f32,
|
||||
muted: bool,
|
||||
channels: u8,
|
||||
}
|
||||
|
||||
pub struct PulseController {
|
||||
@@ -95,6 +108,7 @@ impl PulseController {
|
||||
muted: i.mute,
|
||||
volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32,
|
||||
channels: i.volume.len(),
|
||||
sink: i.sink,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -103,6 +117,46 @@ impl PulseController {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn sinks(&mut self) -> AudioResult<Vec<Sink>> {
|
||||
let out: Rc<RefCell<Vec<Sink>>> = Rc::default();
|
||||
let sink = out.clone();
|
||||
let op = self.context.introspect().get_sink_info_list(move |r| {
|
||||
if let ListResult::Item(i) = r {
|
||||
let name = i.name.as_deref().unwrap_or_default().to_owned();
|
||||
sink.borrow_mut().push(Sink {
|
||||
index: i.index,
|
||||
description: i.description.as_deref().filter(|d| !d.is_empty()).unwrap_or(&name).to_owned(),
|
||||
name,
|
||||
volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32,
|
||||
muted: i.mute,
|
||||
channels: i.volume.len(),
|
||||
});
|
||||
}
|
||||
});
|
||||
self.wait(op)?;
|
||||
let v = out.borrow().clone();
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn default_sink_name(&mut self) -> AudioResult<Option<String>> {
|
||||
let out: Rc<RefCell<Option<String>>> = Rc::default();
|
||||
let sink = out.clone();
|
||||
let op = self.context.introspect().get_server_info(move |info| {
|
||||
*sink.borrow_mut() = info.default_sink_name.as_deref().map(str::to_owned);
|
||||
});
|
||||
self.wait(op)?;
|
||||
let v = out.borrow().clone();
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn default_sink(&mut self) -> AudioResult<Sink> {
|
||||
let name = self.default_sink_name()?;
|
||||
let sinks = self.sinks()?;
|
||||
name.and_then(|n| sinks.iter().find(|s| s.name == n).cloned())
|
||||
.or_else(|| sinks.first().cloned())
|
||||
.ok_or_else(|| backend("no output device"))
|
||||
}
|
||||
|
||||
fn for_each_input_of(
|
||||
&mut self,
|
||||
app: &str,
|
||||
@@ -126,10 +180,18 @@ impl AudioController for PulseController {
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { per_app_volume: true, per_app_mute: true }
|
||||
Capabilities {
|
||||
per_app_volume: true,
|
||||
per_app_mute: true,
|
||||
per_app_device: true,
|
||||
master_volume: true,
|
||||
output_devices: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||
let sinks = self.sinks().unwrap_or_default();
|
||||
let default_sink = self.default_sink_name().ok().flatten();
|
||||
let mut grouped: BTreeMap<String, Vec<Input>> = BTreeMap::new();
|
||||
for i in self.inputs()? {
|
||||
grouped.entry(i.key.clone()).or_default().push(i);
|
||||
@@ -139,7 +201,16 @@ impl AudioController for PulseController {
|
||||
.map(|(key, ins)| {
|
||||
let mut pids: Vec<u32> = ins.iter().map(|i| i.pid).filter(|p| *p != 0).collect();
|
||||
pids.dedup();
|
||||
// PulseAudio doesn't say whether a stream *follows* the default; treat a
|
||||
// stream on the default sink as following it, anything else as routed.
|
||||
let device = sinks
|
||||
.iter()
|
||||
.find(|s| s.index == ins[0].sink)
|
||||
.map(|s| s.name.clone())
|
||||
.filter(|name| Some(name) != default_sink.as_ref());
|
||||
AudioApp {
|
||||
device,
|
||||
routable: true,
|
||||
name: ins[0].name.clone(),
|
||||
volume: Some(ins.iter().map(|i| i.volume).sum::<f32>() / ins.len() as f32),
|
||||
muted: ins.iter().all(|i| i.muted),
|
||||
@@ -165,4 +236,49 @@ impl AudioController for PulseController {
|
||||
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()> {
|
||||
self.for_each_input_of(app, |me, input| me.context.introspect().set_sink_input_mute(input.index, muted, None))
|
||||
}
|
||||
|
||||
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||
let default = self.default_sink_name()?;
|
||||
let mut out: Vec<OutputDevice> = self
|
||||
.sinks()?
|
||||
.into_iter()
|
||||
.map(|s| OutputDevice { is_default: Some(&s.name) == default.as_ref(), id: s.name, name: s.description })
|
||||
.collect();
|
||||
out.sort_by_key(|d| d.name.to_lowercase());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn set_default_output_device(&mut self, id: &str) -> AudioResult<()> {
|
||||
let op = self.context.set_default_sink(id, |_| {});
|
||||
self.wait(op)
|
||||
}
|
||||
|
||||
fn master_volume(&mut self) -> AudioResult<MasterVolume> {
|
||||
let s = self.default_sink()?;
|
||||
Ok(MasterVolume { volume: Some(s.volume), muted: s.muted })
|
||||
}
|
||||
|
||||
fn set_master_volume(&mut self, volume: f32) -> AudioResult<()> {
|
||||
let s = self.default_sink()?;
|
||||
let mut cv = ChannelVolumes::default();
|
||||
cv.set(s.channels.max(1), Volume((volume.clamp(0.0, 1.0) * Volume::NORMAL.0 as f32) as u32));
|
||||
let op = self.context.introspect().set_sink_volume_by_name(&s.name, &cv, None);
|
||||
self.wait(op)
|
||||
}
|
||||
|
||||
fn set_master_mute(&mut self, muted: bool) -> AudioResult<()> {
|
||||
let s = self.default_sink()?;
|
||||
let op = self.context.introspect().set_sink_mute_by_name(&s.name, muted, None);
|
||||
self.wait(op)
|
||||
}
|
||||
|
||||
fn set_app_output_device(&mut self, app: &str, device: Option<&str>) -> AudioResult<()> {
|
||||
let target = match device {
|
||||
Some(d) => d.to_owned(),
|
||||
None => self.default_sink()?.name,
|
||||
};
|
||||
self.for_each_input_of(app, |me, input| {
|
||||
me.context.introspect().move_sink_input_by_name(input.index, &target, None)
|
||||
})
|
||||
}
|
||||
}
|
||||
+160
-4
@@ -11,6 +11,9 @@
|
||||
//!
|
||||
//! Consequences:
|
||||
//! - Per-app **mute works**; per-app **volume levels do not** (`per_app_volume: false`).
|
||||
//! - Per-app **output devices do not** either (`per_app_device: false`): there is no
|
||||
//! public API to reroute another process. System volume/mute (the default device's
|
||||
//! virtual main volume) and switching the default output device are public and supported.
|
||||
//! `set_app_volume` accepts only 0.0 (mute) and 1.0 (unmute) and reports `Unsupported`
|
||||
//! for anything in between — it never fakes a level.
|
||||
//! - Requires macOS 14.2+. On older systems the symbols are absent; we look them up with
|
||||
@@ -25,7 +28,7 @@
|
||||
//! **Untested on real hardware by the original author** (developed on Windows, compile-
|
||||
//! checked for `aarch64-apple-darwin`). Reports from macOS users are very welcome.
|
||||
|
||||
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities};
|
||||
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, MasterVolume, OutputDevice};
|
||||
use objc2::msg_send;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{AnyClass, AnyObject};
|
||||
@@ -55,6 +58,16 @@ const K_HW_PROCESS_OBJECT_LIST: u32 = fourcc(b"prs#");
|
||||
const K_PROCESS_PID: u32 = fourcc(b"ppid");
|
||||
const K_PROCESS_BUNDLE_ID: u32 = fourcc(b"pbid");
|
||||
const K_PROCESS_IS_RUNNING_OUTPUT: u32 = fourcc(b"piro");
|
||||
const K_SCOPE_OUTPUT: u32 = fourcc(b"outp");
|
||||
const K_HW_DEVICES: u32 = fourcc(b"dev#");
|
||||
const K_HW_DEFAULT_OUTPUT_DEVICE: u32 = fourcc(b"dOut");
|
||||
const K_DEVICE_STREAMS: u32 = fourcc(b"stm#");
|
||||
const K_DEVICE_UID: u32 = fourcc(b"uid ");
|
||||
const K_OBJECT_NAME: u32 = fourcc(b"lnam");
|
||||
const K_DEVICE_VOLUME_SCALAR: u32 = fourcc(b"volm");
|
||||
const K_DEVICE_MUTE: u32 = fourcc(b"mute");
|
||||
/// `kAudioHardwareServiceDeviceProperty_VirtualMainVolume` (the menu-bar volume).
|
||||
const K_VIRTUAL_MAIN_VOLUME: u32 = fourcc(b"vmvc");
|
||||
/// `CATapMuteBehavior.CATapMuted`
|
||||
const CA_TAP_MUTED: isize = 1;
|
||||
|
||||
@@ -75,6 +88,35 @@ extern "C" {
|
||||
io_size: *mut u32,
|
||||
out: *mut c_void,
|
||||
) -> OSStatus;
|
||||
fn AudioObjectSetPropertyData(
|
||||
id: AudioObjectID,
|
||||
addr: *const AudioObjectPropertyAddress,
|
||||
qualifier_size: u32,
|
||||
qualifier: *const c_void,
|
||||
data_size: u32,
|
||||
data: *const c_void,
|
||||
) -> OSStatus;
|
||||
}
|
||||
|
||||
// The virtual main volume is only served through the AudioHardwareService shim.
|
||||
#[link(name = "AudioToolbox", kind = "framework")]
|
||||
extern "C" {
|
||||
fn AudioHardwareServiceGetPropertyData(
|
||||
id: AudioObjectID,
|
||||
addr: *const AudioObjectPropertyAddress,
|
||||
qualifier_size: u32,
|
||||
qualifier: *const c_void,
|
||||
io_size: *mut u32,
|
||||
out: *mut c_void,
|
||||
) -> OSStatus;
|
||||
fn AudioHardwareServiceSetPropertyData(
|
||||
id: AudioObjectID,
|
||||
addr: *const AudioObjectPropertyAddress,
|
||||
qualifier_size: u32,
|
||||
qualifier: *const c_void,
|
||||
data_size: u32,
|
||||
data: *const c_void,
|
||||
) -> OSStatus;
|
||||
}
|
||||
|
||||
type CreateTapFn = unsafe extern "C" fn(*mut AnyObject, *mut AudioObjectID) -> OSStatus;
|
||||
@@ -201,7 +243,13 @@ impl AudioController for CoreAudioTapController {
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { per_app_volume: false, per_app_mute: self.api.is_some() }
|
||||
Capabilities {
|
||||
per_app_volume: false,
|
||||
per_app_mute: self.api.is_some(),
|
||||
per_app_device: false,
|
||||
master_volume: true,
|
||||
output_devices: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||
@@ -245,6 +293,8 @@ impl AudioController for CoreAudioTapController {
|
||||
pids: ps.iter().map(|p| p.pid).collect(),
|
||||
volume: None, // not readable per-app on macOS
|
||||
exe_path: ps[0].path.clone(),
|
||||
device: None,
|
||||
routable: false,
|
||||
key,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -282,10 +332,70 @@ impl AudioController for CoreAudioTapController {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||
let default = default_output_device();
|
||||
let ids: Vec<AudioObjectID> = unsafe { get_array(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_DEVICES)? };
|
||||
let mut out = Vec::new();
|
||||
for id in ids {
|
||||
if !has_output_streams(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(uid) = (unsafe { get_cfstring(id, K_DEVICE_UID) }) else { continue };
|
||||
let name = unsafe { get_cfstring(id, K_OBJECT_NAME) }.unwrap_or_else(|| uid.clone());
|
||||
out.push(OutputDevice { id: uid, name, is_default: Some(id) == default });
|
||||
}
|
||||
out.sort_by_key(|d| d.name.to_lowercase());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn set_default_output_device(&mut self, uid: &str) -> AudioResult<()> {
|
||||
let ids: Vec<AudioObjectID> = unsafe { get_array(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_DEVICES)? };
|
||||
let id = ids
|
||||
.into_iter()
|
||||
.find(|id| unsafe { get_cfstring(*id, K_DEVICE_UID) }.as_deref() == Some(uid))
|
||||
.ok_or_else(|| AudioError::Backend("that output device is gone".into()))?;
|
||||
let a = addr(K_HW_DEFAULT_OUTPUT_DEVICE);
|
||||
let status = unsafe {
|
||||
AudioObjectSetPropertyData(K_AUDIO_OBJECT_SYSTEM_OBJECT, &a, 0, std::ptr::null(), 4, &id as *const u32 as _)
|
||||
};
|
||||
check(status, "set default output device")
|
||||
}
|
||||
|
||||
fn master_volume(&mut self) -> AudioResult<MasterVolume> {
|
||||
let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?;
|
||||
let volume = unsafe { service_get::<f32>(dev, output_addr(K_VIRTUAL_MAIN_VOLUME)) }
|
||||
.or_else(|| unsafe { get_at::<f32>(dev, output_addr(K_DEVICE_VOLUME_SCALAR)) });
|
||||
let muted = unsafe { get_at::<u32>(dev, output_addr(K_DEVICE_MUTE)) }.unwrap_or(0) != 0;
|
||||
Ok(MasterVolume { volume, muted })
|
||||
}
|
||||
|
||||
fn set_master_volume(&mut self, volume: f32) -> AudioResult<()> {
|
||||
let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?;
|
||||
let v = volume.clamp(0.0, 1.0);
|
||||
let a = output_addr(K_VIRTUAL_MAIN_VOLUME);
|
||||
let status =
|
||||
unsafe { AudioHardwareServiceSetPropertyData(dev, &a, 0, std::ptr::null(), 4, &v as *const f32 as _) };
|
||||
if status == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let a = output_addr(K_DEVICE_VOLUME_SCALAR);
|
||||
check(
|
||||
unsafe { AudioObjectSetPropertyData(dev, &a, 0, std::ptr::null(), 4, &v as *const f32 as _) },
|
||||
"set volume",
|
||||
)
|
||||
}
|
||||
|
||||
fn set_master_mute(&mut self, muted: bool) -> AudioResult<()> {
|
||||
let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?;
|
||||
let m = muted as u32;
|
||||
let a = output_addr(K_DEVICE_MUTE);
|
||||
check(unsafe { AudioObjectSetPropertyData(dev, &a, 0, std::ptr::null(), 4, &m as *const u32 as _) }, "set mute")
|
||||
}
|
||||
|
||||
fn platform_note(&self) -> Option<&'static str> {
|
||||
Some(if self.api.is_some() {
|
||||
"macOS can mute individual apps but can't set their volume level. Muting needs the \
|
||||
Screen & System Audio Recording permission."
|
||||
"macOS can mute individual apps but can't set their volume level or output device. \
|
||||
Muting needs the Screen & System Audio Recording permission."
|
||||
} else {
|
||||
"Per-app muting needs macOS 14.2 or newer. Apps are listed read-only."
|
||||
})
|
||||
@@ -326,6 +436,52 @@ fn addr(selector: u32) -> AudioObjectPropertyAddress {
|
||||
AudioObjectPropertyAddress { selector, scope: K_SCOPE_GLOBAL, element: K_ELEMENT_MAIN }
|
||||
}
|
||||
|
||||
fn output_addr(selector: u32) -> AudioObjectPropertyAddress {
|
||||
AudioObjectPropertyAddress { selector, scope: K_SCOPE_OUTPUT, element: K_ELEMENT_MAIN }
|
||||
}
|
||||
|
||||
fn check(status: OSStatus, what: &str) -> AudioResult<()> {
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(AudioError::Backend(format!("{what}: OSStatus {status}")))
|
||||
}
|
||||
}
|
||||
|
||||
fn default_output_device() -> Option<AudioObjectID> {
|
||||
unsafe { get_scalar::<AudioObjectID>(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_DEFAULT_OUTPUT_DEVICE) }
|
||||
.filter(|id| *id != 0)
|
||||
}
|
||||
|
||||
fn has_output_streams(id: AudioObjectID) -> bool {
|
||||
let a = output_addr(K_DEVICE_STREAMS);
|
||||
let mut size = 0u32;
|
||||
let status = unsafe { AudioObjectGetPropertyDataSize(id, &a, 0, std::ptr::null(), &mut size) };
|
||||
status == 0 && size > 0
|
||||
}
|
||||
|
||||
unsafe fn get_at<T: Copy + Default>(object: AudioObjectID, a: AudioObjectPropertyAddress) -> Option<T> {
|
||||
let mut v = T::default();
|
||||
let mut size = std::mem::size_of::<T>() as u32;
|
||||
let status =
|
||||
AudioObjectGetPropertyData(object, &a, 0, std::ptr::null(), &mut size, &mut v as *mut T as *mut c_void);
|
||||
(status == 0).then_some(v)
|
||||
}
|
||||
|
||||
unsafe fn service_get<T: Copy + Default>(object: AudioObjectID, a: AudioObjectPropertyAddress) -> Option<T> {
|
||||
let mut v = T::default();
|
||||
let mut size = std::mem::size_of::<T>() as u32;
|
||||
let status = AudioHardwareServiceGetPropertyData(
|
||||
object,
|
||||
&a,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
&mut size,
|
||||
&mut v as *mut T as *mut c_void,
|
||||
);
|
||||
(status == 0).then_some(v)
|
||||
}
|
||||
|
||||
unsafe fn get_array<T: Copy + Default>(object: AudioObjectID, selector: u32) -> AudioResult<Vec<T>> {
|
||||
let a = addr(selector);
|
||||
let mut size = 0u32;
|
||||
|
||||
+68
-14
@@ -5,16 +5,19 @@
|
||||
//! (see [`worker`]) so they may hold thread-affine handles (COM objects, the
|
||||
//! PulseAudio mainloop, CoreAudio taps) without being `Send`.
|
||||
//!
|
||||
//! | OS | Mechanism | Per-app volume | Per-app mute |
|
||||
//! |---------|---------------------------------------------|----------------|--------------|
|
||||
//! | Windows | WASAPI `IAudioSessionManager2` sessions | yes | yes |
|
||||
//! | Linux | PulseAudio / PipeWire-pulse sink inputs | yes | yes |
|
||||
//! | macOS | Core Audio process taps (macOS 14.2+) | **no** | yes |
|
||||
//! | OS | Mechanism | Per-app volume | Per-app mute | Per-app device |
|
||||
//! |---------|-----------------------------------------|----------------|--------------|----------------|
|
||||
//! | Windows | WASAPI `IAudioSessionManager2` sessions | yes | yes | yes |
|
||||
//! | Linux | PulseAudio / PipeWire-pulse sink inputs | yes | yes | yes |
|
||||
//! | macOS | Core Audio process taps (macOS 14.2+) | **no** | yes | **no** |
|
||||
//!
|
||||
//! macOS has no public API for setting another process's volume. HushKey mutes an
|
||||
//! app by creating a *muted process tap* on it, which silences that process while
|
||||
//! System volume, system mute and switching the default output device work on all three.
|
||||
//!
|
||||
//! macOS has no public API for setting another process's volume or output device. HushKey
|
||||
//! mutes an app by creating a *muted process tap* on it, which silences that process while
|
||||
//! the tap exists. Arbitrary volume levels are not possible — the backend reports
|
||||
//! `per_app_volume: false` and the UI hides volume levels instead of faking them.
|
||||
//! `per_app_volume: false` / `per_app_device: false` and the UI hides those controls
|
||||
//! instead of faking them.
|
||||
|
||||
mod mute;
|
||||
pub mod worker;
|
||||
@@ -55,12 +58,39 @@ pub struct AudioApp {
|
||||
pub muted: bool,
|
||||
/// Executable path for icon lookup, when known.
|
||||
pub exe_path: Option<PathBuf>,
|
||||
/// [`OutputDevice::id`] this app is explicitly routed to; `None` = follows the system default.
|
||||
pub device: Option<String>,
|
||||
/// Whether this app's output device can be changed (false for e.g. Windows system sounds).
|
||||
pub routable: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
/// An active playback device (speakers, headphones, HDMI, virtual cable…).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OutputDevice {
|
||||
/// Backend-specific stable id (MMDevice id, PulseAudio sink name, Core Audio UID).
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub is_default: bool,
|
||||
}
|
||||
|
||||
/// Volume and mute of the system default output device.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct MasterVolume {
|
||||
/// 0.0..=1.0. `None` when the device has no volume control (some HDMI/USB outputs).
|
||||
pub volume: Option<f32>,
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct Capabilities {
|
||||
pub per_app_volume: bool,
|
||||
pub per_app_mute: bool,
|
||||
/// Per-app output device routing.
|
||||
pub per_app_device: bool,
|
||||
/// System volume / mute of the default output device.
|
||||
pub master_volume: bool,
|
||||
/// Listing output devices and switching the system default.
|
||||
pub output_devices: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -68,7 +98,6 @@ pub enum AudioError {
|
||||
/// No running app has this key right now.
|
||||
NotRunning(AppKey),
|
||||
/// The platform can't do this (see the capability table above).
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
Unsupported(&'static str),
|
||||
/// The OS needs a permission the user hasn't granted (macOS audio capture).
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
@@ -115,10 +144,7 @@ pub trait AudioController {
|
||||
/// idle ones that aren't currently producing sound. One entry per [`AppKey`].
|
||||
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>>;
|
||||
|
||||
/// Set the volume of every session of `app` (0.0..=1.0).
|
||||
/// Part of the backend contract (and `--list` diagnostics); the UI currently toggles
|
||||
/// mute only, which preserves the user's own level in the OS mixer.
|
||||
#[allow(dead_code)]
|
||||
/// Set the volume of every session of `app` (0.0..=1.0). Independent of the mute flag.
|
||||
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()>;
|
||||
|
||||
/// Mute/unmute every session of `app`. Uses the OS mixer's own mute flag, so the
|
||||
@@ -151,6 +177,34 @@ pub trait AudioController {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Active output devices, default first is *not* guaranteed (check `is_default`).
|
||||
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Make `id` the system default output device.
|
||||
fn set_default_output_device(&mut self, _id: &str) -> AudioResult<()> {
|
||||
Err(AudioError::Unsupported("switching the output device"))
|
||||
}
|
||||
|
||||
/// Volume / mute of the default output device.
|
||||
fn master_volume(&mut self) -> AudioResult<MasterVolume> {
|
||||
Err(AudioError::Unsupported("system volume"))
|
||||
}
|
||||
|
||||
fn set_master_volume(&mut self, _volume: f32) -> AudioResult<()> {
|
||||
Err(AudioError::Unsupported("system volume"))
|
||||
}
|
||||
|
||||
fn set_master_mute(&mut self, _muted: bool) -> AudioResult<()> {
|
||||
Err(AudioError::Unsupported("system mute"))
|
||||
}
|
||||
|
||||
/// Route every stream of `app` to `device`, or back to the system default with `None`.
|
||||
fn set_app_output_device(&mut self, _app: &str, _device: Option<&str>) -> AudioResult<()> {
|
||||
Err(AudioError::Unsupported("per-app output devices"))
|
||||
}
|
||||
|
||||
/// Best-effort app icon. Default: none (UI shows a letter avatar).
|
||||
fn app_icon(&mut self, _app: &AudioApp) -> Option<IconData> {
|
||||
None
|
||||
|
||||
+3
-1
@@ -22,6 +22,8 @@ impl NullController {
|
||||
volume: Some(1.0),
|
||||
muted: *muted,
|
||||
exe_path: None,
|
||||
device: None,
|
||||
routable: true,
|
||||
})
|
||||
.collect(),
|
||||
mute_calls: 0,
|
||||
@@ -39,7 +41,7 @@ impl AudioController for NullController {
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { per_app_volume: true, per_app_mute: true }
|
||||
Capabilities { per_app_volume: true, per_app_mute: true, ..Capabilities::default() }
|
||||
}
|
||||
|
||||
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||
|
||||
+295
-10
@@ -5,26 +5,44 @@
|
||||
//! active render device**, not just the default one, so apps routed to headphones
|
||||
//! or a virtual device are found too. Sessions are grouped by executable name.
|
||||
//!
|
||||
//! Full per-app volume and mute are natively supported (`ISimpleAudioVolume`).
|
||||
//! Full per-app volume and mute are natively supported (`ISimpleAudioVolume`). System
|
||||
//! volume uses `IAudioEndpointVolume` on the default device.
|
||||
//!
|
||||
//! # Undocumented interfaces
|
||||
//! Windows has no *public* API to change the default output device or an app's output
|
||||
//! device, yet both are what the Sound settings page does. HushKey uses the same private
|
||||
//! COM interfaces as EarTrumpet, SoundSwitch and friends:
|
||||
//! - `IPolicyConfig` (`CPolicyConfigClient`) → `SetDefaultEndpoint`, stable since Vista.
|
||||
//! - `IAudioPolicyConfigFactory` (`Windows.Media.Internal.AudioPolicyConfig`) →
|
||||
//! `Set/GetPersistedDefaultAudioEndpoint`, Windows 10 1803+. Its IID changed in 21H2,
|
||||
//! so both are tried. If neither works the feature is reported unsupported instead of
|
||||
//! failing. Windows itself persists the per-app choice (by executable), like the
|
||||
//! "App volume and device preferences" page.
|
||||
//!
|
||||
//! Threading: this type must stay on the thread that created it (COM MTA init).
|
||||
|
||||
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, IconData};
|
||||
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, IconData, MasterVolume, OutputDevice};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ffi::c_void;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use windows::core::{Interface, HSTRING, PCWSTR, PWSTR};
|
||||
use windows::core::{Interface, GUID, HRESULT, HSTRING, PCWSTR, PWSTR};
|
||||
use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
|
||||
use windows::Win32::Foundation::{CloseHandle, S_OK};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
DeleteObject, GetDC, GetDIBits, GetObjectW, ReleaseDC, BITMAP, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS,
|
||||
};
|
||||
use windows::Win32::Media::Audio::Endpoints::IAudioEndpointVolume;
|
||||
use windows::Win32::Media::Audio::{
|
||||
eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, IMMDeviceEnumerator,
|
||||
ISimpleAudioVolume, MMDeviceEnumerator, DEVICE_STATE_ACTIVE,
|
||||
eConsole, eMultimedia, eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, IMMDevice,
|
||||
IMMDeviceEnumerator, ISimpleAudioVolume, MMDeviceEnumerator, DEVICE_STATE_ACTIVE,
|
||||
};
|
||||
use windows::Win32::Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW};
|
||||
use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED};
|
||||
use windows::Win32::System::Com::StructuredStorage::PropVariantToStringAlloc;
|
||||
use windows::Win32::System::Com::{
|
||||
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED, STGM_READ,
|
||||
};
|
||||
use windows::Win32::System::Threading::{
|
||||
OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
|
||||
};
|
||||
@@ -34,6 +52,103 @@ use windows::Win32::UI::WindowsAndMessaging::{DestroyIcon, GetIconInfo, HICON, I
|
||||
const SYSTEM_SOUNDS_KEY: &str = "system-sounds";
|
||||
const ICON_SIZE: u32 = 64;
|
||||
|
||||
// ── Private policy-config interfaces (see module docs) ─────────────────────────────
|
||||
// Only the methods HushKey calls have real signatures; the others are vtable padding.
|
||||
|
||||
const CLSID_POLICY_CONFIG_CLIENT: GUID = GUID::from_u128(0x870af99c_171d_4f9e_af0d_e63df40c2bc9);
|
||||
|
||||
const AUDIO_POLICY_CONFIG_CLASS: &str = "Windows.Media.Internal.AudioPolicyConfig";
|
||||
/// IID since Windows 10 21H2 (build 21390+), then the one used by 1803–21H1.
|
||||
const AUDIO_POLICY_CONFIG_IIDS: [GUID; 2] =
|
||||
[GUID::from_u128(0xab3d4648_e242_459f_b02f_541c70306324), GUID::from_u128(0x2a59116d_6c4f_45e0_a74f_707e3fef9258)];
|
||||
const MMDEVAPI_PREFIX: &str = r"\\?\SWD#MMDEVAPI#";
|
||||
const RENDER_INTERFACE_SUFFIX: &str = "#{e6327cad-dcec-4949-ae8a-991e976a79d2}";
|
||||
|
||||
mod policy {
|
||||
#![allow(non_snake_case, dead_code)]
|
||||
use std::ffi::c_void;
|
||||
use windows::core::{IUnknown, IUnknown_Vtbl, HRESULT, PCWSTR};
|
||||
use windows::Win32::Media::Audio::{EDataFlow, ERole};
|
||||
|
||||
#[windows::core::interface("f8679f50-850a-41cf-9c72-430f290290c8")]
|
||||
pub unsafe trait IPolicyConfig: IUnknown {
|
||||
pub fn GetMixFormat(&self) -> HRESULT;
|
||||
pub fn GetDeviceFormat(&self) -> HRESULT;
|
||||
pub fn ResetDeviceFormat(&self) -> HRESULT;
|
||||
pub fn SetDeviceFormat(&self) -> HRESULT;
|
||||
pub fn GetProcessingPeriod(&self) -> HRESULT;
|
||||
pub fn SetProcessingPeriod(&self) -> HRESULT;
|
||||
pub fn GetShareMode(&self) -> HRESULT;
|
||||
pub fn SetShareMode(&self) -> HRESULT;
|
||||
pub fn GetPropertyValue(&self) -> HRESULT;
|
||||
pub fn SetPropertyValue(&self) -> HRESULT;
|
||||
pub fn SetDefaultEndpoint(&self, device_id: PCWSTR, role: ERole) -> HRESULT;
|
||||
pub fn SetEndpointVisibility(&self) -> HRESULT;
|
||||
}
|
||||
|
||||
// The IID here is only used by `cast()`, which HushKey never does: the factory is
|
||||
// obtained via `RoGetActivationFactory` with whichever IID the OS accepts (same layout).
|
||||
#[windows::core::interface("ab3d4648-e242-459f-b02f-541c70306324")]
|
||||
pub unsafe trait IAudioPolicyConfigFactory: IUnknown {
|
||||
// IInspectable
|
||||
pub fn GetIids(&self) -> HRESULT;
|
||||
pub fn GetRuntimeClassName(&self) -> HRESULT;
|
||||
pub fn GetTrustLevel(&self) -> HRESULT;
|
||||
pub fn add_CtxVolumeChange(&self) -> HRESULT;
|
||||
pub fn remove_CtxVolumeChanged(&self) -> HRESULT;
|
||||
pub fn add_RingerVibrateStateChanged(&self) -> HRESULT;
|
||||
pub fn remove_RingerVibrateStateChange(&self) -> HRESULT;
|
||||
pub fn SetVolumeGroupGainForId(&self) -> HRESULT;
|
||||
pub fn GetVolumeGroupGainForId(&self) -> HRESULT;
|
||||
pub fn GetActiveVolumeGroupForEndpointId(&self) -> HRESULT;
|
||||
pub fn GetVolumeGroupsForEndpoint(&self) -> HRESULT;
|
||||
pub fn GetCurrentVolumeContext(&self) -> HRESULT;
|
||||
pub fn SetVolumeGroupMuteForId(&self) -> HRESULT;
|
||||
pub fn GetVolumeGroupMuteForId(&self) -> HRESULT;
|
||||
pub fn SetRingerVibrateState(&self) -> HRESULT;
|
||||
pub fn GetRingerVibrateState(&self) -> HRESULT;
|
||||
pub fn SetPreferredChatApplication(&self) -> HRESULT;
|
||||
pub fn ResetPreferredChatApplication(&self) -> HRESULT;
|
||||
pub fn GetPreferredChatApplication(&self) -> HRESULT;
|
||||
pub fn GetCurrentChatApplications(&self) -> HRESULT;
|
||||
pub fn add_ChatContextChanged(&self) -> HRESULT;
|
||||
pub fn remove_ChatContextChanged(&self) -> HRESULT;
|
||||
// `device_id` is a borrowed HSTRING handle (null = back to the system default).
|
||||
pub fn SetPersistedDefaultAudioEndpoint(
|
||||
&self,
|
||||
pid: u32,
|
||||
flow: EDataFlow,
|
||||
role: ERole,
|
||||
device_id: *mut c_void,
|
||||
) -> HRESULT;
|
||||
// Writes an owned HSTRING handle to `device_id` (null when the app follows the default).
|
||||
pub fn GetPersistedDefaultAudioEndpoint(
|
||||
&self,
|
||||
pid: u32,
|
||||
flow: EDataFlow,
|
||||
role: ERole,
|
||||
device_id: *mut *mut c_void,
|
||||
) -> HRESULT;
|
||||
pub fn ClearAllPersistedApplicationDefaultEndpoints(&self) -> HRESULT;
|
||||
}
|
||||
}
|
||||
use policy::{IAudioPolicyConfigFactory, IPolicyConfig};
|
||||
|
||||
fn audio_policy_factory() -> Option<IAudioPolicyConfigFactory> {
|
||||
windows::core::link!("api-ms-win-core-winrt-l1-1-0.dll" "system" fn RoGetActivationFactory(class: *mut c_void, iid: *const GUID, factory: *mut *mut c_void) -> HRESULT);
|
||||
let class = HSTRING::from(AUDIO_POLICY_CONFIG_CLASS);
|
||||
for iid in &AUDIO_POLICY_CONFIG_IIDS {
|
||||
let mut raw: *mut c_void = std::ptr::null_mut();
|
||||
// SAFETY: HSTRING is a transparent handle; the factory comes back +1 and from_raw adopts it.
|
||||
let hr = unsafe { RoGetActivationFactory(std::mem::transmute_copy(&class), iid, &mut raw) };
|
||||
if hr.is_ok() && !raw.is_null() {
|
||||
return Some(unsafe { IAudioPolicyConfigFactory::from_raw(raw) });
|
||||
}
|
||||
}
|
||||
log::info!("per-app output devices unavailable (AudioPolicyConfig factory not found)");
|
||||
None
|
||||
}
|
||||
|
||||
fn err(context: &str, e: windows::core::Error) -> AudioError {
|
||||
AudioError::Backend(format!("{context}: {e}"))
|
||||
}
|
||||
@@ -62,6 +177,8 @@ impl Drop for ComGuard {
|
||||
pub struct WasapiController {
|
||||
enumerator: IMMDeviceEnumerator,
|
||||
procs: HashMap<u32, ProcInfo>,
|
||||
device_names: HashMap<String, String>,
|
||||
policy: Option<IAudioPolicyConfigFactory>,
|
||||
_com: ComGuard,
|
||||
}
|
||||
|
||||
@@ -72,10 +189,55 @@ impl WasapiController {
|
||||
let guard = ComGuard;
|
||||
let enumerator: IMMDeviceEnumerator =
|
||||
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|e| err("MMDeviceEnumerator", e))?;
|
||||
Ok(Self { enumerator, procs: HashMap::new(), _com: guard })
|
||||
Ok(Self {
|
||||
enumerator,
|
||||
procs: HashMap::new(),
|
||||
device_names: HashMap::new(),
|
||||
policy: audio_policy_factory(),
|
||||
_com: guard,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn default_device(&self) -> AudioResult<IMMDevice> {
|
||||
unsafe { self.enumerator.GetDefaultAudioEndpoint(eRender, eMultimedia) }.map_err(|e| err("default device", e))
|
||||
}
|
||||
|
||||
fn endpoint_volume(&self) -> AudioResult<IAudioEndpointVolume> {
|
||||
let device = self.default_device()?;
|
||||
unsafe { device.Activate::<IAudioEndpointVolume>(CLSCTX_ALL, None) }.map_err(|e| err("endpoint volume", e))
|
||||
}
|
||||
|
||||
fn device_name(&mut self, device: &IMMDevice, id: &str) -> String {
|
||||
if let Some(n) = self.device_names.get(id) {
|
||||
return n.clone();
|
||||
}
|
||||
let name = unsafe {
|
||||
device
|
||||
.OpenPropertyStore(STGM_READ)
|
||||
.and_then(|store| store.GetValue(&PKEY_Device_FriendlyName))
|
||||
.and_then(|value| PropVariantToStringAlloc(&value))
|
||||
.ok()
|
||||
.map(take_pwstr)
|
||||
}
|
||||
.filter(|n| !n.is_empty())
|
||||
.unwrap_or_else(|| "Unknown device".to_owned());
|
||||
self.device_names.insert(id.to_owned(), name.clone());
|
||||
name
|
||||
}
|
||||
|
||||
/// The device an app is explicitly routed to, from the first of its processes that has one.
|
||||
fn persisted_device(&self, pids: &[u32]) -> Option<String> {
|
||||
let policy = self.policy.as_ref()?;
|
||||
pids.iter().filter(|p| **p != 0).find_map(|&pid| unsafe {
|
||||
let mut raw: *mut c_void = std::ptr::null_mut();
|
||||
policy.GetPersistedDefaultAudioEndpoint(pid, eRender, eMultimedia, &mut raw).ok().ok()?;
|
||||
// SAFETY: an owned HSTRING handle (or null = empty); HSTRING frees it on drop.
|
||||
let s: HSTRING = std::mem::transmute::<*mut c_void, HSTRING>(raw);
|
||||
unpack_device_id(&s.to_string_lossy())
|
||||
})
|
||||
}
|
||||
|
||||
fn proc_info(&mut self, pid: u32) -> ProcInfo {
|
||||
if let Some(p) = self.procs.get(&pid) {
|
||||
return p.clone();
|
||||
@@ -160,7 +322,13 @@ impl AudioController for WasapiController {
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
Capabilities { per_app_volume: true, per_app_mute: true }
|
||||
Capabilities {
|
||||
per_app_volume: true,
|
||||
per_app_mute: true,
|
||||
per_app_device: self.policy.is_some(),
|
||||
master_volume: true,
|
||||
output_devices: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||
@@ -181,14 +349,17 @@ impl AudioController for WasapiController {
|
||||
let mut apps: Vec<AudioApp> = grouped
|
||||
.into_iter()
|
||||
.map(|(key, (pids, vols, muted))| {
|
||||
let (name, exe_path) = if key == SYSTEM_SOUNDS_KEY {
|
||||
let system = key == SYSTEM_SOUNDS_KEY;
|
||||
let (name, exe_path) = if system {
|
||||
("System Sounds".to_owned(), None)
|
||||
} else {
|
||||
let info = pids.iter().find_map(|p| self.procs.get(p)).cloned();
|
||||
info.map(|i| (i.name, i.path)).unwrap_or_else(|| (key.clone(), None))
|
||||
};
|
||||
let volume = Some(vols.iter().sum::<f32>() / vols.len().max(1) as f32);
|
||||
AudioApp { key, name, pids, volume, muted, exe_path }
|
||||
let device = if system { None } else { self.persisted_device(&pids) };
|
||||
let routable = !system && self.policy.is_some();
|
||||
AudioApp { key, name, pids, volume, muted, exe_path, device, routable }
|
||||
})
|
||||
.collect();
|
||||
apps.sort_by_key(|a| a.name.to_lowercase());
|
||||
@@ -204,11 +375,112 @@ impl AudioController for WasapiController {
|
||||
self.for_each_session_of(app, |s| unsafe { s.SetMute(muted, std::ptr::null()) })
|
||||
}
|
||||
|
||||
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||
let default_id = self.default_device().ok().and_then(|d| unsafe { d.GetId() }.ok()).map(take_pwstr);
|
||||
let mut out = Vec::new();
|
||||
unsafe {
|
||||
let devices = self
|
||||
.enumerator
|
||||
.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE)
|
||||
.map_err(|e| err("EnumAudioEndpoints", e))?;
|
||||
for i in 0..devices.GetCount().map_err(|e| err("GetCount", e))? {
|
||||
let Ok(device) = devices.Item(i) else { continue };
|
||||
let Ok(id) = device.GetId().map(take_pwstr) else { continue };
|
||||
let name = self.device_name(&device, &id);
|
||||
out.push(OutputDevice { is_default: default_id.as_deref() == Some(id.as_str()), id, name });
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|d| d.name.to_lowercase());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn set_default_output_device(&mut self, id: &str) -> AudioResult<()> {
|
||||
unsafe {
|
||||
let policy: IPolicyConfig =
|
||||
CoCreateInstance(&CLSID_POLICY_CONFIG_CLIENT, None, CLSCTX_ALL).map_err(|e| err("PolicyConfig", e))?;
|
||||
let wide_id = HSTRING::from(id);
|
||||
for role in [eConsole, eMultimedia] {
|
||||
policy
|
||||
.SetDefaultEndpoint(PCWSTR(wide_id.as_ptr()), role)
|
||||
.ok()
|
||||
.map_err(|e| err("SetDefaultEndpoint", e))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn master_volume(&mut self) -> AudioResult<MasterVolume> {
|
||||
let ep = self.endpoint_volume()?;
|
||||
unsafe {
|
||||
Ok(MasterVolume {
|
||||
volume: ep.GetMasterVolumeLevelScalar().ok(),
|
||||
muted: ep.GetMute().map(|b| b.as_bool()).unwrap_or(false),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn set_master_volume(&mut self, volume: f32) -> AudioResult<()> {
|
||||
let ep = self.endpoint_volume()?;
|
||||
unsafe { ep.SetMasterVolumeLevelScalar(volume.clamp(0.0, 1.0), std::ptr::null()) }
|
||||
.map_err(|e| err("system volume", e))
|
||||
}
|
||||
|
||||
fn set_master_mute(&mut self, muted: bool) -> AudioResult<()> {
|
||||
let ep = self.endpoint_volume()?;
|
||||
unsafe { ep.SetMute(muted, std::ptr::null()) }.map_err(|e| err("system mute", e))
|
||||
}
|
||||
|
||||
fn set_app_output_device(&mut self, app: &str, device: Option<&str>) -> AudioResult<()> {
|
||||
if app == SYSTEM_SOUNDS_KEY {
|
||||
return Err(AudioError::Unsupported("routing system sounds"));
|
||||
}
|
||||
let Some(policy) = self.policy.clone() else {
|
||||
return Err(AudioError::Unsupported("per-app output devices (needs Windows 10 1803 or newer)"));
|
||||
};
|
||||
let mut pids: Vec<u32> = self.sessions()?.into_iter().filter(|s| s.key == app).map(|s| s.pid).collect();
|
||||
pids.sort_unstable();
|
||||
pids.dedup();
|
||||
if pids.is_empty() {
|
||||
return Err(AudioError::NotRunning(app.to_owned()));
|
||||
}
|
||||
let packed = device.map(|id| HSTRING::from(format!("{MMDEVAPI_PREFIX}{id}{RENDER_INTERFACE_SUFFIX}")));
|
||||
// SAFETY: a borrowed handle that outlives the calls; null resets the app to the default.
|
||||
let raw: *mut c_void =
|
||||
packed.as_ref().map(|h| unsafe { std::mem::transmute_copy(h) }).unwrap_or(std::ptr::null_mut());
|
||||
for pid in pids {
|
||||
for role in [eConsole, eMultimedia] {
|
||||
unsafe { policy.SetPersistedDefaultAudioEndpoint(pid, eRender, role, raw) }
|
||||
.ok()
|
||||
.map_err(|e| err("SetPersistedDefaultAudioEndpoint", e))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn app_icon(&mut self, app: &AudioApp) -> Option<IconData> {
|
||||
exe_icon(app.exe_path.as_deref()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy a CoTaskMem-allocated wide string and free it.
|
||||
fn take_pwstr(p: PWSTR) -> String {
|
||||
if p.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
unsafe {
|
||||
let s = p.to_string().unwrap_or_default();
|
||||
CoTaskMemFree(Some(p.0 as *const c_void));
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// `\\?\SWD#MMDEVAPI#{0.0.0.00000000}.{guid}#{e6327cad-…}` → `{0.0.0.00000000}.{guid}`.
|
||||
fn unpack_device_id(s: &str) -> Option<String> {
|
||||
let s = s.strip_prefix(MMDEVAPI_PREFIX).unwrap_or(s);
|
||||
let s = s.strip_suffix(RENDER_INTERFACE_SUFFIX).unwrap_or(s);
|
||||
(!s.is_empty()).then(|| s.to_owned())
|
||||
}
|
||||
|
||||
fn wide(path: &Path) -> Vec<u16> {
|
||||
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
@@ -337,3 +609,16 @@ unsafe fn hicon_to_rgba(icon: HICON) -> Option<IconData> {
|
||||
}
|
||||
Some(IconData { width: w as u32, height: h as u32, rgba: buf })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn device_id_round_trip() {
|
||||
let id = "{0.0.0.00000000}.{5c6a2d1e-7a3b-4c1d-9e2f-1a2b3c4d5e6f}";
|
||||
let packed = format!("{MMDEVAPI_PREFIX}{id}{RENDER_INTERFACE_SUFFIX}");
|
||||
assert_eq!(unpack_device_id(&packed).as_deref(), Some(id));
|
||||
assert_eq!(unpack_device_id(""), None);
|
||||
}
|
||||
}
|
||||
+123
-6
@@ -6,10 +6,16 @@
|
||||
//!
|
||||
//! The thread blocks on its channel when idle — zero CPU. The only periodic work is
|
||||
//! while "Mute All" is engaged: every 2 s it silences apps that started afterwards.
|
||||
//!
|
||||
//! Volume sliders send a command per mouse move; consecutive volume commands for the
|
||||
//! same target are coalesced so only the latest level is applied.
|
||||
|
||||
use super::mute::ToggleOutcome;
|
||||
use super::{create_controller, AudioApp, AudioError, Capabilities, IconData, MuteManager};
|
||||
use std::collections::HashSet;
|
||||
use super::{
|
||||
create_controller, AudioApp, AudioController, AudioError, Capabilities, IconData, MasterVolume, MuteManager,
|
||||
OutputDevice,
|
||||
};
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
@@ -30,9 +36,43 @@ pub enum AudioCommand {
|
||||
RestoreAll {
|
||||
from_hotkey: bool,
|
||||
},
|
||||
SetAppVolume {
|
||||
key: String,
|
||||
volume: f32,
|
||||
},
|
||||
SetMasterVolume(f32),
|
||||
SetMasterMute(bool),
|
||||
SetDefaultDevice(String),
|
||||
/// `device: None` routes the app back to the system default.
|
||||
SetAppDevice {
|
||||
key: String,
|
||||
device: Option<String>,
|
||||
},
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
impl AudioCommand {
|
||||
/// Commands where only the most recent one matters, keyed by target.
|
||||
fn coalesce_key(&self) -> Option<&str> {
|
||||
match self {
|
||||
AudioCommand::SetAppVolume { key, .. } => Some(key),
|
||||
AudioCommand::SetMasterVolume(_) => Some("@master"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace `cmd` with the newest queued command for the same target, removing the stale ones.
|
||||
fn coalesce(mut cmd: AudioCommand, pending: &mut VecDeque<AudioCommand>) -> AudioCommand {
|
||||
let Some(target) = cmd.coalesce_key().map(str::to_owned) else { return cmd };
|
||||
while let Some(pos) = pending.iter().position(|c| c.coalesce_key() == Some(&target)) {
|
||||
if let Some(newer) = pending.remove(pos) {
|
||||
cmd = newer;
|
||||
}
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum AudioEvent {
|
||||
Ready {
|
||||
@@ -41,6 +81,11 @@ pub enum AudioEvent {
|
||||
note: Option<&'static str>,
|
||||
},
|
||||
Apps(Vec<AudioApp>),
|
||||
/// Output devices and system volume. `master` is `None` when unsupported/unavailable.
|
||||
Output {
|
||||
devices: Vec<OutputDevice>,
|
||||
master: Option<MasterVolume>,
|
||||
},
|
||||
Icon {
|
||||
key: String,
|
||||
icon: IconData,
|
||||
@@ -118,8 +163,9 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
||||
let mut mute = MuteManager::default();
|
||||
let mut icons_sent: HashSet<String> = HashSet::new();
|
||||
|
||||
let publish_apps =
|
||||
|ctl: &mut dyn super::AudioController, icons_sent: &mut HashSet<String>| match ctl.list_audio_apps() {
|
||||
let caps = ctl.capabilities();
|
||||
let publish_apps = |ctl: &mut dyn AudioController, icons_sent: &mut HashSet<String>| {
|
||||
match ctl.list_audio_apps() {
|
||||
Ok(apps) => {
|
||||
for app in &apps {
|
||||
if icons_sent.insert(app.key.clone()) {
|
||||
@@ -131,10 +177,27 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
||||
sink(AudioEvent::Apps(apps));
|
||||
}
|
||||
Err(e) => sink(AudioEvent::Error { message: e.to_string(), from_hotkey: false }),
|
||||
};
|
||||
}
|
||||
if caps.output_devices || caps.master_volume {
|
||||
let devices = ctl.output_devices().unwrap_or_else(|e| {
|
||||
log::debug!("output devices: {e}");
|
||||
Vec::new()
|
||||
});
|
||||
let master = if caps.master_volume { ctl.master_volume().ok() } else { None };
|
||||
sink(AudioEvent::Output { devices, master });
|
||||
}
|
||||
};
|
||||
let report = |result: Result<(), AudioError>, what: &str| {
|
||||
if let Err(e) = result {
|
||||
sink(AudioEvent::Error { message: format!("{what}: {e}"), from_hotkey: false });
|
||||
}
|
||||
};
|
||||
let mut pending: VecDeque<AudioCommand> = VecDeque::new();
|
||||
|
||||
loop {
|
||||
let cmd = if mute.all_muted() {
|
||||
let cmd = if let Some(cmd) = pending.pop_front() {
|
||||
cmd
|
||||
} else if mute.all_muted() {
|
||||
match rx.recv_timeout(ENFORCE_INTERVAL) {
|
||||
Ok(cmd) => cmd,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
@@ -148,6 +211,12 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
||||
} else {
|
||||
rx.recv().unwrap_or(AudioCommand::Shutdown)
|
||||
};
|
||||
let cmd = if cmd.coalesce_key().is_some() {
|
||||
pending.extend(rx.try_iter());
|
||||
coalesce(cmd, &mut pending)
|
||||
} else {
|
||||
cmd
|
||||
};
|
||||
|
||||
match cmd {
|
||||
AudioCommand::Refresh => {
|
||||
@@ -176,6 +245,24 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
||||
}
|
||||
publish_apps(ctl.as_mut(), &mut icons_sent);
|
||||
}
|
||||
// Sliders: the UI already shows the new level, so no full republish per move.
|
||||
AudioCommand::SetAppVolume { key, volume } => match ctl.set_app_volume(&key, volume) {
|
||||
Ok(()) | Err(AudioError::NotRunning(_)) => {}
|
||||
Err(e) => report(Err(e), &key),
|
||||
},
|
||||
AudioCommand::SetMasterVolume(v) => report(ctl.set_master_volume(v), "System volume"),
|
||||
AudioCommand::SetMasterMute(m) => {
|
||||
report(ctl.set_master_mute(m), "System mute");
|
||||
publish_apps(ctl.as_mut(), &mut icons_sent);
|
||||
}
|
||||
AudioCommand::SetDefaultDevice(id) => {
|
||||
report(ctl.set_default_output_device(&id), "Output device");
|
||||
publish_apps(ctl.as_mut(), &mut icons_sent);
|
||||
}
|
||||
AudioCommand::SetAppDevice { key, device } => {
|
||||
report(ctl.set_app_output_device(&key, device.as_deref()), &key);
|
||||
publish_apps(ctl.as_mut(), &mut icons_sent);
|
||||
}
|
||||
AudioCommand::Shutdown => {
|
||||
if let Err(e) = mute.restore_all(ctl.as_mut()) {
|
||||
log::warn!("restore on shutdown failed: {e}");
|
||||
@@ -188,3 +275,33 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
||||
.expect("spawn audio thread");
|
||||
AudioHandle { tx, thread: Some(thread) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn vol(key: &str, v: f32) -> AudioCommand {
|
||||
AudioCommand::SetAppVolume { key: key.into(), volume: v }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coalesces_same_target_and_keeps_others_in_order() {
|
||||
let mut pending: VecDeque<AudioCommand> =
|
||||
[vol("a", 0.2), AudioCommand::Refresh, vol("b", 0.9), vol("a", 0.7), AudioCommand::SetMasterVolume(0.4)]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let cmd = coalesce(vol("a", 0.1), &mut pending);
|
||||
assert!(matches!(cmd, AudioCommand::SetAppVolume { ref key, volume } if key == "a" && volume == 0.7));
|
||||
assert_eq!(pending.len(), 3);
|
||||
assert!(matches!(pending[0], AudioCommand::Refresh));
|
||||
assert!(matches!(pending[1], AudioCommand::SetAppVolume { ref key, .. } if key == "b"));
|
||||
assert!(matches!(pending[2], AudioCommand::SetMasterVolume(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_volume_commands_pass_through() {
|
||||
let mut pending: VecDeque<AudioCommand> = [AudioCommand::Refresh].into_iter().collect();
|
||||
assert!(matches!(coalesce(AudioCommand::SetMasterMute(true), &mut pending), AudioCommand::SetMasterMute(true)));
|
||||
assert_eq!(pending.len(), 1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user