//! Which processes hold a microphone right now (drives call detection). //! //! Every active capture endpoint is asked for its audio sessions //! (`IAudioSessionManager2::GetSessionEnumerator`). A session belongs to one //! process (`IAudioSessionControl2::GetProcessId`) and is active while one //! of its streams runs, i.e. while the app actually records the mic. The //! process's exe comes from `QueryFullProcessImageNameW`; its `root_pid` is //! the top of its same-exe parent chain in a ToolHelp snapshot, which is the //! tree application loopback records. Teams helper processes are reported //! as their Teams ancestor (see [`crate::process_tree`]). use std::path::Path; use recorder_core::detect::MicSession; use wasapi::{deinitialize, initialize_mta, DeviceEnumerator, Direction, SessionState}; use windows::core::PWSTR; use windows::Win32::Foundation::{CloseHandle, FILETIME, HANDLE}; use windows::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS, }; use windows::Win32::System::Threading::{ GetProcessTimes, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, }; use crate::process_tree::{attribute, ProcessTable}; /// Sessions on every active capture endpoint, one entry per session. /// /// Initialises COM (MTA) on the calling thread for the duration of the /// call, so call it from a thread that is not an STA (the detection loop /// has its own thread). Sessions of the system (pid 0) and of processes /// that cannot be opened are skipped; enumeration errors yield fewer or no /// sessions, never an error, because detection simply polls again. pub fn mic_sessions() -> Vec { if let Err(err) = initialize_mta().ok() { log::debug!("mic sessions: COM initialisation failed: {err}"); return Vec::new(); } let sessions = enumerate(); // Every COM object is dropped by now. deinitialize(); sessions } /// (pid, active) of every non-system session on every active capture /// endpoint, then resolved to exe and root pid. fn enumerate() -> Vec { let raw = capture_sessions(); if raw.is_empty() { return Vec::new(); } let table = process_table(); raw.into_iter() .filter_map(|(pid, active)| { let exe = image_name(pid)?; let (exe, root_pid) = attribute(&table, pid, &exe, creation_time); Some(MicSession { exe, pid, root_pid, active, }) }) .collect() } fn capture_sessions() -> Vec<(u32, bool)> { let collection = match DeviceEnumerator::new() .and_then(|enumerator| enumerator.get_device_collection(&Direction::Capture)) { Ok(collection) => collection, Err(err) => { log::debug!("mic sessions: cannot enumerate capture endpoints: {err}"); return Vec::new(); } }; let mut sessions = Vec::new(); for device in &collection { let Ok(device) = device else { continue }; let Ok(enumerator) = device .get_iaudiosessionmanager() .and_then(|manager| manager.get_audiosessionenumerator()) else { continue; }; let count = enumerator.get_count().unwrap_or(0); for index in 0..count { let Ok(control) = enumerator.get_session(index) else { continue; }; let (Ok(pid), Ok(state)) = (control.get_process_id(), control.get_state()) else { continue; }; if pid != 0 { sessions.push((pid, state == SessionState::Active)); } } } sessions } /// The file name of `pid`'s executable, or `None` if the process cannot be /// opened (exited, or protected). fn image_name(pid: u32) -> Option { // SAFETY: plain Win32 calls; the handle is closed below and the buffer // outlives the call that fills it. unsafe { let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; let mut buf = [0u16; 1024]; let mut len = buf.len() as u32; let result = QueryFullProcessImageNameW( handle, PROCESS_NAME_WIN32, PWSTR(buf.as_mut_ptr()), &mut len, ); close(handle); result.ok()?; let path = String::from_utf16_lossy(&buf[..len as usize]); Path::new(&path) .file_name() .map(|name| name.to_string_lossy().into_owned()) } } /// When `pid` was created (FILETIME ticks), or `None` if the process cannot /// be opened. fn creation_time(pid: u32) -> Option { // SAFETY: plain Win32 calls; the handle is closed below and the // FILETIMEs outlive the call that fills them. unsafe { let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; let (mut created, mut exited, mut kernel, mut user) = ( FILETIME::default(), FILETIME::default(), FILETIME::default(), FILETIME::default(), ); let result = GetProcessTimes(handle, &mut created, &mut exited, &mut kernel, &mut user); close(handle); result.ok()?; Some((u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime)) } } /// pid -> (parent pid, exe) of every process, from one ToolHelp snapshot. /// Empty if the snapshot fails, which makes every session its own root. fn process_table() -> ProcessTable { let mut table = ProcessTable::new(); // SAFETY: plain Win32 calls; `entry.dwSize` is set as the API requires // and the snapshot handle is closed below. unsafe { let snapshot = match CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) { Ok(snapshot) => snapshot, Err(err) => { log::debug!("mic sessions: process snapshot failed: {err}"); return table; } }; let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::() as u32, ..Default::default() }; let mut next = Process32FirstW(snapshot, &mut entry); while next.is_ok() { let len = entry .szExeFile .iter() .position(|&c| c == 0) .unwrap_or(entry.szExeFile.len()); table.insert( entry.th32ProcessID, ( entry.th32ParentProcessID, String::from_utf16_lossy(&entry.szExeFile[..len]), ), ); next = Process32NextW(snapshot, &mut entry); } close(snapshot); } table } fn close(handle: HANDLE) { // SAFETY: `handle` was returned by a successful Win32 call and is closed // exactly once. if let Err(err) = unsafe { CloseHandle(handle) } { log::debug!("mic sessions: CloseHandle failed: {err}"); } }