Skip to content

Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.

Rust
8.1 KB
Raw Blame
//! Sound (Core Audio): volume and mute of the default playback device or microphone, the list of devices with choosing the
//! default one, and the volume of every app that plays sound. Every call asks for the default device again, so a device change
//! in Windows is followed. All calls come from the UI thread, which initializes COM in `init`.
#![allow(non_snake_case)] // the method names of the COM interface below
use std::{ffi::c_void, ptr::null};
use windows::{
    Win32::{
        Devices::FunctionDiscovery::PKEY_Device_FriendlyName,
        Media::Audio::{
            DEVICE_STATE_ACTIVE, EDataFlow, Endpoints::IAudioEndpointVolume, IAudioSessionControl2, IAudioSessionManager2, IMMDevice, IMMDeviceEnumerator, ISimpleAudioVolume,
            MMDeviceEnumerator, eCapture, eCommunications, eConsole, eMultimedia, eRender,
        },
        System::Com::{CLSCTX_ALL, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, STGM_READ},
    },
    core::{GUID, HRESULT, Interface, PCWSTR},
};

pub fn init() {
    unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
    }
}

/// What a volume slider controls.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Src {
    Out,
    Mic,
    /// One app's sessions on the default playback device (pid 0: system sounds).
    App(u32),
}

fn enumerator() -> Option<IMMDeviceEnumerator> {
    unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok() }
}

fn default_device(mic: bool) -> Option<IMMDevice> {
    unsafe { enumerator()?.GetDefaultAudioEndpoint(if mic { eCapture } else { eRender }, eConsole).ok() }
}

fn endpoint(mic: bool) -> Option<IAudioEndpointVolume> {
    unsafe { default_device(mic)?.Activate::<IAudioEndpointVolume>(CLSCTX_ALL, None).ok() }
}

// ---- devices ----

pub struct Dev {
    pub id: String,
    pub name: String,
    pub default: bool,
}

fn dev_id(d: &IMMDevice) -> Option<String> {
    unsafe { d.GetId().ok().and_then(|p| p.to_string().ok()) }
}

fn dev_name(d: &IMMDevice) -> String {
    unsafe {
        let name = d.OpenPropertyStore(STGM_READ).ok().and_then(|s| s.GetValue(&PKEY_Device_FriendlyName).ok()).map(|v| v.to_string()).filter(|s| !s.is_empty());
        name.unwrap_or_else(|| dev_id(d).unwrap_or_default())
    }
}

/// The active playback (or recording) devices; the one Windows uses by default is flagged.
pub fn devices(mic: bool) -> Vec<Dev> {
    let Some(e) = enumerator() else { return vec![] };
    let flow: EDataFlow = if mic { eCapture } else { eRender };
    let cur = unsafe { e.GetDefaultAudioEndpoint(flow, eConsole).ok() }.and_then(|d| dev_id(&d));
    let Ok(col) = (unsafe { e.EnumAudioEndpoints(flow, DEVICE_STATE_ACTIVE) }) else { return vec![] };
    (0..unsafe { col.GetCount() }.unwrap_or(0)).filter_map(|i| unsafe { col.Item(i).ok() }).filter_map(|d| dev_id(&d).map(|id| Dev { default: Some(&id) == cur.as_ref(), name: dev_name(&d), id })).collect()
}

/// The default device's name ("—" without one).
pub fn default_name(mic: bool) -> String {
    default_device(mic).map_or("—".into(), |d| dev_name(&d))
}

// The system's own switch of the default device. It has no documented API: this is the COM class Windows' sound panel and every
// third-party switcher use (PolicyConfigClient); only the one method SetDefaultEndpoint is called, the rest are placeholders
// that keep the vtable in place.
#[windows::core::interface("f8679f50-850a-41cf-9c72-430f290290c8")]
unsafe trait IPolicyConfig: windows::core::IUnknown {
    fn GetMixFormat(&self, dev: PCWSTR, fmt: *mut *mut c_void) -> HRESULT;
    fn GetDeviceFormat(&self, dev: PCWSTR, default: i32, fmt: *mut *mut c_void) -> HRESULT;
    fn ResetDeviceFormat(&self, dev: PCWSTR) -> HRESULT;
    fn SetDeviceFormat(&self, dev: PCWSTR, a: *mut c_void, b: *mut c_void) -> HRESULT;
    fn GetProcessingPeriod(&self, dev: PCWSTR, default: i32, a: *mut i64, b: *mut i64) -> HRESULT;
    fn SetProcessingPeriod(&self, dev: PCWSTR, a: *mut i64) -> HRESULT;
    fn GetShareMode(&self, dev: PCWSTR, m: *mut c_void) -> HRESULT;
    fn SetShareMode(&self, dev: PCWSTR, m: *mut c_void) -> HRESULT;
    fn GetPropertyValue(&self, dev: PCWSTR, fx: i32, key: *const c_void, v: *mut c_void) -> HRESULT;
    fn SetPropertyValue(&self, dev: PCWSTR, fx: i32, key: *const c_void, v: *mut c_void) -> HRESULT;
    fn SetDefaultEndpoint(&self, dev: PCWSTR, role: i32) -> HRESULT;
    fn SetEndpointVisibility(&self, dev: PCWSTR, visible: i32) -> HRESULT;
}

