hex/src/microphone_activity.rs
Dax 7364c058da
labs: choose meeting audio (one app or one output device) (#2724)
Labs › Choose meeting audio adds a Computer audio row to Meetings › Settings: all computer audio, one output device, or one app playing audio, read by each OS capture source as it opens and on its route check, so a change applies mid-recording. A chosen source records silence while it is missing and never falls back to all audio.

macOS: Core Audio process taps (per app or with a device UID), Windows: WASAPI process loopback (Windows 10 2004+) and single-endpoint loopback, Linux: PipeWire node and sink targets.

Review fixes: one long-lived thread owns pw-dump, restarts it after a short backing-off wait when it ends, forgets its graph until the next dump answers, and keeps origin/dev's answers for call detection; a chosen app taps every Core Audio process it has, a tap that should be playing but never delivers is rebuilt on a backing-off schedule, and a Windows root is retried on its own thread while the others keep recording, never adopting a restarted stream whose worker already failed; Windows names an app by the process its WebView2 helpers belong to, lists WebView2 helpers with no host as nothing, and reads process start times only for the app listing; Linux adds and removes an app's pw-record captures in place, keeps them when the graph cannot be read, starts a fresh stall window for a capture that appears after silence, and sizes its queue for streams that start later; every source notices a changed choice on its route check; a chosen source needs System Audio Recording consent on macOS; Hex's own playback never lists as an app; a sink pw-record cannot name is skipped once per name, not once per read.

Also makes the Linux playing-app listing independent of pw-dump order: a browser whose first stream reports no application.name kept whichever name the hash map yielded first, which flaked running_output_streams_name_their_apps_and_node_targets and could show "chrome" instead of "Google Chrome".
2026-11-24 17:41:26 -05:00

1673 lines
62 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Which applications hold the microphone, and which call apps and
//! browsers they are. Applications are keyed by macOS bundle identifiers;
//! the Linux and Windows adapters name processes by executable, which
//! [`canonical_bundle_id`](ActiveMicrophoneApplication::canonical_bundle_id)
//! maps to the same keys.
#[cfg(target_os = "macos")]
use std::ffi::c_void;
#[cfg(target_os = "macos")]
use std::mem::{offset_of, size_of};
#[cfg(target_os = "macos")]
use std::ptr::NonNull;
#[cfg(target_os = "macos")]
use color_eyre::eyre::Result;
#[cfg(target_os = "macos")]
use color_eyre::eyre::eyre;
#[cfg(target_os = "macos")]
use objc2_app_kit::NSRunningApplication;
#[cfg(target_os = "macos")]
use objc2_core_audio::{
AudioObjectGetPropertyData, AudioObjectGetPropertyDataSize, AudioObjectID,
AudioObjectPropertyAddress, AudioObjectPropertyScope, AudioObjectPropertySelector,
kAudioDevicePropertyDeviceUID, kAudioDevicePropertyStreamConfiguration,
kAudioHardwarePropertyProcessObjectList, kAudioObjectPropertyElementMain,
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput, kAudioObjectSystemObject,
kAudioProcessPropertyBundleID, kAudioProcessPropertyDevices,
kAudioProcessPropertyIsRunningInput, kAudioProcessPropertyIsRunningOutput,
kAudioProcessPropertyPID,
};
#[cfg(target_os = "macos")]
use objc2_core_audio_types::{AudioBuffer, AudioBufferList};
#[cfg(target_os = "macos")]
use objc2_core_foundation::{CFRetained, CFString};
#[cfg(target_os = "macos")]
use objc2_foundation::NSString;
#[cfg(target_os = "linux")]
#[path = "microphone_activity/linux.rs"]
mod os;
#[cfg(target_os = "windows")]
#[path = "microphone_activity/windows.rs"]
mod os;
#[cfg(not(target_os = "macos"))]
pub use os::active_microphone_applications;
/// Whether any process of `canonical_bundle_id` has audio output running:
/// a call keeps it open, muted or not, until it hangs up (#835). macOS reads
/// Core Audio below; Linux and Windows answer from their own adapters.
#[cfg(not(target_os = "macos"))]
pub(crate) use os::application_running_output;
#[cfg(target_os = "windows")]
pub(crate) use os::{
EndpointSessions, RunningProcess, active_endpoint_sessions, application_pid,
capturable_application, process_application, process_canonical_bundle_id, running_processes,
};
#[cfg(target_os = "linux")]
pub(crate) use os::{PlayingApplication, playing_applications};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ActiveMicrophoneApplication {
pub pid: i32,
pub bundle_id: String,
pub name: String,
}
impl ActiveMicrophoneApplication {
/// Whether this is a call app detection may offer.
pub fn is_supported_meeting_app(&self) -> bool {
self.canonical_bundle_id().is_some()
}
pub fn is_browser(&self) -> bool {
is_browser_id(self.canonical_bundle_id())
}
pub fn detection_priority(&self) -> u8 {
u8::from(self.is_browser())
}
pub fn canonical_bundle_id(&self) -> Option<&'static str> {
canonical_bundle_id_for(&self.bundle_id, Some(&self.name))
}
fn dedup_key(&self) -> &str {
self.canonical_bundle_id().unwrap_or(&self.bundle_id)
}
}
/// One entry per application: a call app's helpers and windows hold the
/// microphone as one.
fn deduplicated(
mut applications: Vec<ActiveMicrophoneApplication>,
) -> Vec<ActiveMicrophoneApplication> {
applications.sort_by(|left, right| left.dedup_key().cmp(right.dedup_key()));
applications.dedup_by(|left, right| left.dedup_key() == right.dedup_key());
applications
}
/// Whether a canonical bundle ID is a browser Hex reads pages from.
pub(crate) fn is_browser_id(canonical_bundle_id: Option<&str>) -> bool {
matches!(
canonical_bundle_id,
Some(
"com.google.Chrome"
| "com.brave.Browser"
| "com.apple.Safari"
| "org.mozilla.firefox"
| "com.microsoft.edgemac"
| "company.thebrowser.Browser"
| "com.vivaldi.Vivaldi"
| "net.imput.helium"
| "com.ardia.browser"
| "app.zen-browser.zen"
| "at.studio.AsideBrowser"
)
)
}
/// One of the browsers Hex knows, or one of their audio helpers.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn browser_bundle(bundle_id: &str, name: Option<&str>) -> bool {
is_browser_id(canonical_bundle_id_for(bundle_id, name))
}
#[cfg(target_os = "macos")]
/// Which browser processes to hear.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum BrowserProcesses {
/// Only those with open output; unknown counts as open.
Playing,
All,
}
#[cfg(target_os = "macos")]
impl BrowserProcesses {
fn includes(self, running_output: Option<bool>) -> bool {
match self {
Self::Playing => running_output.unwrap_or(true),
Self::All => true,
}
}
}
#[cfg(target_os = "macos")]
/// The Core Audio process objects of the running browsers, Hex excluded.
pub(crate) fn browser_process_objects(which: BrowserProcesses) -> Result<Vec<AudioObjectID>> {
objc2::rc::autoreleasepool(|_| {
let own_pid = std::process::id() as i32;
let process_objects = property_vec::<AudioObjectID>(
kAudioObjectSystemObject as AudioObjectID,
kAudioHardwarePropertyProcessObjectList,
)?;
Ok(process_objects
.into_iter()
.filter(|&process_object| {
let Ok(pid) = property_value::<i32>(process_object, kAudioProcessPropertyPID)
else {
return false;
};
let Some(bundle_id) =
property_cf_string(process_object, kAudioProcessPropertyBundleID)
else {
return false;
};
// Safari plays through a WebKit process told apart only by its name.
let name = bundle_id
.eq_ignore_ascii_case("com.apple.WebKit.GPU")
.then(|| running_application_info(pid))
.flatten()
.and_then(|(_, name)| name);
pid != own_pid
&& browser_bundle(&bundle_id, name.as_deref())
&& which.includes(
property_value::<u32>(process_object, kAudioProcessPropertyIsRunningOutput)
.ok()
.map(|running| running != 0),
)
})
.collect())
})
}
#[cfg(target_os = "macos")]
/// Whether any Core Audio process of the app `canonical_bundle_id` (its
/// helpers included) is playing output: a call keeps it open, muted or not,
/// and a hung-up WhatsApp call closes it with the microphone (#835).
pub(crate) fn application_running_output(canonical_bundle_id: &str) -> Result<bool> {
objc2::rc::autoreleasepool(|_| {
let process_objects = property_vec::<AudioObjectID>(
kAudioObjectSystemObject as AudioObjectID,
kAudioHardwarePropertyProcessObjectList,
)?;
Ok(process_objects.into_iter().any(|process_object| {
property_value::<u32>(process_object, kAudioProcessPropertyIsRunningOutput)
.is_ok_and(|running| running != 0)
&& property_cf_string(process_object, kAudioProcessPropertyBundleID)
.is_some_and(|bundle_id| is_process_of(&bundle_id, canonical_bundle_id))
}))
})
}
/// One Core Audio process object, as Labs › Choose meeting audio reads it:
/// a meeting's tap names its `object`, and `id` is the app the Meetings
/// pane lists for it.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) struct OutputProcess {
/// The Core Audio process object a tap includes or excludes.
pub(crate) object: u32,
/// The process the object describes.
pub(crate) pid: i32,
/// The bundle id the process reports (its LaunchServices one when Core
/// Audio reports none), which names it for display.
pub(crate) bundle_id: String,
/// The canonical bundle id the Meetings pane lists, else `bundle_id`.
pub(crate) id: String,
/// Whether the process plays output now.
pub(crate) running_output: bool,
}
/// Whether a bundle id is Hex itself, including the identifiers a retired
/// Hex build still reports: a meeting's tap never includes Hex's own audio,
/// and its pane never lists Hex.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn is_hex_bundle(bundle_id: &str) -> bool {
let bundle_id = bundle_id.to_ascii_lowercase();
bundle_id == "anomaly.hex"
|| bundle_id == "anomaly.hex.test"
|| crate::desktop::onboarding::LEGACY_MAC_BUNDLE_IDS
.iter()
.any(|legacy| legacy.eq_ignore_ascii_case(&bundle_id))
}
/// The process objects a meeting taps for the app `id`: every process of
/// that app, its helpers included and whether it plays output now or not,
/// once each and sorted so two readings compare. A process idle now is tapped
/// anyway, so a helper that starts playing later is heard without rebuilding
/// the tap; only the set of processes changes it. An app with no processes at
/// all records silence until it starts, never every output; Hex's own
/// processes are never among them.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn app_process_objects(id: &str, processes: &[OutputProcess]) -> Vec<u32> {
let mut objects: Vec<u32> = processes
.iter()
.filter(|process| {
process.id == id && !is_hex_bundle(&process.id) && !is_hex_bundle(&process.bundle_id)
})
.map(|process| process.object)
.collect();
objects.sort_unstable();
objects.dedup();
objects
}
#[cfg(target_os = "macos")]
/// Whether any Core Audio process object of the app `id` reports output
/// running now: a chosen tap on an app that should be playing but delivers
/// no IO cycle is stalled. `None` when the process list cannot be read.
pub(crate) fn app_output_running(id: &str) -> Option<bool> {
output_process_objects().ok().map(|processes| {
processes
.iter()
.any(|process| process.id == id && process.running_output)
})
}
#[cfg(target_os = "macos")]
/// Every Core Audio process object, Hex's own processes excluded, with the
/// app each belongs to: a helper process is its app's, so a browser's audio
/// service belongs to the browser. Only Core Audio's process metadata is
/// read, never audio.
pub(crate) fn output_process_objects() -> Result<Vec<OutputProcess>> {
objc2::rc::autoreleasepool(|_| {
let own_pid = std::process::id() as i32;
let process_objects = property_vec::<AudioObjectID>(
kAudioObjectSystemObject as AudioObjectID,
kAudioHardwarePropertyProcessObjectList,
)?;
let mut processes = Vec::new();
for process_object in process_objects {
let Ok(pid) = property_value::<i32>(process_object, kAudioProcessPropertyPID) else {
continue;
};
let bundle_id = match property_cf_string(process_object, kAudioProcessPropertyBundleID)
{
Some(bundle_id) => bundle_id,
None => match running_application_info(pid) {
Some((bundle_id, _)) => bundle_id,
None => continue,
},
};
// Safari plays through a WebKit process told apart only by its name.
let name = bundle_id
.eq_ignore_ascii_case("com.apple.WebKit.GPU")
.then(|| running_application_info(pid))
.flatten()
.and_then(|(_, name)| name);
let id = canonical_bundle_id_for(&bundle_id, name.as_deref())
.unwrap_or(bundle_id.as_str())
.to_owned();
if pid == own_pid || is_hex_bundle(&id) || is_hex_bundle(&bundle_id) {
continue;
}
processes.push(OutputProcess {
object: process_object,
pid,
bundle_id,
id,
running_output: property_value::<u32>(
process_object,
kAudioProcessPropertyIsRunningOutput,
)
.is_ok_and(|running| running != 0),
});
}
Ok(processes)
})
}
#[cfg(target_os = "macos")]
/// The applications playing output now, Hex excluded, for Labs › Choose
/// meeting audio: each canonical bundle id (else its own) and a display
/// name. A helper process is named as its app, once; only Core Audio's
/// process metadata is read, never audio.
pub(crate) fn playing_output_applications() -> Vec<(String, String)> {
let Ok(processes) = output_process_objects() else {
return Vec::new();
};
objc2::rc::autoreleasepool(|_| {
let mut applications: Vec<(String, String)> = Vec::new();
for process in processes.iter().filter(|process| process.running_output) {
if applications.iter().any(|(known, _)| *known == process.id) {
continue;
}
let localized = running_application_info(process.pid).and_then(|(_, name)| name);
applications.push((
process.id.clone(),
display_name(&process.bundle_id, localized),
));
}
applications.sort_by_key(|(_, name)| name.to_lowercase());
applications
})
}
/// One device a call app's process reports recording from: the UID Core
/// Audio names it by and the input channels it offers. An output-only device
/// the app lists, such as the MacBook Pro Speakers, has no input channels and
/// is never a microphone.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ReportedInput {
pub(crate) uid: String,
pub(crate) input_channels: u32,
}
#[cfg(target_os = "macos")]
/// The devices the app `canonical_bundle_id` (its helpers included) reports
/// recording from, read from each of its processes running input, with the
/// input channels each one offers. macOS 14 and later report them; earlier
/// systems report none. Output-only devices are reported too, so the caller
/// can log and skip them; only the ones with input channels may be followed.
pub(crate) fn application_input_devices(canonical_bundle_id: &str) -> Result<Vec<ReportedInput>> {
objc2::rc::autoreleasepool(|_| {
let process_objects = property_vec::<AudioObjectID>(
kAudioObjectSystemObject as AudioObjectID,
kAudioHardwarePropertyProcessObjectList,
)?;
let mut reported: Vec<ReportedInput> = Vec::new();
for process_object in process_objects {
let recording =
property_value::<u32>(process_object, kAudioProcessPropertyIsRunningInput)
.is_ok_and(|running| running != 0)
&& property_cf_string(process_object, kAudioProcessPropertyBundleID)
.is_some_and(|bundle_id| is_process_of(&bundle_id, canonical_bundle_id));
if !recording {
continue;
}
let Ok(devices) = property_vec_in::<AudioObjectID>(
process_object,
kAudioProcessPropertyDevices,
kAudioObjectPropertyScopeInput,
) else {
continue;
};
for device in devices {
let Some(uid) = property_cf_string(device, kAudioDevicePropertyDeviceUID) else {
continue;
};
let input_channels = input_channel_count(device);
match reported.iter_mut().find(|input| input.uid == uid) {
Some(input) => input.input_channels = input.input_channels.max(input_channels),
None => reported.push(ReportedInput {
uid,
input_channels,
}),
}
}
}
Ok(reported)
})
}
#[cfg(target_os = "macos")]
/// How many input channels `device` offers, from its input stream
/// configuration: an output-only device such as the built-in speakers has
/// none. A device Core Audio will not describe counts as having none.
fn input_channel_count(device: AudioObjectID) -> u32 {
let mut address = property_address_in(
kAudioDevicePropertyStreamConfiguration,
kAudioObjectPropertyScopeInput,
);
let mut bytes = 0u32;
// SAFETY: The property address and size point to initialized stack values.
let status = unsafe {
AudioObjectGetPropertyDataSize(
device,
NonNull::from(&mut address),
0,
std::ptr::null(),
NonNull::from(&mut bytes),
)
};
if status != 0 || !(size_of::<AudioBufferList>() as u32..=65536).contains(&bytes) {
return 0;
}
// u64 storage gives AudioBufferList and its pointer fields their required alignment.
let mut storage = vec![0u64; (bytes as usize).div_ceil(size_of::<u64>())];
// SAFETY: Storage is aligned and has at least the size reported by CoreAudio.
let status = unsafe {
AudioObjectGetPropertyData(
device,
NonNull::from(&mut address),
0,
std::ptr::null(),
NonNull::from(&mut bytes),
NonNull::new(storage.as_mut_ptr()).unwrap().cast(),
)
};
if status != 0
|| bytes as usize > storage.len() * size_of::<u64>()
|| (bytes as usize) < size_of::<AudioBufferList>()
{
return 0;
}
// SAFETY: The successful property read initialized the header within storage.
let count = unsafe { (*(storage.as_ptr().cast::<AudioBufferList>())).mNumberBuffers } as usize;
let offset = offset_of!(AudioBufferList, mBuffers);
let Some(end) = count
.checked_mul(size_of::<AudioBuffer>())
.and_then(|buffers| offset.checked_add(buffers))
else {
return 0;
};
if end > bytes as usize {
return 0;
}
// SAFETY: The bounds above cover every buffer, and offset preserves alignment.
let buffers = unsafe {
std::slice::from_raw_parts(
storage
.as_ptr()
.cast::<u8>()
.add(offset)
.cast::<AudioBuffer>(),
count,
)
};
buffers.iter().fold(0u32, |channels, buffer| {
channels.saturating_add(buffer.mNumberChannels)
})
}
#[cfg(target_os = "macos")]
/// The process IDs recording from the input device `uid`, read from Core
/// Audio's process metadata: devices only, never audio samples. Hex's own
/// process is included; a caller that records excludes itself. A failed
/// per-process read, including a listed device's UID, fails the whole call,
/// so a dropped pid is never mistaken for an app that stopped recording.
pub(crate) fn input_recorders(uid: &str) -> Result<Vec<i32>> {
objc2::rc::autoreleasepool(|_| {
let process_objects = property_vec::<AudioObjectID>(
kAudioObjectSystemObject as AudioObjectID,
kAudioHardwarePropertyProcessObjectList,
)?;
let mut pids = Vec::new();
for process_object in process_objects {
let recording =
property_value::<u32>(process_object, kAudioProcessPropertyIsRunningInput)?;
if recording == 0 {
continue;
}
let devices = property_vec_in::<AudioObjectID>(
process_object,
kAudioProcessPropertyDevices,
kAudioObjectPropertyScopeInput,
)?;
let mut records_uid = false;
for device in devices {
let device_uid = property_cf_string(device, kAudioDevicePropertyDeviceUID)
.ok_or_else(|| {
eyre!("could not read a recording process's input device uid")
})?;
if device_uid == uid {
records_uid = true;
break;
}
}
if !records_uid {
continue;
}
let pid = property_value::<i32>(process_object, kAudioProcessPropertyPID)?;
pids.push(pid);
}
Ok(pids)
})
}
/// Whether the Core Audio process `bundle_id` belongs to the app
/// `canonical_bundle_id`: the app itself or one of its helpers, such as the
/// browser helper that holds the microphone for a Meet tab.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn is_process_of(bundle_id: &str, canonical_bundle_id: &str) -> bool {
canonical_bundle_id_for(bundle_id, None) == Some(canonical_bundle_id)
}
/// Linux and Windows executables (lowercase, without `.exe`) by the bundle
/// identifier of the same app on macOS.
const EXECUTABLES: [(&str, &str); 47] = [
// Discord and its Canary and PTB builds, on Windows and Linux (the
// Flatpak runs the same binary).
("discord", "com.hnc.Discord"),
("discordcanary", "com.hnc.Discord"),
("discordptb", "com.hnc.Discord"),
("discord-canary", "com.hnc.Discord"),
("discord-ptb", "com.hnc.Discord"),
("com.discordapp.discord", "com.hnc.Discord"),
// Gather for Windows.
("gather", "com.gather.GatherV2"),
("gatherv2", "com.gather.GatherV2"),
// WhatsApp for Windows, before and after its WinUI rewrite.
("whatsapp", "net.whatsapp.WhatsApp"),
("whatsapp.root", "net.whatsapp.WhatsApp"),
// The apps Hex knows beyond the common ones.
("signal", "org.whispersystems.signal-desktop"),
("signal-desktop", "org.whispersystems.signal-desktop"),
("telegram", "ru.keepcoder.Telegram"),
("telegram-desktop", "ru.keepcoder.Telegram"),
("element", "im.riot.app"),
("element-desktop", "im.riot.app"),
("webex", "com.webex.meetingmanager"),
// The Webex app's multiprocess host on Windows (Cisco's executable list).
("ciscocollabhost", "com.webex.meetingmanager"),
("wechat", "com.tencent.xinWeChat"),
("weixin", "com.tencent.xinWeChat"),
("line", "jp.naver.line.mac"),
("zoom", "us.zoom.xos"),
("ms-teams", "com.microsoft.teams2"),
("teams", "com.microsoft.teams2"),
("teams-for-linux", "com.microsoft.teams2"),
("slack", "com.tinyspeck.slackmacgap"),
("chrome", "com.google.Chrome"),
("google-chrome", "com.google.Chrome"),
("google-chrome-stable", "com.google.Chrome"),
("chromium", "com.google.Chrome"),
("chromium-browser", "com.google.Chrome"),
("brave", "com.brave.Browser"),
("brave-browser", "com.brave.Browser"),
("helium", "net.imput.helium"),
("helium-browser", "net.imput.helium"),
("firefox", "org.mozilla.firefox"),
("firefox-bin", "org.mozilla.firefox"),
("firefox-esr", "org.mozilla.firefox"),
// Zen is Firefox-based. Its Flatpak and tarball launcher run `zen`, the
// tarball's binary is `zen-bin`, and every content process keeps the same
// executable, so the microphone's binary names the browser.
("zen", "app.zen-browser.zen"),
("zen-bin", "app.zen-browser.zen"),
("msedge", "com.microsoft.edgemac"),
("microsoft-edge", "com.microsoft.edgemac"),
("microsoft-edge-stable", "com.microsoft.edgemac"),
// Vivaldi, its web apps (PWAs) included: they run in the same process.
("vivaldi", "com.vivaldi.Vivaldi"),
("vivaldi-bin", "com.vivaldi.Vivaldi"),
("vivaldi-stable", "com.vivaldi.Vivaldi"),
("vivaldi-snapshot", "com.vivaldi.Vivaldi"),
];
pub(crate) fn canonical_bundle_id_for(bundle_id: &str, name: Option<&str>) -> Option<&'static str> {
let bundle = bundle_id.to_ascii_lowercase();
let executable = bundle.strip_suffix(".exe").unwrap_or(&bundle);
if let Some((_, canonical)) = EXECUTABLES.iter().find(|(known, _)| *known == executable) {
return Some(canonical);
}
if bundle == "com.apple.webkit.gpu" {
return name
.is_some_and(|name| name.to_ascii_lowercase().starts_with("safari"))
.then_some("com.apple.Safari");
}
[
("us.zoom.xos", "us.zoom.xos"),
("us.zoom.cpthost", "us.zoom.xos"),
("us.zoom.caphost", "us.zoom.xos"),
("us.zoom.aomhost", "us.zoom.xos"),
("us.zoom.zoomcefhelper", "us.zoom.xos"),
("us.zoom.zccimeetinghost", "us.zoom.xos"),
("us.zoom.zoomphone", "us.zoom.xos"),
("us.zoom.zoomhybridconf", "us.zoom.xos"),
("com.microsoft.teams2", "com.microsoft.teams2"),
("com.microsoft.teams", "com.microsoft.teams2"),
("com.tinyspeck.slackmacgap", "com.tinyspeck.slackmacgap"),
("com.apple.facetime", "com.apple.FaceTime"),
// The native (Catalyst) app, and the older Electron one.
("net.whatsapp.whatsapp", "net.whatsapp.WhatsApp"),
("desktop.whatsapp", "net.whatsapp.WhatsApp"),
// Gather V2 and its Electron helpers, and Gather V1.
("com.gather.gatherv2", "com.gather.GatherV2"),
("com.gather.gather", "com.gather.GatherV2"),
// Discord and its helpers, and its Canary and PTB builds.
("com.hnc.discord", "com.hnc.Discord"),
("com.hnc.discordcanary", "com.hnc.Discord"),
("com.hnc.discordptb", "com.hnc.Discord"),
// The apps Hex knows beyond the common ones, their Electron helpers and
// alternative bundle IDs included.
(
"org.whispersystems.signal-desktop",
"org.whispersystems.signal-desktop",
),
("ru.keepcoder.telegram", "ru.keepcoder.Telegram"),
("com.tdesktop.telegram", "ru.keepcoder.Telegram"),
("org.telegram.desktop", "ru.keepcoder.Telegram"),
("com.tencent.xinwechat", "com.tencent.xinWeChat"),
("jp.naver.line.mac", "jp.naver.line.mac"),
("com.webex.meetingmanager", "com.webex.meetingmanager"),
("com.cisco.webexmeetingsapp", "com.webex.meetingmanager"),
// The current Webex app uses Spark's bundle id, helpers included.
("cisco-systems.spark", "com.webex.meetingmanager"),
("im.riot.app", "im.riot.app"),
("com.apple.mobilephone", "com.apple.mobilephone"),
("com.google.chrome", "com.google.Chrome"),
("at.studio.asidebrowser", "at.studio.AsideBrowser"),
("com.brave.browser", "com.brave.Browser"),
("com.apple.safari", "com.apple.Safari"),
("org.mozilla.firefox", "org.mozilla.firefox"),
("org.mozilla.plugincontainer", "org.mozilla.firefox"),
("com.microsoft.edgemac", "com.microsoft.edgemac"),
("company.thebrowser.browser", "company.thebrowser.Browser"),
("com.vivaldi.vivaldi", "com.vivaldi.Vivaldi"),
("net.imput.helium", "net.imput.helium"),
// Ardia's Chromium audio service reports `com.ardia.browser.helper`.
("com.ardia.browser", "com.ardia.browser"),
// Zen is Firefox-based: its main process and its helpers, which are
// `app.zen-browser.*` rather than `org.mozilla.*`.
("app.zen-browser", "app.zen-browser.zen"),
]
.iter()
.find_map(|(prefix, canonical)| {
bundle
.strip_prefix(prefix)
.is_some_and(|rest| rest.is_empty() || rest.starts_with('.'))
.then_some(*canonical)
})
}
pub(crate) fn canonical_application_name(canonical_bundle_id: &str) -> Option<&'static str> {
match canonical_bundle_id {
"us.zoom.xos" => Some("zoom.us"),
"com.microsoft.teams2" => Some("Microsoft Teams"),
"com.tinyspeck.slackmacgap" => Some("Slack"),
"com.apple.FaceTime" => Some("FaceTime"),
"net.whatsapp.WhatsApp" => Some("WhatsApp"),
"com.gather.GatherV2" => Some("Gather"),
"com.hnc.Discord" => Some("Discord"),
"org.whispersystems.signal-desktop" => Some("Signal"),
"ru.keepcoder.Telegram" => Some("Telegram"),
"com.tencent.xinWeChat" => Some("WeChat"),
"jp.naver.line.mac" => Some("LINE"),
"com.webex.meetingmanager" => Some("Webex"),
"im.riot.app" => Some("Element"),
"com.apple.mobilephone" => Some("Phone"),
"at.studio.AsideBrowser" => Some("Aside"),
"com.google.Chrome" => Some("Google Chrome"),
"com.brave.Browser" => Some("Brave Browser"),
"com.apple.Safari" => Some("Safari"),
"org.mozilla.firefox" => Some("Firefox"),
"com.microsoft.edgemac" => Some("Microsoft Edge"),
"company.thebrowser.Browser" => Some("Arc"),
"com.vivaldi.Vivaldi" => Some("Vivaldi"),
"net.imput.helium" => Some("Helium"),
"com.ardia.browser" => Some("Ardia"),
"app.zen-browser.zen" => Some("Zen"),
_ => None,
}
}
#[cfg(target_os = "macos")]
fn is_helper_bundle_id(bundle_id: &str) -> bool {
let lower = bundle_id.to_ascii_lowercase();
lower.ends_with(".helper")
|| lower.contains(".helper.")
|| matches!(
lower.as_str(),
"com.apple.webkit.gpu"
| "us.zoom.cpthost"
| "us.zoom.caphost"
| "us.zoom.aomhost"
| "us.zoom.zoomcefhelper"
| "us.zoom.zccimeetinghost"
| "org.mozilla.plugincontainer"
| "app.zen-browser.plugincontainer"
)
}
#[cfg(target_os = "macos")]
fn display_name(bundle_id: &str, localized_name: Option<String>) -> String {
if !is_helper_bundle_id(bundle_id)
&& let Some(name) = localized_name.as_ref().filter(|name| !name.is_empty())
{
return name.clone();
}
if let Some(canonical) = canonical_bundle_id_for(bundle_id, localized_name.as_deref())
&& let Some(name) = canonical_application_name(canonical)
{
return name.to_string();
}
localized_name
.filter(|name| !name.is_empty())
.unwrap_or_else(|| bundle_id.to_string())
}
#[cfg(target_os = "macos")]
fn resolve_application_with(
pid: i32,
audio_bundle_id: Option<String>,
mut lookup_running_app: impl FnMut(i32) -> Option<(String, Option<String>)>,
mut lookup_parent_pid: impl FnMut(i32) -> Option<i32>,
mut lookup_running_by_bundle: impl FnMut(&str) -> Option<(i32, String)>,
) -> Option<ActiveMicrophoneApplication> {
let direct = lookup_running_app(pid);
if let Some((ref bundle_id, ref name)) = direct
&& !is_helper_bundle_id(bundle_id)
{
return Some(ActiveMicrophoneApplication {
pid,
name: display_name(bundle_id, name.clone()),
bundle_id: bundle_id.clone(),
});
}
// Chromium and Electron run microphone input in a sandboxed utility
// process (`audio.mojom.AudioService`) that does not register with
// LaunchServices, so `NSRunningApplication(processIdentifier:)` returns
// nil for the helper PID while its parent process is the host browser/app.
let mut current_pid = pid;
for _ in 0..4 {
let Some(parent) = lookup_parent_pid(current_pid) else {
break;
};
if let Some((parent_bundle, parent_name)) = lookup_running_app(parent)
&& !is_helper_bundle_id(&parent_bundle)
&& audio_bundle_id.as_deref().is_none_or(|audio_bundle| {
is_helper_bundle_id(audio_bundle)
|| audio_bundle.eq_ignore_ascii_case(&parent_bundle)
|| (canonical_bundle_id_for(audio_bundle, None).is_some()
&& canonical_bundle_id_for(audio_bundle, None)
== canonical_bundle_id_for(&parent_bundle, parent_name.as_deref()))
})
{
return Some(ActiveMicrophoneApplication {
pid: parent,
name: display_name(&parent_bundle, parent_name),
bundle_id: parent_bundle,
});
}
current_pid = parent;
}
if audio_bundle_id.as_deref() == Some("com.apple.avconferenced") {
let (facetime_pid, facetime_name) = lookup_running_by_bundle("com.apple.FaceTime")?;
return Some(ActiveMicrophoneApplication {
pid: facetime_pid,
bundle_id: "com.apple.FaceTime".into(),
name: facetime_name,
});
}
let (bundle_id, localized_name) = match (direct, audio_bundle_id) {
(Some((bundle_id, name)), _) => (bundle_id, name),
(None, Some(bundle_id)) => (bundle_id, None),
(None, None) => return None,
};
if is_helper_bundle_id(&bundle_id)
&& let Some(canonical) = canonical_bundle_id_for(&bundle_id, localized_name.as_deref())
&& let Some((host_pid, host_name)) = lookup_running_by_bundle(canonical)
{
return Some(ActiveMicrophoneApplication {
pid: host_pid,
bundle_id: canonical.into(),
name: host_name,
});
}
Some(ActiveMicrophoneApplication {
pid,
name: display_name(&bundle_id, localized_name),
bundle_id,
})
}
#[cfg(target_os = "macos")]
fn running_application_info(pid: i32) -> Option<(String, Option<String>)> {
let application = NSRunningApplication::runningApplicationWithProcessIdentifier(pid)?;
let bundle_id = application.bundleIdentifier()?.to_string();
if bundle_id.is_empty() {
return None;
}
let name = application.localizedName().map(|name| name.to_string());
Some((bundle_id, name))
}
#[cfg(target_os = "macos")]
pub(crate) fn running_application_by_bundle_id(bundle_id: &str) -> Option<(i32, String)> {
let candidates = NSRunningApplication::runningApplicationsWithBundleIdentifier(
&NSString::from_str(bundle_id),
);
let application = candidates.firstObject()?;
let pid = application.processIdentifier();
let name = application
.localizedName()
.map(|name| name.to_string())
.filter(|name| !name.is_empty())
.or_else(|| canonical_application_name(bundle_id).map(str::to_string))
.unwrap_or_else(|| bundle_id.to_string());
Some((pid, name))
}
#[cfg(target_os = "macos")]
fn parent_pid(pid: i32) -> Option<i32> {
if pid <= 1 {
return None;
}
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = size_of::<libc::proc_bsdinfo>() as libc::c_int;
let written = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDTBSDINFO,
0,
(&raw mut info).cast::<c_void>(),
size,
)
};
if written != size {
return None;
}
let ppid = i32::try_from(info.pbi_ppid).ok()?;
(ppid > 1 && ppid != pid).then_some(ppid)
}
#[cfg(target_os = "macos")]
/// AppKit returns these lookups autoreleased. The meeting watcher polls from
/// a plain thread with no pool to drain them, so each poll would otherwise
/// keep every `NSRunningApplication` it touched for the life of the process.
pub fn active_microphone_applications() -> Result<Vec<ActiveMicrophoneApplication>> {
objc2::rc::autoreleasepool(|_| inspect_microphone_applications(None))
}
#[cfg(target_os = "macos")]
pub(crate) fn applications_using_input(
device: AudioObjectID,
) -> Result<Vec<ActiveMicrophoneApplication>> {
objc2::rc::autoreleasepool(|_| inspect_microphone_applications(Some(device)))
}
#[cfg(target_os = "macos")]
fn inspect_microphone_applications(
device: Option<AudioObjectID>,
) -> Result<Vec<ActiveMicrophoneApplication>> {
let process_objects = property_vec::<AudioObjectID>(
kAudioObjectSystemObject as AudioObjectID,
kAudioHardwarePropertyProcessObjectList,
)?;
let mut applications = Vec::new();
for process_object in process_objects {
let Ok(is_running_input) =
property_value::<u32>(process_object, kAudioProcessPropertyIsRunningInput)
else {
continue;
};
if is_running_input == 0
|| device.is_some_and(|id| {
!property_vec_in::<AudioObjectID>(
process_object,
kAudioProcessPropertyDevices,
kAudioObjectPropertyScopeInput,
)
.is_ok_and(|devices| devices.contains(&id))
})
{
continue;
}
let Ok(pid) = property_value::<i32>(process_object, kAudioProcessPropertyPID) else {
continue;
};
let audio_bundle_id = property_cf_string(process_object, kAudioProcessPropertyBundleID);
let Some(application) = resolve_application_with(
pid,
audio_bundle_id,
running_application_info,
parent_pid,
running_application_by_bundle_id,
) else {
continue;
};
applications.push(application);
}
Ok(deduplicated(applications))
}
#[cfg(target_os = "macos")]
fn property_address(selector: AudioObjectPropertySelector) -> AudioObjectPropertyAddress {
property_address_in(selector, kAudioObjectPropertyScopeGlobal)
}
#[cfg(target_os = "macos")]
fn property_address_in(
selector: AudioObjectPropertySelector,
scope: AudioObjectPropertyScope,
) -> AudioObjectPropertyAddress {
AudioObjectPropertyAddress {
mSelector: selector,
mScope: scope,
mElement: kAudioObjectPropertyElementMain,
}
}
#[cfg(target_os = "macos")]
fn property_value<T: Copy + Default>(
object: AudioObjectID,
selector: AudioObjectPropertySelector,
) -> Result<T> {
let mut value = T::default();
let mut size = size_of::<T>() as u32;
let mut address = property_address(selector);
let status = unsafe {
AudioObjectGetPropertyData(
object,
NonNull::from(&mut address),
0,
std::ptr::null(),
NonNull::from(&mut size),
NonNull::from(&mut value).cast::<c_void>(),
)
};
if status == 0 && size as usize == size_of::<T>() {
Ok(value)
} else {
Err(eyre!(
"CoreAudio property {selector:#x} failed with status {status} and size {size}"
))
}
}
#[cfg(target_os = "macos")]
fn property_vec<T: Copy + Default>(
object: AudioObjectID,
selector: AudioObjectPropertySelector,
) -> Result<Vec<T>> {
property_vec_in(object, selector, kAudioObjectPropertyScopeGlobal)
}
#[cfg(target_os = "macos")]
fn property_vec_in<T: Copy + Default>(
object: AudioObjectID,
selector: AudioObjectPropertySelector,
scope: AudioObjectPropertyScope,
) -> Result<Vec<T>> {
let mut address = property_address_in(selector, scope);
let mut size = 0;
let status = unsafe {
AudioObjectGetPropertyDataSize(
object,
NonNull::from(&mut address),
0,
std::ptr::null(),
NonNull::from(&mut size),
)
};
if status != 0 {
return Err(eyre!(
"CoreAudio property size {selector:#x} failed with status {status}"
));
}
if !(size as usize).is_multiple_of(size_of::<T>()) {
return Err(eyre!(
"CoreAudio property {selector:#x} had invalid size {size}"
));
}
let mut values = vec![T::default(); size as usize / size_of::<T>()];
if values.is_empty() {
return Ok(values);
}
let status = unsafe {
AudioObjectGetPropertyData(
object,
NonNull::from(&mut address),
0,
std::ptr::null(),
NonNull::from(&mut size),
NonNull::new(values.as_mut_ptr().cast::<c_void>())
.ok_or_else(|| eyre!("CoreAudio returned a null output buffer"))?,
)
};
if status == 0 {
values.truncate(size as usize / size_of::<T>());
Ok(values)
} else {
Err(eyre!(
"CoreAudio property {selector:#x} failed with status {status}"
))
}
}
#[cfg(target_os = "macos")]
fn property_cf_string(
object: AudioObjectID,
selector: AudioObjectPropertySelector,
) -> Option<String> {
let mut raw: *const CFString = std::ptr::null();
let mut size = size_of::<*const CFString>() as u32;
let mut address = property_address(selector);
let status = unsafe {
AudioObjectGetPropertyData(
object,
NonNull::from(&mut address),
0,
std::ptr::null(),
NonNull::from(&mut size),
NonNull::from(&mut raw).cast::<c_void>(),
)
};
if status != 0 || size as usize != size_of::<*const CFString>() {
return None;
}
let ptr = NonNull::new(raw.cast_mut())?;
let cf_string = unsafe { CFRetained::from_raw(ptr) };
let value = cf_string.to_string();
(!value.is_empty()).then_some(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "macos")]
fn physical_footprint() -> u64 {
let mut info: libc::rusage_info_v4 = unsafe { std::mem::zeroed() };
let status = unsafe {
libc::proc_pid_rusage(
std::process::id() as i32,
libc::RUSAGE_INFO_V4,
(&raw mut info).cast(),
)
};
assert_eq!(status, 0);
info.ri_phys_footprint
}
/// Polls like the meeting watcher, from a thread without an autorelease
/// pool. Run alone: footprint is process-wide.
#[cfg(target_os = "macos")]
#[test]
#[ignore = "measures process footprint; needs another app using the microphone"]
fn polling_microphone_activity_does_not_accumulate_running_applications() {
std::thread::spawn(|| {
assert!(
!active_microphone_applications().unwrap().is_empty(),
"an app must be using the microphone"
);
let before = physical_footprint();
for _ in 0..20_000 {
active_microphone_applications().unwrap();
}
let grown = physical_footprint().saturating_sub(before);
println!("footprint grew {} KB over 20,000 polls", grown / 1024);
assert!(grown < 2 * 1024 * 1024, "grew {grown} bytes");
})
.join()
.unwrap();
}
#[cfg(target_os = "macos")]
#[test]
fn resolves_unregistered_chromium_and_electron_audio_helpers_to_their_host_apps() {
// Brave's sandboxed `audio.mojom.AudioService` helper is not registered in
// `NSRunningApplication`, reports `com.brave.Browser.helper` to CoreAudio,
// and is a child of the main `Brave Browser` process.
let brave = resolve_application_with(
2352,
Some("com.brave.Browser.helper".into()),
|pid| match pid {
1592 => Some(("com.brave.Browser".into(), Some("Brave Browser".into()))),
_ => None,
},
|pid| (pid == 2352).then_some(1592),
|_| None,
)
.unwrap();
assert_eq!(
brave,
ActiveMicrophoneApplication {
pid: 1592,
bundle_id: "com.brave.Browser".into(),
name: "Brave Browser".into(),
}
);
assert!(brave.is_supported_meeting_app());
assert!(brave.is_browser());
assert_eq!(brave.canonical_bundle_id(), Some("com.brave.Browser"));
// Slack's audio utility process behaves the same way.
let slack = resolve_application_with(
31807,
Some("com.tinyspeck.slackmacgap.helper".into()),
|pid| match pid {
31782 => Some(("com.tinyspeck.slackmacgap".into(), Some("Slack".into()))),
_ => None,
},
|pid| (pid == 31807).then_some(31782),
|_| None,
)
.unwrap();
assert_eq!(
slack,
ActiveMicrophoneApplication {
pid: 31782,
bundle_id: "com.tinyspeck.slackmacgap".into(),
name: "Slack".into(),
}
);
assert!(slack.is_supported_meeting_app());
assert!(!slack.is_browser());
assert_eq!(
slack.canonical_bundle_id(),
Some("com.tinyspeck.slackmacgap")
);
}
#[cfg(target_os = "macos")]
#[test]
fn resolves_helper_bundle_ids_when_parent_lookup_is_unavailable() {
let chrome = resolve_application_with(
4100,
Some("com.google.Chrome.helper".into()),
|_| None,
|_| None,
|bundle| (bundle == "com.google.Chrome").then_some((4000, "Google Chrome".into())),
)
.unwrap();
assert_eq!(
chrome,
ActiveMicrophoneApplication {
pid: 4000,
bundle_id: "com.google.Chrome".into(),
name: "Google Chrome".into(),
}
);
let zoom = resolve_application_with(
9010,
Some("us.zoom.CptHost".into()),
|_| Some(("us.zoom.CptHost".into(), Some("CptHost".into()))),
|_| None,
|bundle| (bundle == "us.zoom.xos").then_some((9000, "zoom.us".into())),
)
.unwrap();
assert_eq!(
zoom,
ActiveMicrophoneApplication {
pid: 9000,
bundle_id: "us.zoom.xos".into(),
name: "zoom.us".into(),
}
);
assert_eq!(zoom.canonical_bundle_id(), Some("us.zoom.xos"));
}
#[cfg(target_os = "macos")]
#[test]
fn attributes_safari_webkit_gpu_and_facetime_avconferenced_only_when_active() {
let safari = resolve_application_with(
7100,
Some("com.apple.WebKit.GPU".into()),
|_| {
Some((
"com.apple.WebKit.GPU".into(),
Some("Safari Graphics and Media".into()),
))
},
|_| None,
|bundle| (bundle == "com.apple.Safari").then_some((7000, "Safari".into())),
)
.unwrap();
assert_eq!(safari.canonical_bundle_id(), Some("com.apple.Safari"));
assert!(safari.is_browser());
let non_safari_webkit = resolve_application_with(
7200,
Some("com.apple.WebKit.GPU".into()),
|_| {
Some((
"com.apple.WebKit.GPU".into(),
Some("Mail Graphics and Media".into()),
))
},
|_| None,
|_| Some((7000, "Safari".into())),
)
.unwrap();
assert_eq!(non_safari_webkit.canonical_bundle_id(), None);
assert!(!non_safari_webkit.is_supported_meeting_app());
let facetime = resolve_application_with(
8100,
Some("com.apple.avconferenced".into()),
|_| None,
|_| None,
|bundle| (bundle == "com.apple.FaceTime").then_some((8000, "FaceTime".into())),
)
.unwrap();
assert_eq!(facetime.canonical_bundle_id(), Some("com.apple.FaceTime"));
assert_eq!(facetime.name, "FaceTime");
assert!(
resolve_application_with(
8100,
Some("com.apple.avconferenced".into()),
|_| None,
|_| None,
|_| None,
)
.is_none()
);
}
#[cfg(target_os = "macos")]
#[test]
fn a_pause_taps_only_browsers_with_open_output() {
assert!(BrowserProcesses::Playing.includes(Some(true)));
assert!(!BrowserProcesses::Playing.includes(Some(false)));
assert!(BrowserProcesses::Playing.includes(None));
assert!(BrowserProcesses::All.includes(Some(false)));
}
#[test]
fn a_chosen_meeting_app_taps_every_one_of_its_processes() {
let process =
|object: u32, bundle_id: &str, id: &str, running_output: bool| OutputProcess {
object,
pid: 1_000 + object as i32,
bundle_id: bundle_id.into(),
id: id.into(),
running_output,
};
let processes = [
// A browser's own process and its audio service, both its own.
process(10, "com.google.Chrome", "com.google.Chrome", true),
process(11, "com.google.Chrome.helper", "com.google.Chrome", true),
// A helper whose output is closed now is tapped anyway, so it is
// heard as soon as it plays again and the tap is only rebuilt
// when the set of processes changes.
process(12, "com.google.Chrome.helper", "com.google.Chrome", false),
process(20, "com.apple.Music", "com.apple.Music", true),
// Hex's own audio never joins a tap, even naming a retired build.
process(30, "anomaly.hex", "anomaly.hex", true),
process(31, "com.kitlangton.hex2", "com.kitlangton.hex2", true),
];
assert_eq!(
app_process_objects("com.google.Chrome", &processes),
[10, 11, 12]
);
assert_eq!(app_process_objects("com.apple.Music", &processes), [20]);
// An app that isn't playing is tapped as it is, and reaches the track
// as silence; an app that isn't running never taps every output.
assert_eq!(
app_process_objects(
"com.apple.Music",
&[process(21, "com.apple.Music", "com.apple.Music", false)]
),
[21]
);
assert!(app_process_objects("com.apple.Safari", &processes).is_empty());
assert!(app_process_objects("anomaly.hex", &processes).is_empty());
assert!(app_process_objects("com.kitlangton.hex2", &processes).is_empty());
// Reading the same processes in another order is not a change, so
// the tap is not rebuilt for it.
let reordered = processes.iter().rev().cloned().collect::<Vec<_>>();
assert_eq!(
app_process_objects("com.google.Chrome", &processes),
app_process_objects("com.google.Chrome", &reordered)
);
}
#[test]
fn a_helper_process_belongs_to_the_app_its_bundle_id_names() {
for (bundle_id, canonical) in [
("com.google.Chrome.helper.Renderer", "com.google.Chrome"),
("us.zoom.CptHost", "us.zoom.xos"),
("com.microsoft.teams2.helper", "com.microsoft.teams2"),
("app.zen-browser.zen-gpu-helper", "app.zen-browser.zen"),
] {
let process = OutputProcess {
object: 7,
pid: 70,
bundle_id: bundle_id.into(),
id: canonical_bundle_id_for(bundle_id, None)
.unwrap_or(bundle_id)
.into(),
running_output: true,
};
assert_eq!(
canonical_bundle_id_for(bundle_id, None),
Some(canonical),
"{bundle_id}"
);
assert_eq!(
app_process_objects(canonical, std::slice::from_ref(&process)),
[7],
"{bundle_id}"
);
assert!(
app_process_objects("com.brave.Browser", &[process]).is_empty(),
"{bundle_id}"
);
}
}
#[test]
fn hex_is_never_an_app_a_meeting_records() {
for bundle_id in [
"anomaly.hex",
"anomaly.hex.test",
"COM.KITLANGTON.HEX2",
"com.kitlangton.Hex",
"com.kitlangton.Hex.debug",
] {
assert!(is_hex_bundle(bundle_id), "{bundle_id}");
}
for bundle_id in [
"com.apple.Music",
"com.google.Chrome",
"com.tinyspeck.slackmacgap",
] {
assert!(!is_hex_bundle(bundle_id), "{bundle_id}");
}
}
#[test]
fn a_call_apps_helper_processes_belong_to_it() {
// The processes that held the microphone in Google Meet calls (#1086).
assert!(is_process_of(
"company.thebrowser.browser.helper",
"company.thebrowser.Browser"
));
assert!(is_process_of(
"com.google.Chrome.helper",
"com.google.Chrome"
));
assert!(is_process_of(
"com.google.Chrome.helper.Renderer",
"com.google.Chrome"
));
assert!(is_process_of(
"net.imput.helium.helper.Renderer",
"net.imput.helium"
));
assert!(is_process_of(
"com.ardia.browser.helper",
"com.ardia.browser"
));
// Zen's audio process is the main app; its helpers are Zen's own.
assert!(is_process_of("app.zen-browser.zen", "app.zen-browser.zen"));
assert!(is_process_of(
"app.zen-browser.plugincontainer",
"app.zen-browser.zen"
));
assert!(is_process_of(
"app.zen-browser.zen-gpu-helper",
"app.zen-browser.zen"
));
assert!(is_process_of(
"app.zen-browser.zen-media-plugin-helper",
"app.zen-browser.zen"
));
assert!(is_process_of("com.google.Chrome", "com.google.Chrome"));
assert!(!is_process_of(
"com.google.Chrome.helper",
"company.thebrowser.Browser"
));
assert!(!is_process_of(
"company.thebrowser.dia",
"company.thebrowser.Browser"
));
assert!(!is_process_of("com.google.Chromecast", "com.google.Chrome"));
// A prefix without the dot boundary is a different app.
assert!(!is_process_of("com.ardia.browserx", "com.ardia.browser"));
assert!(!is_process_of("app.zen-browserx", "app.zen-browser.zen"));
}
#[test]
fn browser_bundles_include_helpers() {
assert!(browser_bundle("com.brave.Browser.helper", None));
assert!(browser_bundle("com.google.Chrome.helper", None));
assert!(browser_bundle("net.imput.helium.helper", None));
assert!(browser_bundle("com.ardia.browser.helper", None));
assert!(browser_bundle("at.studio.AsideBrowser.helper", None));
assert!(browser_bundle("app.zen-browser.zen", None));
assert!(browser_bundle("app.zen-browser.plugincontainer", None));
assert!(browser_bundle(
"com.apple.WebKit.GPU",
Some("Safari Graphics and Media")
));
assert!(!browser_bundle(
"com.apple.WebKit.GPU",
Some("Mail Graphics and Media")
));
assert!(!browser_bundle("com.spotify.client", None));
assert!(!browser_bundle("com.kitlangton.hex2", None));
}
#[test]
fn canonical_bundle_matching_covers_supported_apps_and_variants() {
for (bundle_id, name, expected, browser) in [
("us.zoom.xos", "zoom.us", Some("us.zoom.xos"), false),
("us.zoom.CptHost", "CptHost", Some("us.zoom.xos"), false),
(
"com.microsoft.teams2",
"Microsoft Teams",
Some("com.microsoft.teams2"),
false,
),
(
"com.microsoft.teams2.helper",
"Microsoft Teams Helper",
Some("com.microsoft.teams2"),
false,
),
(
"com.tinyspeck.slackmacgap.helper",
"Slack Helper",
Some("com.tinyspeck.slackmacgap"),
false,
),
(
"com.brave.Browser.beta",
"Brave Browser Beta",
Some("com.brave.Browser"),
true,
),
(
"com.google.Chrome.canary",
"Google Chrome Canary",
Some("com.google.Chrome"),
true,
),
(
"org.mozilla.plugincontainer",
"plugin-container",
Some("org.mozilla.firefox"),
true,
),
(
"com.microsoft.edgemac.helper",
"Microsoft Edge Helper",
Some("com.microsoft.edgemac"),
true,
),
(
"company.thebrowser.Browser",
"Arc",
Some("company.thebrowser.Browser"),
true,
),
(
"company.thebrowser.browser.helper",
"Browser Helper",
Some("company.thebrowser.Browser"),
true,
),
("company.thebrowser.dia", "Dia", None, false),
(
"at.studio.AsideBrowser",
"Aside",
Some("at.studio.AsideBrowser"),
true,
),
(
"at.studio.AsideBrowser.helper",
"Aside Helper",
Some("at.studio.AsideBrowser"),
true,
),
("net.imput.helium", "Helium", Some("net.imput.helium"), true),
(
"net.imput.helium.helper",
"Helium Helper",
Some("net.imput.helium"),
true,
),
(
"net.imput.helium.helper.Renderer",
"Helium Helper (Renderer)",
Some("net.imput.helium"),
true,
),
(
"com.ardia.browser",
"Ardia",
Some("com.ardia.browser"),
true,
),
(
"com.ardia.browser.helper",
"Ardia Helper",
Some("com.ardia.browser"),
true,
),
(
"app.zen-browser.zen",
"Zen",
Some("app.zen-browser.zen"),
true,
),
(
"app.zen-browser.plugincontainer",
"plugin-container",
Some("app.zen-browser.zen"),
true,
),
(
"app.zen-browser.zen-gpu-helper",
"Zen GPU Helper",
Some("app.zen-browser.zen"),
true,
),
(
"app.zen-browser.zen-media-plugin-helper",
"Zen Media Plugin Helper",
Some("app.zen-browser.zen"),
true,
),
("anomaly.hex", "Hex", None, false),
("zoom", "Zoom", Some("us.zoom.xos"), false),
(
"ms-teams.exe",
"ms-teams",
Some("com.microsoft.teams2"),
false,
),
(
"Slack.exe",
"Slack",
Some("com.tinyspeck.slackmacgap"),
false,
),
("chrome", "Google Chrome", Some("com.google.Chrome"), true),
("firefox.exe", "Firefox", Some("org.mozilla.firefox"), true),
// Zen on Linux: the Flatpak and tarball launcher binary, then the
// tarball's real `zen-bin`; content processes run the same one.
("zen", "Zen", Some("app.zen-browser.zen"), true),
("zen-bin", "Zen", Some("app.zen-browser.zen"), true),
(
"msedge.exe",
"Microsoft Edge",
Some("com.microsoft.edgemac"),
true,
),
("vivaldi-bin", "Vivaldi", Some("com.vivaldi.Vivaldi"), true),
("vivaldi.exe", "Vivaldi", Some("com.vivaldi.Vivaldi"), true),
("helium", "Helium", Some("net.imput.helium"), true),
("helium-browser", "Helium", Some("net.imput.helium"), true),
("helium.exe", "Helium", Some("net.imput.helium"), true),
(
"com.vivaldi.Vivaldi.helper",
"Vivaldi Helper",
Some("com.vivaldi.Vivaldi"),
true,
),
("spotify", "Spotify", None, false),
] {
let app = ActiveMicrophoneApplication {
pid: 100,
bundle_id: bundle_id.into(),
name: name.into(),
};
assert_eq!(app.canonical_bundle_id(), expected, "bundle {bundle_id}");
assert_eq!(app.is_browser(), browser, "browser {bundle_id}");
}
// The names the pause and a browser call show for them.
assert_eq!(
canonical_application_name("com.ardia.browser"),
Some("Ardia")
);
assert_eq!(
canonical_application_name("app.zen-browser.zen"),
Some("Zen")
);
}
#[test]
fn more_call_app_bundle_variants_and_executables_canonicalize() {
for (bundle_id, expected) in [
(
"org.whispersystems.signal-desktop",
"org.whispersystems.signal-desktop",
),
(
"org.whispersystems.signal-desktop.helper.Renderer",
"org.whispersystems.signal-desktop",
),
("ru.keepcoder.Telegram", "ru.keepcoder.Telegram"),
("com.tdesktop.Telegram", "ru.keepcoder.Telegram"),
("com.tdesktop.Telegram.helper", "ru.keepcoder.Telegram"),
("org.telegram.desktop", "ru.keepcoder.Telegram"),
("com.tencent.xinWeChat", "com.tencent.xinWeChat"),
("jp.naver.line.mac", "jp.naver.line.mac"),
("com.webex.meetingmanager", "com.webex.meetingmanager"),
("com.cisco.webexmeetingsapp", "com.webex.meetingmanager"),
("Cisco-Systems.Spark", "com.webex.meetingmanager"),
("Cisco-Systems.Spark.helper", "com.webex.meetingmanager"),
("im.riot.app", "im.riot.app"),
("com.apple.mobilephone", "com.apple.mobilephone"),
("Signal.exe", "org.whispersystems.signal-desktop"),
("signal-desktop", "org.whispersystems.signal-desktop"),
("Telegram.exe", "ru.keepcoder.Telegram"),
("telegram-desktop", "ru.keepcoder.Telegram"),
("Element.exe", "im.riot.app"),
("element-desktop", "im.riot.app"),
("webex", "com.webex.meetingmanager"),
("CiscoCollabHost.exe", "com.webex.meetingmanager"),
("ciscocollabhost", "com.webex.meetingmanager"),
("WeChat.exe", "com.tencent.xinWeChat"),
("Weixin.exe", "com.tencent.xinWeChat"),
("LINE.exe", "jp.naver.line.mac"),
] {
assert_eq!(
canonical_bundle_id_for(bundle_id, None),
Some(expected),
"{bundle_id}"
);
}
assert_eq!(
canonical_application_name("ru.keepcoder.Telegram"),
Some("Telegram")
);
assert_eq!(
canonical_application_name("jp.naver.line.mac"),
Some("LINE")
);
let signal = ActiveMicrophoneApplication {
pid: 7,
bundle_id: "org.whispersystems.signal-desktop".into(),
name: "Signal".into(),
};
assert!(signal.is_supported_meeting_app());
let chrome = ActiveMicrophoneApplication {
pid: 8,
bundle_id: "com.google.Chrome".into(),
name: "Google Chrome".into(),
};
assert!(chrome.is_supported_meeting_app());
}
}