//! Which microphone Mac captures record from: `"microphone": {"id", "name"}` in
//! `~/.config/scrawl/config.json` (absent = the macOS default, followed as it changes). The id is
//! the CoreAudio device UID, which is also `AVCaptureDevice.uniqueID`; the name is kept only to
//! say which device is missing. A chosen device that isn't connected falls back to the default.
use serde::{Deserialize, Serialize};
/// The `microphone` key: a device the user picked in Settings.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Choice {
pub id: String,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Input {
pub id: String,
pub name: String,
}
/// The input devices connected now, in CoreAudio's order, and the default's id.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Inputs {
pub devices: Vec,
pub default: Option,
}
impl Inputs {
pub fn find(&self, id: &str) -> Option<&Input> {
self.devices.iter().find(|d| d.id == id)
}
pub fn default_input(&self) -> Option<&Input> {
self.default.as_deref().and_then(|id| self.find(id))
}
}
/// What a recording uses, given the choice and what's connected.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Pick<'a> {
/// No choice: the macOS default (none when there's no microphone at all).
Default(Option<&'a Input>),
Chosen(&'a Input),
/// The chosen device isn't connected; the default stands in.
Missing {
wanted: &'a Choice,
using: Option<&'a Input>,
},
}
impl<'a> Pick<'a> {
pub fn new(choice: Option<&'a Choice>, inputs: &'a Inputs) -> Self {
match choice {
None => Pick::Default(inputs.default_input()),
Some(wanted) => match inputs.find(&wanted.id) {
Some(input) => Pick::Chosen(input),
None => Pick::Missing {
wanted,
using: inputs.default_input(),
},
},
}
}
/// The device that will record.
pub fn device(&self) -> Option<&'a Input> {
match *self {
Pick::Default(input) | Pick::Missing { using: input, .. } => input,
Pick::Chosen(input) => Some(input),
}
}
/// "AirPods Pro isn't connected. Using MacBook Pro Microphone." for a missing device.
pub fn note(&self) -> Option {
let Pick::Missing { wanted, using } = self else {
return None;
};
Some(match using {
Some(using) => format!("{} isn't connected. Using {}.", wanted.name, using.name),
None => format!(
"{} isn't connected, and there's no other microphone.",
wanted.name
),
})
}
}
/// The configured choice, if any.
pub fn choice() -> Option {
choice_in(&crate::handoff::default_config_path())
}
pub fn choice_in(path: &std::path::Path) -> Option {
crate::handoff::load_config_from(path)
.microphone
.filter(|c| !c.id.trim().is_empty())
}
/// Saves a pick from Settings: `"default"` clears the key; an id that isn't connected (so it
/// can't be named) changes nothing.
pub fn save_in(path: &std::path::Path, id: &str, inputs: &Inputs) -> anyhow::Result<()> {
let value = if id == "default" {
serde_json::Value::Null
} else if let Some(input) = inputs.find(id) {
serde_json::to_value(Choice {
id: input.id.clone(),
name: input.name.clone(),
})?
} else {
return Ok(());
};
crate::handoff::set_config_value_in(path, "microphone", value)
}
/// Enumerates input devices (CoreAudio, a few ms; never on the UI thread).
#[cfg(feature = "mic")]
pub fn inputs() -> Inputs {
use cpal::traits::{DeviceTrait, HostTrait};
let host = cpal::default_host();
let devices = host
.input_devices()
.map(|devices| {
devices
.filter_map(|device| {
let id = device.id().ok()?.id().to_owned();
let name = device.description().ok()?.name().to_owned();
Some(Input { id, name })
})
.collect()
})
.unwrap_or_default();
let default = host
.default_input_device()
.and_then(|device| device.id().ok())
.map(|id| id.id().to_owned());
Inputs { devices, default }
}
#[cfg(not(feature = "mic"))]
pub fn inputs() -> Inputs {
Inputs::default()
}
/// The cpal device for `id`, if connected.
#[cfg(feature = "mic")]
pub fn device(id: &str) -> Option {
use cpal::traits::{DeviceTrait, HostTrait};
cpal::default_host()
.input_devices()
.ok()?
.find(|device| device.id().is_ok_and(|d| d.id() == id))
}
/// Logs a missing chosen device once, until it's back or another goes missing.
pub fn note_pick(pick: &Pick) {
static WARNED: std::sync::Mutex