const POLICY_CONFIG_CLIENT: GUID = GUID::from_u128(0x870af99c_171d_4f9e_af0d_e63df40c2bc9);

/// Makes `id` (from `devices`) the default for every role (apps, media, calls).
pub fn set_default(id: &str) -> bool {
    unsafe {
        let Ok(pc) = CoCreateInstance::<_, IPolicyConfig>(&POLICY_CONFIG_CLIENT, None, CLSCTX_ALL) else { return false };
        let w: Vec<u16> = id.encode_utf16().chain([0]).collect();
        [eConsole, eMultimedia, eCommunications].iter().all(|r| pc.SetDefaultEndpoint(PCWSTR(w.as_ptr()), r.0).is_ok())
    }
}

// ---- apps ----

fn sessions() -> Vec<IAudioSessionControl2> {
    unsafe {
        let Some(m) = default_device(false).and_then(|d| d.Activate::<IAudioSessionManager2>(CLSCTX_ALL, None).ok()) else { return vec![] };
        let Ok(list) = m.GetSessionEnumerator() else { return vec![] };
        (0..list.GetCount().unwrap_or(0)).filter_map(|i| list.GetSession(i).ok()).filter_map(|s| s.cast::<IAudioSessionControl2>().ok()).collect()
    }
}

/// "chrome.exe" -> "chrome": the name of a process from its image path.
fn proc_name(pid: u32) -> Option<String> {
    use windows_sys::Win32::{Foundation::CloseHandle, System::Threading::*};
    unsafe {
        let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
        if h.is_null() {
            return None;
        }
        let mut buf = [0u16; 520];
        let mut n = buf.len() as u32;
        let ok = QueryFullProcessImageNameW(h, 0, buf.as_mut_ptr(), &mut n) != 0;
        CloseHandle(h);
        let path = String::from_utf16_lossy(&buf[..n as usize]);
        ok.then(|| path.rsplit('\\').next().unwrap_or(&path).trim_end_matches(".exe").to_string())
    }
}

/// The apps with an audio session on the default playback device: (pid, name), one entry per process, by name.
pub fn apps() -> Vec<(u32, String)> {
    let mut out: Vec<(u32, String)> = vec![];
    for s in sessions() {
        let pid = unsafe { s.GetProcessId() }.unwrap_or(0);
        let system = unsafe { s.IsSystemSoundsSession() }.0 == 0; // S_OK: it is the system sounds session
        let pid = if system { 0 } else { pid };
        if out.iter().any(|o| o.0 == pid) {
            continue;
        }
        let name = if pid == 0 { t!("Системные звуки", "System sounds").to_string() } else { proc_name(pid).unwrap_or_else(|| format!("PID {pid}")) };
        out.push((pid, name));
    }
    out.sort_by_key(|a| a.1.to_lowercase());
    out
}

fn app_volumes(pid: u32) -> Vec<ISimpleAudioVolume> {
    sessions()
        .into_iter()
        .filter(|s| {
            let sys = unsafe { s.IsSystemSoundsSession() }.0 == 0;
            if pid == 0 { sys } else { !sys && unsafe { s.GetProcessId() }.ok() == Some(pid) }
        })
        .filter_map(|s| s.cast::<ISimpleAudioVolume>().ok())
        .collect()
}

// ---- volume and mute ----

/// 0.0..=1.0; None when there is no such device (or app).
pub fn volume(src: Src) -> Option<f32> {
    unsafe {
        match src {
            Src::Out | Src::Mic => endpoint(src == Src::Mic)?.GetMasterVolumeLevelScalar().ok(),
            Src::App(pid) => app_volumes(pid).first()?.GetMasterVolume().ok(),
        }
    }
}

pub fn set_volume(src: Src, v: f32) {
    let v = v.clamp(0.0, 1.0);
    unsafe {
        match src {
            Src::Out | Src::Mic => {
                if let Some(e) = endpoint(src == Src::Mic) {
                    let _ = e.SetMasterVolumeLevelScalar(v, null());
                }
            }
            Src::App(pid) => app_volumes(pid).iter().for_each(|a| drop(a.SetMasterVolume(v, null()))),
        }
    }
}

pub fn muted(mic: bool) -> Option<bool> {
    unsafe { Some(endpoint(mic)?.GetMute().ok()?.as_bool()) }
}

pub fn set_mute(mic: bool, m: bool) {
    if let Some(e) = endpoint(mic) {
        let _ = unsafe { e.SetMute(m, null()) };
    }
}