feat: HushKey 1.0.0 — per-app mute hotkeys for Windows, macOS and Linux

Native Rust tray app that binds global shortcuts to mute/unmute
individual applications' audio, plus a Mute All / Restore All shortcut.

- AudioController trait with per-OS backends: WASAPI sessions (Windows),
  Core Audio process taps (macOS 14.2+, mute only), PulseAudio/PipeWire
  sink inputs (Linux)
- Dedicated audio thread; hotkey presses go straight to it
- Snapshot-based Mute All that restores exactly the previous state
- Slint UI with software renderer; window destroyed on close
- Non-activating on-screen confirmation and tray icon flash
- TOML config, launch at login, start minimized, dark/light theme
- Procedurally drawn icon embedded into the Windows executable
- Docs, AGENTS.md, CLAUDE.md, contributing guide and CI for all three OSes
This commit is contained in:
X4Lo committed 2026-11-14 04:26:05 +00:00
commit 8f476dbe52
40 files changed
+11604

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
//! Linux backend: PulseAudio sink inputs (also works on PipeWire via `pipewire-pulse`,
//! the default on Fedora, Ubuntu 22.10+, Arch, etc.).
//!
//! 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.
//!
//! 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 libpulse_binding as pulse;
use pulse::callbacks::ListResult;
use pulse::context::{Context, FlagSet, State};
use pulse::mainloop::standard::{IterateResult, Mainloop};
use pulse::operation::{Operation, State as OpState};
use pulse::proplist::{properties, Proplist};
use pulse::volume::{ChannelVolumes, Volume};
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
#[derive(Clone)]
struct Input {
index: u32,
key: String,
name: String,
pid: u32,
muted: bool,
volume: f32,
channels: u8,
}
pub struct PulseController {
mainloop: Mainloop,
context: Context,
}
fn backend(msg: impl Into<String>) -> AudioError {
AudioError::Backend(msg.into())
}
impl PulseController {
pub fn new() -> AudioResult<Self> {
let mut props = Proplist::new().ok_or_else(|| backend("Proplist::new failed"))?;
let _ = props.set_str(properties::APPLICATION_NAME, "HushKey");
let _ = props.set_str(properties::APPLICATION_ID, "io.github.hushkey");
let mut mainloop = Mainloop::new().ok_or_else(|| backend("PulseAudio mainloop unavailable"))?;
let mut context = Context::new_with_proplist(&mainloop, "HushKey", &props)
.ok_or_else(|| backend("PulseAudio context failed"))?;
context
.connect(None, FlagSet::NOFLAGS, None)
.map_err(|e| backend(format!("cannot connect to PulseAudio/PipeWire: {e}")))?;
loop {
match mainloop.iterate(true) {
IterateResult::Success(_) => {}
IterateResult::Quit(_) | IterateResult::Err(_) => return Err(backend("PulseAudio mainloop failed")),
}
match context.get_state() {
State::Ready => break,
State::Failed | State::Terminated => {
return Err(backend("no PulseAudio server (is pipewire-pulse or pulseaudio running?)"))
}
_ => {}
}
}
Ok(Self { mainloop, context })
}
fn wait<T: ?Sized>(&mut self, op: Operation<T>) -> AudioResult<()> {
while op.get_state() == OpState::Running {
if let IterateResult::Quit(_) | IterateResult::Err(_) = self.mainloop.iterate(true) {
return Err(backend("PulseAudio connection lost"));
}
}
Ok(())
}
fn inputs(&mut self) -> AudioResult<Vec<Input>> {
let out: Rc<RefCell<Vec<Input>>> = Rc::default();
let sink = out.clone();
let op = self.context.introspect().get_sink_input_info_list(move |r| {
if let ListResult::Item(i) = r {
let get = |k: &str| i.proplist.get_str(k).filter(|s| !s.is_empty());
let binary = get(properties::APPLICATION_PROCESS_BINARY);
let app_name = get(properties::APPLICATION_NAME);
let key = binary.clone().or_else(|| app_name.clone()).unwrap_or_else(|| format!("stream-{}", i.index));
let name = app_name.or(binary).unwrap_or_else(|| key.clone());
let pid = get(properties::APPLICATION_PROCESS_ID).and_then(|p| p.parse().ok()).unwrap_or(0);
sink.borrow_mut().push(Input {
index: i.index,
key: key.to_lowercase(),
name,
pid,
muted: i.mute,
volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32,
channels: i.volume.len(),
});
}
});
self.wait(op)?;
let v = out.borrow().clone();
Ok(v)
}
fn for_each_input_of(
&mut self,
app: &str,
mut f: impl FnMut(&mut Self, &Input) -> Operation<dyn FnMut(bool)>,
) -> AudioResult<()> {
let inputs: Vec<Input> = self.inputs()?.into_iter().filter(|i| i.key == app).collect();
if inputs.is_empty() {
return Err(AudioError::NotRunning(app.into()));
}
for input in &inputs {
let op = f(self, input);
self.wait(op)?;
}
Ok(())
}
}
impl AudioController for PulseController {
fn backend_name(&self) -> &'static str {
"PulseAudio / PipeWire"
}
fn capabilities(&self) -> Capabilities {
Capabilities { per_app_volume: true, per_app_mute: true }
}
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
let mut grouped: BTreeMap<String, Vec<Input>> = BTreeMap::new();
for i in self.inputs()? {
grouped.entry(i.key.clone()).or_default().push(i);
}
let mut apps: Vec<AudioApp> = grouped
.into_iter()
.map(|(key, ins)| {
let mut pids: Vec<u32> = ins.iter().map(|i| i.pid).filter(|p| *p != 0).collect();
pids.dedup();
AudioApp {
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),
exe_path: pids.first().and_then(|p| std::fs::read_link(format!("/proc/{p}/exe")).ok()),
pids,
key,
}
})
.collect();
apps.sort_by_key(|a| a.name.to_lowercase());
Ok(apps)
}
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()> {
let level = Volume((volume.clamp(0.0, 1.0) * Volume::NORMAL.0 as f32) as u32);
self.for_each_input_of(app, |me, input| {
let mut cv = ChannelVolumes::default();
cv.set(input.channels.max(1), level);
me.context.introspect().set_sink_input_volume(input.index, &cv, None)
})
}
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))
}
}
+360
View File
@@ -0,0 +1,360 @@
//! macOS backend: Core Audio **process taps** (macOS 14.2+).
//!
//! # Platform limitation — read before editing
//!
//! macOS has no public API to set another application's output volume. The options are:
//! 1. Install a virtual audio driver (what SoundSource / Background Music do) — needs a
//! kernel/HAL plug-in install and admin rights. Rejected: too invasive for a hotkey tool.
//! 2. **Core Audio process taps** (`AudioHardwareCreateProcessTap`, macOS 14.2+). A tap
//! created with `muteBehavior = CATapMuted` silences the tapped process for as long as
//! the tap exists. ← what HushKey uses.
//!
//! Consequences:
//! - Per-app **mute works**; per-app **volume levels do not** (`per_app_volume: false`).
//! `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
//! `dlsym` (never hard-link them, or the binary would fail to launch on macOS 13) and
//! fall back to listing apps read-only.
//! - The user must grant the audio-capture permission ("Screen & System Audio Recording"
//! in System Settings → Privacy & Security). The app bundle's Info.plist needs
//! `NSAudioCaptureUsageDescription` (see docs/building.md).
//! - Crash-safe: taps belong to our process, so if HushKey exits or crashes every muted
//! app becomes audible again automatically.
//!
//! **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 objc2::msg_send;
use objc2::rc::Retained;
use objc2::runtime::{AnyClass, AnyObject};
use objc2_foundation::{NSArray, NSNumber, NSString};
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::path::PathBuf;
type AudioObjectID = u32;
type OSStatus = i32;
#[repr(C)]
struct AudioObjectPropertyAddress {
selector: u32,
scope: u32,
element: u32,
}
const fn fourcc(s: &[u8; 4]) -> u32 {
((s[0] as u32) << 24) | ((s[1] as u32) << 16) | ((s[2] as u32) << 8) | (s[3] as u32)
}
const K_AUDIO_OBJECT_SYSTEM_OBJECT: AudioObjectID = 1;
const K_SCOPE_GLOBAL: u32 = fourcc(b"glob");
const K_ELEMENT_MAIN: u32 = 0;
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");
/// `CATapMuteBehavior.CATapMuted`
const CA_TAP_MUTED: isize = 1;
#[link(name = "CoreAudio", kind = "framework")]
extern "C" {
fn AudioObjectGetPropertyDataSize(
id: AudioObjectID,
addr: *const AudioObjectPropertyAddress,
qualifier_size: u32,
qualifier: *const c_void,
out_size: *mut u32,
) -> OSStatus;
fn AudioObjectGetPropertyData(
id: AudioObjectID,
addr: *const AudioObjectPropertyAddress,
qualifier_size: u32,
qualifier: *const c_void,
io_size: *mut u32,
out: *mut c_void,
) -> OSStatus;
}
type CreateTapFn = unsafe extern "C" fn(*mut AnyObject, *mut AudioObjectID) -> OSStatus;
type DestroyTapFn = unsafe extern "C" fn(AudioObjectID) -> OSStatus;
struct TapApi {
create: CreateTapFn,
destroy: DestroyTapFn,
description_class: &'static AnyClass,
}
impl TapApi {
/// Resolve the macOS 14.2+ tap API at runtime.
fn load() -> Option<Self> {
unsafe {
let create = libc::dlsym(libc::RTLD_DEFAULT, c"AudioHardwareCreateProcessTap".as_ptr());
let destroy = libc::dlsym(libc::RTLD_DEFAULT, c"AudioHardwareDestroyProcessTap".as_ptr());
if create.is_null() || destroy.is_null() {
return None;
}
Some(Self {
create: std::mem::transmute::<*mut c_void, CreateTapFn>(create),
destroy: std::mem::transmute::<*mut c_void, DestroyTapFn>(destroy),
description_class: AnyClass::get(c"CATapDescription")?,
})
}
}
}
struct Process {
object: AudioObjectID,
pid: u32,
running_output: bool,
key: String,
name: String,
path: Option<PathBuf>,
}
struct Tap {
id: AudioObjectID,
objects: Vec<AudioObjectID>,
}
pub struct CoreAudioTapController {
api: Option<TapApi>,
taps: HashMap<String, Tap>,
}
impl CoreAudioTapController {
pub fn new() -> AudioResult<Self> {
let api = TapApi::load();
if api.is_none() {
log::warn!("Core Audio process taps unavailable (needs macOS 14.2+); muting disabled");
}
Ok(Self { api, taps: HashMap::new() })
}
fn processes(&self) -> AudioResult<Vec<Process>> {
let objects: Vec<AudioObjectID> = unsafe { get_array(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_PROCESS_OBJECT_LIST)? };
let mut out = Vec::new();
for object in objects {
let pid = unsafe { get_scalar::<i32>(object, K_PROCESS_PID) }.unwrap_or(-1);
if pid <= 0 || pid as u32 == std::process::id() {
continue;
}
let running_output = unsafe { get_scalar::<u32>(object, K_PROCESS_IS_RUNNING_OUTPUT) }.unwrap_or(0) != 0;
let bundle_id = unsafe { get_cfstring(object, K_PROCESS_BUNDLE_ID) }.unwrap_or_default();
let path = pid_path(pid);
let (key, name) = identify(path.as_ref(), &bundle_id);
out.push(Process { object, pid: pid as u32, running_output, key, name, path });
}
Ok(out)
}
fn create_tap(&self, objects: &[AudioObjectID]) -> AudioResult<AudioObjectID> {
let api = self.api.as_ref().ok_or(AudioError::Unsupported("per-app mute requires macOS 14.2 or newer"))?;
unsafe {
let numbers: Vec<Retained<NSNumber>> = objects.iter().map(|o| NSNumber::new_u32(*o)).collect();
let array = NSArray::from_retained_slice(&numbers);
let alloc: *mut AnyObject = msg_send![api.description_class, alloc];
let desc: *mut AnyObject = msg_send![alloc, initStereoMixdownOfProcesses: &*array];
if desc.is_null() {
return Err(AudioError::Backend("CATapDescription init failed".into()));
}
let desc: Retained<AnyObject> = Retained::from_raw(desc).expect("non-null");
let name = NSString::from_str("HushKey mute");
let _: () = msg_send![&*desc, setName: &*name];
let _: () = msg_send![&*desc, setPrivate: true];
let _: () = msg_send![&*desc, setMuteBehavior: CA_TAP_MUTED];
let mut tap: AudioObjectID = 0;
let status = (api.create)(Retained::as_ptr(&desc) as *mut AnyObject, &mut tap);
if status != 0 {
return Err(AudioError::PermissionDenied(format!(
"macOS refused to create an audio tap (OSStatus {status}). Allow HushKey under System Settings → \
Privacy & Security → Screen & System Audio Recording."
)));
}
Ok(tap)
}
}
fn destroy_tap(&mut self, key: &str) {
if let (Some(tap), Some(api)) = (self.taps.remove(key), self.api.as_ref()) {
let status = unsafe { (api.destroy)(tap.id) };
if status != 0 {
log::warn!("AudioHardwareDestroyProcessTap({}) = {status}", tap.id);
}
}
}
}
impl Drop for CoreAudioTapController {
fn drop(&mut self) {
let keys: Vec<String> = self.taps.keys().cloned().collect();
for k in keys {
self.destroy_tap(&k);
}
}
}
impl AudioController for CoreAudioTapController {
fn backend_name(&self) -> &'static str {
"macOS Core Audio process taps"
}
fn capabilities(&self) -> Capabilities {
Capabilities { per_app_volume: false, per_app_mute: self.api.is_some() }
}
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
let procs = self.processes()?;
let mut grouped: BTreeMap<String, Vec<&Process>> = BTreeMap::new();
for p in &procs {
// Show real apps (inside an .app bundle), anything currently playing, and anything we muted.
let is_app = p.path.as_ref().is_some_and(|p| p.to_string_lossy().contains(".app/"));
if is_app || p.running_output || self.taps.contains_key(&p.key) {
grouped.entry(p.key.clone()).or_default().push(p);
}
}
// Drop taps for apps that quit; re-tap apps whose process set changed (new helper process).
let stale: Vec<String> = self.taps.keys().filter(|k| !grouped.contains_key(*k)).cloned().collect();
for k in stale {
self.destroy_tap(&k);
}
let mut retap = Vec::new();
for (key, ps) in &grouped {
if let Some(tap) = self.taps.get(key) {
let mut now: Vec<AudioObjectID> = ps.iter().map(|p| p.object).collect();
now.sort_unstable();
if now != tap.objects {
retap.push((key.clone(), now));
}
}
}
for (key, objects) in retap {
self.destroy_tap(&key);
if let Ok(id) = self.create_tap(&objects) {
self.taps.insert(key, Tap { id, objects });
}
}
let apps = grouped
.into_iter()
.map(|(key, ps)| AudioApp {
muted: self.taps.contains_key(&key),
name: ps[0].name.clone(),
pids: ps.iter().map(|p| p.pid).collect(),
volume: None, // not readable per-app on macOS
exe_path: ps[0].path.clone(),
key,
})
.collect::<Vec<_>>();
let mut apps = apps;
apps.sort_by_key(|a| a.name.to_lowercase());
Ok(apps)
}
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()> {
if volume <= 0.0 {
self.set_app_mute(app, true)
} else if volume >= 1.0 {
self.set_app_mute(app, false)
} else {
Err(AudioError::Unsupported("per-app volume levels on macOS (mute/unmute only)"))
}
}
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()> {
let mut objects: Vec<AudioObjectID> =
self.processes()?.into_iter().filter(|p| p.key == app).map(|p| p.object).collect();
if objects.is_empty() {
self.destroy_tap(app);
return Err(AudioError::NotRunning(app.into()));
}
objects.sort_unstable();
if muted {
if !self.taps.contains_key(app) {
let id = self.create_tap(&objects)?;
self.taps.insert(app.to_owned(), Tap { id, objects });
}
} else {
self.destroy_tap(app);
}
Ok(())
}
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."
} else {
"Per-app muting needs macOS 14.2 or newer. Apps are listed read-only."
})
}
}
/// Key + display name. Helper processes (e.g. "Google Chrome Helper (Renderer).app" inside
/// "Google Chrome.app") resolve to the *outermost* bundle so they group under their app.
fn identify(path: Option<&PathBuf>, bundle_id: &str) -> (String, String) {
if let Some(p) = path {
let s = p.to_string_lossy();
if let Some(end) = s.find(".app/") {
let bundle_path = &s[..end];
let name = bundle_path.rsplit('/').next().unwrap_or(bundle_path).to_owned();
return (format!("{}.app", name.to_lowercase()), name);
}
}
if !bundle_id.is_empty() {
let name = bundle_id.rsplit('.').next().unwrap_or(bundle_id).to_owned();
return (bundle_id.to_lowercase(), name);
}
let exe =
path.and_then(|p| p.file_name()).map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| "unknown".into());
(exe.to_lowercase(), exe)
}
fn pid_path(pid: i32) -> Option<PathBuf> {
let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
let n = unsafe { libc::proc_pidpath(pid, buf.as_mut_ptr() as *mut c_void, buf.len() as u32) };
if n <= 0 {
return None;
}
buf.truncate(n as usize);
Some(PathBuf::from(String::from_utf8_lossy(&buf).into_owned()))
}
fn addr(selector: u32) -> AudioObjectPropertyAddress {
AudioObjectPropertyAddress { selector, scope: K_SCOPE_GLOBAL, element: K_ELEMENT_MAIN }
}
unsafe fn get_array<T: Copy + Default>(object: AudioObjectID, selector: u32) -> AudioResult<Vec<T>> {
let a = addr(selector);
let mut size = 0u32;
let status = AudioObjectGetPropertyDataSize(object, &a, 0, std::ptr::null(), &mut size);
if status != 0 {
return Err(AudioError::Backend(format!("AudioObjectGetPropertyDataSize = {status}")));
}
let mut out = vec![T::default(); size as usize / std::mem::size_of::<T>()];
let status =
AudioObjectGetPropertyData(object, &a, 0, std::ptr::null(), &mut size, out.as_mut_ptr() as *mut c_void);
if status != 0 {
return Err(AudioError::Backend(format!("AudioObjectGetPropertyData = {status}")));
}
out.truncate(size as usize / std::mem::size_of::<T>());
Ok(out)
}
unsafe fn get_scalar<T: Copy + Default>(object: AudioObjectID, selector: u32) -> Option<T> {
let a = addr(selector);
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)
}
/// Reads a `CFStringRef` property (returned +1 retained; toll-free bridged to `NSString`).
unsafe fn get_cfstring(object: AudioObjectID, selector: u32) -> Option<String> {
let raw: *mut NSString = get_scalar::<*mut c_void>(object, selector)? as *mut NSString;
let s: Retained<NSString> = Retained::from_raw(raw)?;
Some(s.to_string())
}
+175
View File
@@ -0,0 +1,175 @@
//! Platform-neutral audio control.
//!
//! Every OS backend implements [`AudioController`]; nothing outside `src/audio/`
//! knows which one is active. Backends are created *on the audio worker thread*
//! (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 |
//!
//! 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
//! 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.
mod mute;
pub mod worker;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(any(test, not(any(target_os = "windows", target_os = "macos", target_os = "linux"))))]
mod null;
#[cfg(target_os = "windows")]
mod windows;
pub use mute::MuteManager;
use std::fmt;
use std::path::PathBuf;
/// Stable identifier for an application across restarts — *not* a PID.
///
/// - Windows: lower-cased executable file name (`spotify.exe`), or `system-sounds`.
/// - Linux: `application.process.binary` (`firefox`), falling back to `application.name`.
/// - macOS: bundle identifier (`com.spotify.client`), falling back to executable name.
///
/// All audio sessions/streams sharing a key are controlled together (e.g. every
/// Chrome tab), which is what users expect from "mute Chrome".
pub type AppKey = String;
#[derive(Debug, Clone, PartialEq)]
pub struct AudioApp {
pub key: AppKey,
/// Friendly name (`Spotify`, `Google Chrome`).
pub name: String,
pub pids: Vec<u32>,
/// 0.0..=1.0, averaged across sessions. `None` if the backend can't read it.
pub volume: Option<f32>,
/// `true` only if *every* session of this app is muted.
pub muted: bool,
/// Executable path for icon lookup, when known.
pub exe_path: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capabilities {
pub per_app_volume: bool,
pub per_app_mute: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
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))]
PermissionDenied(String),
Backend(String),
}
impl fmt::Display for AudioError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AudioError::NotRunning(k) => write!(f, "{k} isn't running"),
AudioError::Unsupported(what) => write!(f, "not supported on this platform: {what}"),
AudioError::PermissionDenied(m) => write!(f, "permission needed: {m}"),
AudioError::Backend(m) => write!(f, "{m}"),
}
}
}
impl std::error::Error for AudioError {}
pub type AudioResult<T> = Result<T, AudioError>;
/// RGBA8 icon pixels (premultiplied: no), row-major.
#[derive(Debug, Clone)]
pub struct IconData {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
}
/// What was muted by a `mute_all` call, so `restore_all` only undoes HushKey's own work
/// and leaves apps the user had muted beforehand alone.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MuteSnapshot {
pub muted_keys: Vec<AppKey>,
}
pub trait AudioController {
fn backend_name(&self) -> &'static str;
fn capabilities(&self) -> Capabilities;
/// Every app with an audio session/stream registered with the OS mixer — including
/// 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)]
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
/// user's volume level is preserved by the OS itself — nothing is lost if HushKey
/// crashes while an app is muted.
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()>;
/// Mute every app that isn't already muted.
fn mute_all(&mut self) -> AudioResult<MuteSnapshot> {
let mut snap = MuteSnapshot::default();
for app in self.list_audio_apps()? {
if !app.muted {
match self.set_app_mute(&app.key, true) {
Ok(()) => snap.muted_keys.push(app.key),
Err(e) => log::warn!("mute_all: {}: {e}", app.key),
}
}
}
Ok(snap)
}
/// Undo a [`mute_all`](Self::mute_all). Apps that have since exited are skipped.
fn restore_all(&mut self, snapshot: &MuteSnapshot) -> AudioResult<()> {
for key in &snapshot.muted_keys {
match self.set_app_mute(key, false) {
Ok(()) | Err(AudioError::NotRunning(_)) => {}
Err(e) => log::warn!("restore_all: {key}: {e}"),
}
}
Ok(())
}
/// Best-effort app icon. Default: none (UI shows a letter avatar).
fn app_icon(&mut self, _app: &AudioApp) -> Option<IconData> {
None
}
/// Short note for the UI about platform limitations, if any.
fn platform_note(&self) -> Option<&'static str> {
None
}
}
/// Create the backend for the current OS. Must be called on the thread that will use it.
pub fn create_controller() -> AudioResult<Box<dyn AudioController>> {
#[cfg(target_os = "windows")]
return Ok(Box::new(windows::WasapiController::new()?));
#[cfg(target_os = "macos")]
return Ok(Box::new(macos::CoreAudioTapController::new()?));
#[cfg(target_os = "linux")]
return Ok(Box::new(linux::PulseController::new()?));
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
return Ok(Box::new(null::NullController::default()));
}
+147
View File
@@ -0,0 +1,147 @@
//! Toggle / mute-all state machine, independent of any OS backend.
use super::{AudioController, AudioError, AudioResult, MuteSnapshot};
/// Result of a toggle, for feedback (toast / tray flash).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToggleOutcome {
pub key: String,
pub name: String,
pub muted: bool,
}
#[derive(Default)]
pub struct MuteManager {
/// Present while "Mute All" is engaged.
all: Option<MuteSnapshot>,
}
impl MuteManager {
pub fn all_muted(&self) -> bool {
self.all.is_some()
}
/// Toggle one app: if any of its sessions is audible, mute them all; otherwise unmute.
pub fn toggle_app(&mut self, ctl: &mut dyn AudioController, key: &str) -> AudioResult<ToggleOutcome> {
let app = ctl
.list_audio_apps()?
.into_iter()
.find(|a| a.key == key)
.ok_or_else(|| AudioError::NotRunning(key.into()))?;
let mute = !app.muted;
ctl.set_app_mute(key, mute)?;
// If the user manually unmutes an app during Mute All, Restore All must not touch it
// again; if they manually mute it, it was their choice, so restore leaves it muted.
if let Some(snap) = &mut self.all {
snap.muted_keys.retain(|k| k != key);
}
Ok(ToggleOutcome { key: app.key, name: app.name, muted: mute })
}
pub fn mute_all(&mut self, ctl: &mut dyn AudioController) -> AudioResult<()> {
let snap = ctl.mute_all()?;
match &mut self.all {
// Already engaged (e.g. re-applied after new apps appeared): extend the snapshot.
Some(existing) => {
for k in snap.muted_keys {
if !existing.muted_keys.contains(&k) {
existing.muted_keys.push(k);
}
}
}
None => self.all = Some(snap),
}
Ok(())
}
pub fn restore_all(&mut self, ctl: &mut dyn AudioController) -> AudioResult<()> {
if let Some(snap) = self.all.take() {
ctl.restore_all(&snap)?;
}
Ok(())
}
/// Returns the new "all muted" state.
pub fn toggle_all(&mut self, ctl: &mut dyn AudioController) -> AudioResult<bool> {
if self.all_muted() {
self.restore_all(ctl)?;
} else {
self.mute_all(ctl)?;
}
Ok(self.all_muted())
}
/// While Mute All is engaged, silence apps that started playing afterwards.
pub fn enforce(&mut self, ctl: &mut dyn AudioController) -> AudioResult<()> {
if self.all_muted() {
self.mute_all(ctl)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::audio::null::NullController;
#[test]
fn toggle_flips_state() {
let mut ctl = NullController::with_apps(&[("a", false)]);
let mut m = MuteManager::default();
assert!(m.toggle_app(&mut ctl, "a").unwrap().muted);
assert_eq!(ctl.is_muted("a"), Some(true));
assert!(!m.toggle_app(&mut ctl, "a").unwrap().muted);
assert_eq!(ctl.is_muted("a"), Some(false));
}
#[test]
fn toggle_missing_app_is_not_running() {
let mut ctl = NullController::with_apps(&[]);
let err = MuteManager::default().toggle_app(&mut ctl, "ghost").unwrap_err();
assert_eq!(err, AudioError::NotRunning("ghost".into()));
}
#[test]
fn restore_all_leaves_previously_muted_apps_muted() {
let mut ctl = NullController::with_apps(&[("a", false), ("b", true)]);
let mut m = MuteManager::default();
assert!(m.toggle_all(&mut ctl).unwrap());
assert_eq!(ctl.is_muted("a"), Some(true));
assert!(!m.toggle_all(&mut ctl).unwrap());
assert_eq!(ctl.is_muted("a"), Some(false));
assert_eq!(ctl.is_muted("b"), Some(true), "user had muted b before; keep it muted");
}
#[test]
fn manual_toggle_during_mute_all_is_respected() {
let mut ctl = NullController::with_apps(&[("a", false), ("b", false)]);
let mut m = MuteManager::default();
m.mute_all(&mut ctl).unwrap();
m.toggle_app(&mut ctl, "a").unwrap(); // user unmutes a
m.toggle_app(&mut ctl, "a").unwrap(); // ...and mutes it again manually
m.restore_all(&mut ctl).unwrap();
assert_eq!(ctl.is_muted("a"), Some(true));
assert_eq!(ctl.is_muted("b"), Some(false));
}
#[test]
fn enforce_mutes_late_starters_and_restores_them() {
let mut ctl = NullController::with_apps(&[("a", false)]);
let mut m = MuteManager::default();
m.mute_all(&mut ctl).unwrap();
ctl.apps.extend(NullController::with_apps(&[("late", false)]).apps);
m.enforce(&mut ctl).unwrap();
assert_eq!(ctl.is_muted("late"), Some(true));
m.restore_all(&mut ctl).unwrap();
assert_eq!(ctl.is_muted("late"), Some(false));
assert_eq!(ctl.is_muted("a"), Some(false));
}
#[test]
fn enforce_is_noop_when_not_engaged() {
let mut ctl = NullController::with_apps(&[("a", false)]);
MuteManager::default().enforce(&mut ctl).unwrap();
assert_eq!(ctl.mute_calls, 0);
}
}
+65
View File
@@ -0,0 +1,65 @@
//! In-memory backend: used by unit tests and as the fallback on unsupported OSes.
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities};
#[derive(Default)]
pub struct NullController {
pub apps: Vec<AudioApp>,
/// Count of set_app_mute calls, for tests.
pub mute_calls: usize,
}
impl NullController {
#[cfg(test)]
pub fn with_apps(keys: &[(&str, bool)]) -> Self {
Self {
apps: keys
.iter()
.map(|(k, muted)| AudioApp {
key: (*k).into(),
name: (*k).into(),
pids: vec![1],
volume: Some(1.0),
muted: *muted,
exe_path: None,
})
.collect(),
mute_calls: 0,
}
}
pub fn is_muted(&self, key: &str) -> Option<bool> {
self.apps.iter().find(|a| a.key == key).map(|a| a.muted)
}
}
impl AudioController for NullController {
fn backend_name(&self) -> &'static str {
"none"
}
fn capabilities(&self) -> Capabilities {
Capabilities { per_app_volume: true, per_app_mute: true }
}
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
Ok(self.apps.clone())
}
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()> {
let a = self.apps.iter_mut().find(|a| a.key == app).ok_or_else(|| AudioError::NotRunning(app.into()))?;
a.volume = Some(volume.clamp(0.0, 1.0));
Ok(())
}
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()> {
self.mute_calls += 1;
let a = self.apps.iter_mut().find(|a| a.key == app).ok_or_else(|| AudioError::NotRunning(app.into()))?;
a.muted = muted;
Ok(())
}
fn platform_note(&self) -> Option<&'static str> {
Some("Per-app audio control isn't available on this platform.")
}
}
+339
View File
@@ -0,0 +1,339 @@
//! Windows backend: WASAPI audio sessions.
//!
//! Each app that opens an audio stream gets an *audio session* per output device
//! (the same thing the Windows Volume Mixer shows). We enumerate sessions on **every
//! 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`).
//! Threading: this type must stay on the thread that created it (COM MTA init).
use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, IconData};
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::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::{
eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, 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::Threading::{
OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
};
use windows::Win32::UI::Shell::SHDefExtractIconW;
use windows::Win32::UI::WindowsAndMessaging::{DestroyIcon, GetIconInfo, HICON, ICONINFO};
const SYSTEM_SOUNDS_KEY: &str = "system-sounds";
const ICON_SIZE: u32 = 64;
fn err(context: &str, e: windows::core::Error) -> AudioError {
AudioError::Backend(format!("{context}: {e}"))
}
#[derive(Clone)]
struct ProcInfo {
key: String,
name: String,
path: Option<PathBuf>,
}
struct Session {
key: String,
pid: u32,
volume: ISimpleAudioVolume,
}
/// Balances `CoInitializeEx`. Declared as the *last* field so COM objects are released first.
struct ComGuard;
impl Drop for ComGuard {
fn drop(&mut self) {
unsafe { CoUninitialize() };
}
}
pub struct WasapiController {
enumerator: IMMDeviceEnumerator,
procs: HashMap<u32, ProcInfo>,
_com: ComGuard,
}
impl WasapiController {
pub fn new() -> AudioResult<Self> {
unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok().map_err(|e| err("CoInitializeEx", e))?;
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 })
}
}
fn proc_info(&mut self, pid: u32) -> ProcInfo {
if let Some(p) = self.procs.get(&pid) {
return p.clone();
}
if self.procs.len() > 512 {
self.procs.clear(); // PIDs get reused; keep the cache from growing forever.
}
let info = match process_path(pid) {
Some(path) => {
let file = path.file_name().map(|f| f.to_string_lossy().to_lowercase()).unwrap_or_default();
let name = file_description(&path).unwrap_or_else(|| pretty_stem(&path));
ProcInfo { key: file, name, path: Some(path) }
}
// Protected/elevated processes we can't open: still controllable by PID.
None => ProcInfo { key: format!("pid-{pid}"), name: format!("Process {pid}"), path: None },
};
self.procs.insert(pid, info.clone());
info
}
/// Every live audio session on every active output device.
fn sessions(&mut self) -> AudioResult<Vec<Session>> {
let mut out = Vec::new();
unsafe {
let devices = self
.enumerator
.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE)
.map_err(|e| err("EnumAudioEndpoints", e))?;
let count = devices.GetCount().map_err(|e| err("GetCount", e))?;
for i in 0..count {
let Ok(device) = devices.Item(i) else { continue };
let Ok(manager) = device.Activate::<IAudioSessionManager2>(CLSCTX_ALL, None) else { continue };
let Ok(list) = manager.GetSessionEnumerator() else { continue };
let n = list.GetCount().unwrap_or(0);
for j in 0..n {
let Ok(control) = list.GetSession(j) else { continue };
if control.GetState().map(|s| s == AudioSessionStateExpired).unwrap_or(true) {
continue;
}
let Ok(control2) = control.cast::<IAudioSessionControl2>() else { continue };
let Ok(volume) = control.cast::<ISimpleAudioVolume>() else { continue };
let pid = control2.GetProcessId().unwrap_or(0);
let key = if control2.IsSystemSoundsSession() == S_OK || pid == 0 {
SYSTEM_SOUNDS_KEY.to_owned()
} else {
self.proc_info(pid).key
};
out.push(Session { key, pid, volume });
}
}
}
Ok(out)
}
fn for_each_session_of(
&mut self,
app: &str,
f: impl Fn(&ISimpleAudioVolume) -> windows::core::Result<()>,
) -> AudioResult<()> {
let sessions = self.sessions()?;
let mut found = false;
let mut last_err = None;
for s in sessions.iter().filter(|s| s.key == app) {
found = true;
if let Err(e) = f(&s.volume) {
last_err = Some(e);
}
}
if !found {
return Err(AudioError::NotRunning(app.to_owned()));
}
match last_err {
Some(e) => Err(err(app, e)),
None => Ok(()),
}
}
}
impl AudioController for WasapiController {
fn backend_name(&self) -> &'static str {
"Windows Core Audio (WASAPI)"
}
fn capabilities(&self) -> Capabilities {
Capabilities { per_app_volume: true, per_app_mute: true }
}
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
let sessions = self.sessions()?;
// key -> (pids, volumes, all_muted)
let mut grouped: BTreeMap<String, (Vec<u32>, Vec<f32>, bool)> = BTreeMap::new();
for s in &sessions {
let (vol, muted) = unsafe {
(s.volume.GetMasterVolume().unwrap_or(1.0), s.volume.GetMute().map(|b| b.as_bool()).unwrap_or(false))
};
let e = grouped.entry(s.key.clone()).or_insert_with(|| (Vec::new(), Vec::new(), true));
if !e.0.contains(&s.pid) {
e.0.push(s.pid);
}
e.1.push(vol);
e.2 &= muted;
}
let mut apps: Vec<AudioApp> = grouped
.into_iter()
.map(|(key, (pids, vols, muted))| {
let (name, exe_path) = if key == SYSTEM_SOUNDS_KEY {
("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 }
})
.collect();
apps.sort_by_key(|a| a.name.to_lowercase());
Ok(apps)
}
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()> {
let v = volume.clamp(0.0, 1.0);
self.for_each_session_of(app, |s| unsafe { s.SetMasterVolume(v, std::ptr::null()) })
}
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()> {
self.for_each_session_of(app, |s| unsafe { s.SetMute(muted, std::ptr::null()) })
}
fn app_icon(&mut self, app: &AudioApp) -> Option<IconData> {
exe_icon(app.exe_path.as_deref()?)
}
}
fn wide(path: &Path) -> Vec<u16> {
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
}
fn process_path(pid: u32) -> Option<PathBuf> {
unsafe {
let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;
let mut buf = [0u16; 1024];
let mut len = buf.len() as u32;
let ok = QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, PWSTR(buf.as_mut_ptr()), &mut len);
let _ = CloseHandle(handle);
ok.ok()?;
Some(PathBuf::from(String::from_utf16_lossy(&buf[..len as usize])))
}
}
fn pretty_stem(path: &Path) -> String {
let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let mut c = stem.chars();
match c.next() {
Some(f) => f.to_uppercase().chain(c).collect(),
None => stem,
}
}
/// `FileDescription` from the exe's version resource ("Spotify", "Google Chrome").
fn file_description(path: &Path) -> Option<String> {
let w = wide(path);
unsafe {
let size = GetFileVersionInfoSizeW(PCWSTR(w.as_ptr()), None);
if size == 0 {
return None;
}
let mut data = vec![0u8; size as usize];
GetFileVersionInfoW(PCWSTR(w.as_ptr()), None, size, data.as_mut_ptr() as *mut c_void).ok()?;
let mut ptr: *mut c_void = std::ptr::null_mut();
let mut len = 0u32;
if !VerQueryValueW(
data.as_ptr() as *const c_void,
&HSTRING::from("\\VarFileInfo\\Translation"),
&mut ptr,
&mut len,
)
.as_bool()
|| len < 4
{
return None;
}
let lang = *(ptr as *const u16);
let codepage = *(ptr as *const u16).add(1);
let sub = HSTRING::from(format!("\\StringFileInfo\\{lang:04x}{codepage:04x}\\FileDescription"));
if !VerQueryValueW(data.as_ptr() as *const c_void, &sub, &mut ptr, &mut len).as_bool() || len == 0 {
return None;
}
let chars = std::slice::from_raw_parts(ptr as *const u16, len as usize);
let s = String::from_utf16_lossy(chars).trim_end_matches('\0').trim().to_owned();
(!s.is_empty()).then_some(s)
}
}
fn exe_icon(path: &Path) -> Option<IconData> {
let w = wide(path);
unsafe {
let mut icon = HICON::default();
SHDefExtractIconW(PCWSTR(w.as_ptr()), 0, 0, Some(&mut icon), None, ICON_SIZE).ok().ok()?;
if icon.is_invalid() {
return None;
}
let data = hicon_to_rgba(icon);
let _ = DestroyIcon(icon);
data
}
}
unsafe fn hicon_to_rgba(icon: HICON) -> Option<IconData> {
let mut info = ICONINFO::default();
GetIconInfo(icon, &mut info).ok()?;
let cleanup = |info: &ICONINFO| {
if !info.hbmColor.is_invalid() {
let _ = DeleteObject(info.hbmColor.into());
}
if !info.hbmMask.is_invalid() {
let _ = DeleteObject(info.hbmMask.into());
}
};
if info.hbmColor.is_invalid() {
cleanup(&info);
return None; // monochrome icon; letter avatar looks better anyway
}
let mut bmp = BITMAP::default();
if GetObjectW(info.hbmColor.into(), std::mem::size_of::<BITMAP>() as i32, Some(&mut bmp as *mut _ as *mut c_void))
== 0
{
cleanup(&info);
return None;
}
let (w, h) = (bmp.bmWidth, bmp.bmHeight);
let mut bi = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: w,
biHeight: -h, // top-down
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB.0,
..Default::default()
},
..Default::default()
};
let mut buf = vec![0u8; (w * h * 4) as usize];
let dc = GetDC(None);
let lines =
GetDIBits(dc, info.hbmColor, 0, h as u32, Some(buf.as_mut_ptr() as *mut c_void), &mut bi, DIB_RGB_COLORS);
ReleaseDC(None, dc);
cleanup(&info);
if lines == 0 {
return None;
}
let has_alpha = buf.chunks_exact(4).any(|p| p[3] != 0);
for px in buf.chunks_exact_mut(4) {
px.swap(0, 2); // BGRA -> RGBA
if !has_alpha {
px[3] = 255;
}
}
Some(IconData { width: w as u32, height: h as u32, rgba: buf })
}
+190
View File
@@ -0,0 +1,190 @@
//! Dedicated audio thread.
//!
//! The backend lives entirely on this thread; everyone else talks to it through
//! [`AudioHandle`] (commands in) and an event sink (events out). Hotkey presses go
//! straight here from the OS hotkey callback, so muting never waits on the UI.
//!
//! 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.
use super::mute::ToggleOutcome;
use super::{create_controller, AudioApp, AudioError, Capabilities, IconData, MuteManager};
use std::collections::HashSet;
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
use std::thread::JoinHandle;
use std::time::Duration;
const ENFORCE_INTERVAL: Duration = Duration::from_secs(2);
#[derive(Debug, Clone)]
pub enum AudioCommand {
Refresh,
/// `from_hotkey` controls whether the user gets toast/tray feedback.
ToggleApp {
key: String,
from_hotkey: bool,
},
ToggleAll {
from_hotkey: bool,
},
RestoreAll {
from_hotkey: bool,
},
Shutdown,
}
#[derive(Debug, Clone)]
pub enum AudioEvent {
Ready {
backend: &'static str,
caps: Capabilities,
note: Option<&'static str>,
},
Apps(Vec<AudioApp>),
Icon {
key: String,
icon: IconData,
},
Toggled {
outcome: ToggleOutcome,
from_hotkey: bool,
},
AllMuted {
muted: bool,
from_hotkey: bool,
},
/// A per-app shortcut fired but that app has no audio session right now.
NotRunning {
key: String,
from_hotkey: bool,
},
Error {
message: String,
from_hotkey: bool,
},
/// The backend couldn't start at all (e.g. no PulseAudio server).
Fatal(String),
}
pub struct AudioHandle {
tx: Sender<AudioCommand>,
thread: Option<JoinHandle<()>>,
}
impl AudioHandle {
pub fn sender(&self) -> Sender<AudioCommand> {
self.tx.clone()
}
pub fn send(&self, cmd: AudioCommand) {
let _ = self.tx.send(cmd);
}
/// Restores anything Mute All silenced, then joins the thread.
pub fn shutdown(mut self) {
let _ = self.tx.send(AudioCommand::Shutdown);
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
let (tx, rx) = mpsc::channel::<AudioCommand>();
let thread = std::thread::Builder::new()
.name("hushkey-audio".into())
.spawn(move || {
let mut ctl = match create_controller() {
Ok(c) => c,
Err(e) => {
log::error!("audio backend failed to start: {e}");
sink(AudioEvent::Fatal(e.to_string()));
// Keep draining so senders never block/err; nothing to control.
while let Ok(cmd) = rx.recv() {
if matches!(cmd, AudioCommand::Shutdown) {
break;
}
}
return;
}
};
log::info!("audio backend: {}", ctl.backend_name());
sink(AudioEvent::Ready {
backend: ctl.backend_name(),
caps: ctl.capabilities(),
note: ctl.platform_note(),
});
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() {
Ok(apps) => {
for app in &apps {
if icons_sent.insert(app.key.clone()) {
if let Some(icon) = ctl.app_icon(app) {
sink(AudioEvent::Icon { key: app.key.clone(), icon });
}
}
}
sink(AudioEvent::Apps(apps));
}
Err(e) => sink(AudioEvent::Error { message: e.to_string(), from_hotkey: false }),
};
loop {
let cmd = if mute.all_muted() {
match rx.recv_timeout(ENFORCE_INTERVAL) {
Ok(cmd) => cmd,
Err(RecvTimeoutError::Timeout) => {
if let Err(e) = mute.enforce(ctl.as_mut()) {
log::debug!("enforce: {e}");
}
continue;
}
Err(RecvTimeoutError::Disconnected) => AudioCommand::Shutdown,
}
} else {
rx.recv().unwrap_or(AudioCommand::Shutdown)
};
match cmd {
AudioCommand::Refresh => {
let _ = mute.enforce(ctl.as_mut());
publish_apps(ctl.as_mut(), &mut icons_sent);
}
AudioCommand::ToggleApp { key, from_hotkey } => {
match mute.toggle_app(ctl.as_mut(), &key) {
Ok(outcome) => sink(AudioEvent::Toggled { outcome, from_hotkey }),
Err(AudioError::NotRunning(_)) => sink(AudioEvent::NotRunning { key, from_hotkey }),
Err(e) => sink(AudioEvent::Error { message: format!("{key}: {e}"), from_hotkey }),
}
publish_apps(ctl.as_mut(), &mut icons_sent);
}
AudioCommand::ToggleAll { from_hotkey } => {
match mute.toggle_all(ctl.as_mut()) {
Ok(muted) => sink(AudioEvent::AllMuted { muted, from_hotkey }),
Err(e) => sink(AudioEvent::Error { message: e.to_string(), from_hotkey }),
}
publish_apps(ctl.as_mut(), &mut icons_sent);
}
AudioCommand::RestoreAll { from_hotkey } => {
match mute.restore_all(ctl.as_mut()) {
Ok(()) => sink(AudioEvent::AllMuted { muted: false, from_hotkey }),
Err(e) => sink(AudioEvent::Error { message: e.to_string(), from_hotkey }),
}
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}");
}
break;
}
}
}
})
.expect("spawn audio thread");
AudioHandle { tx, thread: Some(thread) }
}