use crate::error::{AudioError, ErrorCode};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) enum MicStatus {
Granted,
NotDetermined,
Denied,
Restricted,
}
#[derive(Clone, Default)]
pub(crate) struct Reply(Arc<AtomicU8>);
impl Reply {
const YES: u8 = 1;
const NO: u8 = 2;
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn send(&self, granted: bool) {
let v = if granted { Self::YES } else { Self::NO };
self.0.store(v, Ordering::Release);
}
fn get(&self) -> Option<bool> {
match self.0.load(Ordering::Acquire) {
Self::YES => Some(true),
Self::NO => Some(false),
_ => None,
}
}
}
pub(crate) trait MicOs {
fn status(&self) -> MicStatus;
fn can_ask(&self) -> bool;
fn ask(&self, reply: Reply);
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Gate {
Open,
Waiting,
Refused(AudioError),
}
pub(crate) struct MicGate {
os: Box<dyn MicOs>,
reply: Reply,
asked: bool,
answer_seen: bool,
last: Option<MicStatus>,
}
fn refused(detail: &str) -> Gate {
Gate::Refused(AudioError::new(ErrorCode::NoPermission, detail))
}
impl MicGate {
pub(crate) fn new(os: Box<dyn MicOs>) -> MicGate {
MicGate {
os,
reply: Reply::default(),
asked: false,
answer_seen: false,
last: None,
}
}
pub(crate) fn check(&mut self) -> Gate {
let status = self.os.status();
self.last = Some(status);
match status {
MicStatus::Granted => Gate::Open,
MicStatus::Denied => {
refused("microphone access is turned off for this app in the system settings")
}
MicStatus::Restricted => {
refused("microphone access is restricted on this device by policy")
}
MicStatus::NotDetermined => match self.reply.get() {
Some(true) => Gate::Open,
Some(false) => refused("the person declined microphone access"),
None if self.asked => Gate::Waiting,
None if !self.os.can_ask() => refused(
"microphone access was never granted, and the app can't ask: \
its Info.plist has no NSMicrophoneUsageDescription",
),
None => {
self.asked = true;
self.os.ask(self.reply.clone());
Gate::Waiting
}
},
}
}
pub(crate) fn answered(&mut self) -> bool {
if self.asked && !self.answer_seen && self.reply.get().is_some() {
self.answer_seen = true;
return true;
}
false
}
pub(crate) fn status_changed(&self) -> bool {
self.last != Some(self.os.status())
}
}
pub(crate) fn system_os() -> Box<dyn MicOs> {
#[cfg(target_os = "macos")]
{
Box::new(macos::CaptureDeviceAuth)
}
#[cfg(not(target_os = "macos"))]
{
Box::new(NoCheck)
}
}
#[cfg(not(target_os = "macos"))]
struct NoCheck;
#[cfg(not(target_os = "macos"))]
impl MicOs for NoCheck {
fn status(&self) -> MicStatus {
MicStatus::Granted
}
fn can_ask(&self) -> bool {
false
}
fn ask(&self, _reply: Reply) {}
}
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
mod macos {
use super::{MicOs, MicStatus, Reply};
use block2::RcBlock;
use objc2::rc::autoreleasepool;
use objc2::runtime::{AnyObject, Bool};
use objc2::{class, msg_send};
#[link(name = "AVFoundation", kind = "framework")]
extern "C" {
static AVMediaTypeAudio: *const AnyObject;
}
fn from_raw(raw: isize) -> MicStatus {
match raw {
0 => MicStatus::NotDetermined,
1 => MicStatus::Restricted,
3 => MicStatus::Granted,
_ => MicStatus::Denied,
}
}
pub(super) struct CaptureDeviceAuth;
impl MicOs for CaptureDeviceAuth {
fn status(&self) -> MicStatus {
let raw: isize = unsafe {
msg_send![class!(AVCaptureDevice), authorizationStatusForMediaType: AVMediaTypeAudio]
};
from_raw(raw)
}
fn can_ask(&self) -> bool {
autoreleasepool(|_| {
unsafe {
let bundle: *mut AnyObject = msg_send![class!(NSBundle), mainBundle];
let key: *mut AnyObject = msg_send![
class!(NSString),
stringWithUTF8String: c"NSMicrophoneUsageDescription".as_ptr()
];
if bundle.is_null() || key.is_null() {
return false;
}
let value: *mut AnyObject = msg_send![bundle, objectForInfoDictionaryKey: key];
!value.is_null()
}
})
}
fn ask(&self, reply: Reply) {
let done = RcBlock::new(move |granted: Bool| reply.send(granted.as_bool()));
autoreleasepool(|_| {
unsafe {
let _: () = msg_send![
class!(AVCaptureDevice),
requestAccessForMediaType: AVMediaTypeAudio,
completionHandler: &*done
];
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
#[test]
fn raw_statuses() {
assert_eq!(from_raw(0), MicStatus::NotDetermined);
assert_eq!(from_raw(1), MicStatus::Restricted);
assert_eq!(from_raw(2), MicStatus::Denied);
assert_eq!(from_raw(3), MicStatus::Granted);
assert_eq!(from_raw(99), MicStatus::Denied);
}
#[test]
fn status_and_usage_check_run_without_a_prompt() {
let os = CaptureDeviceAuth;
eprintln!("[mic] status {:?}", os.status());
assert!(!os.can_ask(), "a test binary has no usage description");
}
#[test]
#[ignore = "needs the microphone refused for this process; starts the real output device"]
fn real_denied_mic_raises_no_permission() {
use crate::{
AudioEngine, DeviceChoice, DeviceSelection, EngineConfig, ErrorCode, Event,
};
assert_eq!(
CaptureDeviceAuth.status(),
MicStatus::Denied,
"refuse the microphone first"
);
let engine = AudioEngine::start(EngineConfig::default()).expect("start");
let events = engine.events();
let deadline = Instant::now() + Duration::from_secs(5);
let mut raised = false;
while !raised && Instant::now() < deadline {
if let Some(Event::Error(e)) = events.recv_timeout(Duration::from_millis(100)) {
eprintln!("[mic] event: {e}");
raised = e.code == ErrorCode::NoPermission;
}
}
assert!(raised, "no no_permission event in 5 s");
assert_eq!(engine.devices_in_use().input, None);
let sel = DeviceSelection {
input: Some(DeviceChoice::Default),
output: None,
};
let e = engine.set_device(sel).expect_err("the switch must fail");
assert_eq!(e.code, ErrorCode::NoPermission);
assert!(
engine.capture_frames().try_recv().is_none(),
"frames from a refused microphone"
);
}
#[test]
#[ignore = "shows the OS prompt; needs a usage description linked in"]
fn real_ask_returns_at_once_and_calls_back() {
let os = CaptureDeviceAuth;
assert!(
os.can_ask(),
"link an Info.plist with the usage description"
);
let reply = Reply::default();
let t = Instant::now();
os.ask(reply.clone());
assert!(
t.elapsed() < Duration::from_secs(2),
"ask blocked for {:?}",
t.elapsed()
);
let deadline = Instant::now() + Duration::from_secs(60);
while reply.get().is_none() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
eprintln!("[mic] answer {:?}, status {:?}", reply.get(), os.status());
assert!(reply.get().is_some(), "no answer in 60 s");
}
}
}
#[cfg(test)]
pub(crate) mod fake {
use super::*;
use std::sync::Mutex;
struct State {
status: MicStatus,
can_ask: bool,
asks: u32,
reply: Option<Reply>,
}
#[derive(Clone)]
pub(crate) struct FakeOs(Arc<Mutex<State>>);
impl FakeOs {
pub(crate) fn new(status: MicStatus) -> FakeOs {
FakeOs(Arc::new(Mutex::new(State {
status,
can_ask: true,
asks: 0,
reply: None,
})))
}
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.0.lock().expect("fake OS lock")
}
pub(crate) fn no_usage_description(self) -> FakeOs {
self.state().can_ask = false;
self
}
pub(crate) fn set_status(&self, s: MicStatus) {
self.state().status = s;
}
pub(crate) fn asks(&self) -> u32 {
self.state().asks
}
pub(crate) fn answer(&self, granted: bool) {
let mut g = self.state();
g.status = if granted {
MicStatus::Granted
} else {
MicStatus::Denied
};
g.reply.as_ref().expect("nobody asked").send(granted);
}
}
impl MicOs for FakeOs {
fn status(&self) -> MicStatus {
self.state().status
}
fn can_ask(&self) -> bool {
self.state().can_ask
}
fn ask(&self, reply: Reply) {
let mut g = self.state();
g.asks += 1;
g.reply = Some(reply);
}
}
}
#[cfg(test)]
mod tests {
use super::fake::FakeOs;
use super::*;
fn gate(os: &FakeOs) -> MicGate {
MicGate::new(Box::new(os.clone()))
}
fn assert_refused(g: Gate) {
match g {
Gate::Refused(e) => {
assert_eq!(e.code, ErrorCode::NoPermission);
assert_eq!(e.code.as_str(), "no_permission");
}
other => panic!("expected a refusal, got {other:?}"),
}
}
#[test]
fn granted_opens_without_asking() {
let os = FakeOs::new(MicStatus::Granted);
assert_eq!(gate(&os).check(), Gate::Open);
assert_eq!(os.asks(), 0);
}
#[test]
fn denied_and_restricted_refuse_without_asking() {
for status in [MicStatus::Denied, MicStatus::Restricted] {
let os = FakeOs::new(status);
assert_refused(gate(&os).check());
assert_eq!(os.asks(), 0, "{status:?}");
}
}
#[test]
fn not_determined_asks_once_and_waits() {
let os = FakeOs::new(MicStatus::NotDetermined);
let mut g = gate(&os);
assert_eq!(g.check(), Gate::Waiting);
assert_eq!(g.check(), Gate::Waiting);
assert_eq!(os.asks(), 1, "a second check must not ask again");
assert!(!g.answered());
}
#[test]
fn a_yes_opens_and_is_reported_once() {
let os = FakeOs::new(MicStatus::NotDetermined);
let mut g = gate(&os);
g.check();
os.answer(true);
assert!(g.answered());
assert!(!g.answered(), "the answer is reported once");
assert_eq!(g.check(), Gate::Open);
}
#[test]
fn a_no_refuses_and_is_never_asked_again() {
let os = FakeOs::new(MicStatus::NotDetermined);
let mut g = gate(&os);
g.check();
os.answer(false);
assert!(g.answered());
assert_refused(g.check());
assert_eq!(os.asks(), 1);
}
#[test]
fn the_answer_decides_while_the_status_lags() {
for (granted, opens) in [(true, true), (false, false)] {
let os = FakeOs::new(MicStatus::NotDetermined);
let mut g = gate(&os);
g.check();
os.answer(granted);
os.set_status(MicStatus::NotDetermined);
match g.check() {
Gate::Open => assert!(opens),
other => {
assert!(!opens, "{other:?}");
assert_refused(other);
}
}
assert_eq!(os.asks(), 1);
}
}
#[test]
fn without_a_usage_description_it_refuses_instead_of_asking() {
let os = FakeOs::new(MicStatus::NotDetermined).no_usage_description();
let mut g = gate(&os);
match g.check() {
Gate::Refused(e) => assert!(e.detail.contains("NSMicrophoneUsageDescription"), "{e}"),
other => panic!("{other:?}"),
}
assert_eq!(os.asks(), 0, "asking without one kills the app on macOS");
}
#[test]
fn status_changes_are_noticed() {
let os = FakeOs::new(MicStatus::Denied);
let mut g = gate(&os);
assert!(g.status_changed(), "nothing checked yet");
assert_refused(g.check());
assert!(!g.status_changed());
os.set_status(MicStatus::Granted);
assert!(g.status_changed());
assert_eq!(g.check(), Gate::Open);
assert!(!g.status_changed());
}
#[test]
fn no_answer_means_nothing_to_report() {
let os = FakeOs::new(MicStatus::Granted);
let mut g = gate(&os);
g.check();
assert!(!g.answered());
}
}