diff --git a/crates/core/src/detect.rs b/crates/core/src/detect.rs new file mode 100644 index 0000000..253db9a --- /dev/null +++ b/crates/core/src/detect.rs @@ -0,0 +1,698 @@ +//! Call detector state machine. +//! +//! Pure and clockless: [`CallDetector::tick`] is driven by whatever polls the +//! current microphone-holding processes (on Windows, session enumeration — +//! see Task 10) and the caller's own clock. The detector itself never reads +//! the clock, spawns threads or touches I/O, which keeps it unit-testable +//! with a synthetic [`Instant`]. +//! +//! States: `Idle` (nothing happening) -> `Pending` (an allowlisted exe is +//! active, waiting out the continuous hold) -> `InCall` (the hold elapsed; +//! bound to that exe until it has been released for the end window) -> +//! back to `Idle`. `Suppressed` is a parallel state entered via +//! [`CallDetector::manual_stop`] that blocks re-detection of one exe until +//! it next has no active session. + +use std::time::{Duration, Instant}; + +/// One process currently (or not) holding the microphone, as reported by +/// the platform-specific session enumeration. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MicSession { + pub exe: String, + pub pid: u32, + pub root_pid: u32, + pub active: bool, +} + +/// Static configuration the detector is driven by. Replaceable at runtime +/// via [`CallDetector::set_config`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DetectorConfig { + pub allowlist: Vec, + pub own_pid: u32, + pub start_after: Duration, + pub end_after: Duration, +} + +/// Emitted by [`CallDetector::tick`] at most once per call transition. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DetectorEvent { + CallStarted { + exe: String, + app: String, + root_pid: u32, + }, + CallEnded, +} + +#[derive(Debug, Clone)] +enum State { + Idle, + Pending { + exe: String, + since: Instant, + }, + InCall { + exe: String, + released_since: Option, + }, + Suppressed { + exe: String, + }, +} + +/// Strips any directory part, returning just the file name. +fn basename(name: &str) -> &str { + name.rsplit(['/', '\\']).next().unwrap_or(name) +} + +/// Case- and path-insensitive comparison key for an exe name. +fn exe_key(name: &str) -> String { + basename(name).to_ascii_lowercase() +} + +/// Human-readable name shown in the UI for a detected call. +pub fn display_name(exe: &str) -> String { + match exe_key(exe).as_str() { + "ms-teams.exe" | "teams.exe" => "Microsoft Teams".to_string(), + "microsip.exe" => "MicroSIP".to_string(), + "msedge.exe" => "Edge".to_string(), + "chrome.exe" => "Chrome".to_string(), + "firefox.exe" => "Firefox".to_string(), + other => { + // `other` is the lowercased form of `exe`'s basename and has the + // same byte length (ASCII case folding only), so slicing `exe` + // by its length is safe and preserves the original casing. + let base = basename(exe); + if other.ends_with(".exe") { + base[..base.len() - 4].to_string() + } else { + base.to_string() + } + } + } +} + +/// Pure call-start/call-end detector driven by periodic [`MicSession`] +/// snapshots. See the module docs for the state diagram. +pub struct CallDetector { + cfg: DetectorConfig, + state: State, + last_sessions: Vec, + emit_ended_next_tick: bool, +} + +impl CallDetector { + pub fn new(cfg: DetectorConfig) -> Self { + Self { + cfg, + state: State::Idle, + last_sessions: Vec::new(), + emit_ended_next_tick: false, + } + } + + /// True if `exe` is on the (case-/path-insensitive) allowlist. + fn is_allowlisted(&self, exe: &str) -> bool { + let key = exe_key(exe); + self.cfg.allowlist.iter().any(|a| exe_key(a) == key) + } + + /// True if `session` belongs to this app's own process. + fn is_own(&self, session: &MicSession) -> bool { + session.pid == self.cfg.own_pid || session.root_pid == self.cfg.own_pid + } + + /// Active, allowlisted, non-own sessions from a snapshot. + fn relevant<'a>(&self, sessions: &'a [MicSession]) -> Vec<&'a MicSession> { + sessions + .iter() + .filter(|s| s.active && !self.is_own(s) && self.is_allowlisted(&s.exe)) + .collect() + } + + /// Picks the detection candidate: lowest pid among relevant sessions, + /// for determinism when several allowlisted exes are active at once. + fn pick_candidate(relevant: &[&MicSession]) -> Option { + relevant + .iter() + .min_by_key(|s| s.pid) + .map(|s| basename(&s.exe).to_string()) + } + + /// True if any relevant session matches `exe` (case-/path-insensitive). + fn has_exe(relevant: &[&MicSession], exe: &str) -> bool { + let key = exe_key(exe); + relevant.iter().any(|s| exe_key(&s.exe) == key) + } + + /// `root_pid` of the lowest-pid relevant session matching `exe`. + fn root_pid_for(relevant: &[&MicSession], exe: &str) -> u32 { + let key = exe_key(exe); + relevant + .iter() + .filter(|s| exe_key(&s.exe) == key) + .min_by_key(|s| s.pid) + .map(|s| s.root_pid) + .unwrap_or_default() + } + + /// Advances the state machine by one poll. `now` is the only time + /// source; the detector keeps no clock of its own. + pub fn tick(&mut self, now: Instant, sessions: &[MicSession]) -> Option { + self.last_sessions = sessions.to_vec(); + + if self.emit_ended_next_tick { + self.emit_ended_next_tick = false; + return Some(DetectorEvent::CallEnded); + } + + let relevant = self.relevant(sessions); + + match std::mem::replace(&mut self.state, State::Idle) { + State::Idle => { + self.state = match Self::pick_candidate(&relevant) { + Some(exe) => State::Pending { exe, since: now }, + None => State::Idle, + }; + None + } + State::Pending { exe, since } => { + if Self::has_exe(&relevant, &exe) { + if now.duration_since(since) >= self.cfg.start_after { + let root_pid = Self::root_pid_for(&relevant, &exe); + let event = DetectorEvent::CallStarted { + exe: exe.clone(), + app: display_name(&exe), + root_pid, + }; + self.state = State::InCall { + exe, + released_since: None, + }; + Some(event) + } else { + self.state = State::Pending { exe, since }; + None + } + } else { + self.state = State::Idle; + None + } + } + State::InCall { + exe, + released_since, + } => { + if Self::has_exe(&relevant, &exe) { + self.state = State::InCall { + exe, + released_since: None, + }; + None + } else { + let released_since = released_since.unwrap_or(now); + if now.duration_since(released_since) >= self.cfg.end_after { + self.state = State::Idle; + Some(DetectorEvent::CallEnded) + } else { + self.state = State::InCall { + exe, + released_since: Some(released_since), + }; + None + } + } + } + State::Suppressed { exe } => { + self.state = if Self::has_exe(&relevant, &exe) { + State::Suppressed { exe } + } else { + State::Idle + }; + None + } + } + } + + /// Ends the current call (if any) and suppresses re-detection of the + /// exe involved until a tick sees it with no active session. The + /// caller is responsible for actually stopping the recording; this + /// only updates the detector's state and returns nothing. + pub fn manual_stop(&mut self) { + let suppress_exe = match &self.state { + State::InCall { exe, .. } | State::Pending { exe, .. } => Some(exe.clone()), + State::Idle => { + let relevant = self.relevant(&self.last_sessions); + Self::pick_candidate(&relevant) + } + State::Suppressed { .. } => None, + }; + if let Some(exe) = suppress_exe { + self.state = State::Suppressed { exe }; + } + } + + /// Replaces the configuration without resetting state, except that a + /// bound (`InCall`) or pending exe that is no longer allowlisted drops + /// the detector back to `Idle`. If that exe was an active call, the + /// `CallEnded` event is deferred to (and returned from) the next tick. + pub fn set_config(&mut self, cfg: DetectorConfig) { + self.cfg = cfg; + let dropped = match &self.state { + State::InCall { exe, .. } => Some((exe.clone(), true)), + State::Pending { exe, .. } => Some((exe.clone(), false)), + _ => None, + }; + if let Some((exe, was_in_call)) = dropped { + if !self.is_allowlisted(&exe) { + self.state = State::Idle; + if was_in_call { + self.emit_ended_next_tick = true; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg() -> DetectorConfig { + DetectorConfig { + allowlist: vec![ + "ms-teams.exe".into(), + "teams.exe".into(), + "microsip.exe".into(), + "msedge.exe".into(), + "chrome.exe".into(), + "firefox.exe".into(), + ], + own_pid: 9_999, + start_after: Duration::from_secs(3), + end_after: Duration::from_secs(10), + } + } + + fn session(exe: &str, pid: u32, root_pid: u32, active: bool) -> MicSession { + MicSession { + exe: exe.to_string(), + pid, + root_pid, + active, + } + } + + #[test] + fn starts_only_after_continuous_hold() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let teams = session("teams.exe", 100, 100, true); + + for ms in [0, 1_000, 2_000, 2_900] { + assert_eq!( + d.tick( + base + Duration::from_millis(ms), + std::slice::from_ref(&teams) + ), + None, + "t={ms}ms" + ); + } + assert_eq!( + d.tick(base + Duration::from_secs(3), &[teams]), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + } + + #[test] + fn short_use_never_starts() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let active = session("teams.exe", 100, 100, true); + let released = session("teams.exe", 100, 100, false); + + assert_eq!(d.tick(base, std::slice::from_ref(&active)), None); + assert_eq!(d.tick(base + Duration::from_millis(2_500), &[active]), None); + assert_eq!( + d.tick( + base + Duration::from_millis(2_600), + std::slice::from_ref(&released) + ), + None + ); + assert_eq!(d.tick(base + Duration::from_secs(10), &[released]), None); + } + + #[test] + fn ends_after_release_window() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let active = session("teams.exe", 100, 100, true); + let released = session("teams.exe", 100, 100, false); + + d.tick(base, std::slice::from_ref(&active)); + assert_eq!( + d.tick(base + Duration::from_secs(3), &[active]), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + // released at t=60 + assert_eq!( + d.tick( + base + Duration::from_secs(60), + std::slice::from_ref(&released) + ), + None + ); + assert_eq!( + d.tick( + base + Duration::from_millis(69_900), + std::slice::from_ref(&released) + ), + None + ); + assert_eq!( + d.tick(base + Duration::from_secs(70), &[released]), + Some(DetectorEvent::CallEnded) + ); + } + + #[test] + fn reacquire_within_window_keeps_call() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let active = session("teams.exe", 100, 100, true); + let released = session("teams.exe", 100, 100, false); + + d.tick(base, std::slice::from_ref(&active)); + assert_eq!( + d.tick(base + Duration::from_secs(3), std::slice::from_ref(&active)), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + // released right after the call starts + assert_eq!( + d.tick( + base + Duration::from_secs(4), + std::slice::from_ref(&released) + ), + None + ); + // 8s after release (t=4): well within the 10s end_after window + assert_eq!( + d.tick( + base + Duration::from_secs(12), + std::slice::from_ref(&released) + ), + None + ); + // reacquired before the window would have expired (t=14) + assert_eq!(d.tick(base + Duration::from_secs(13), &[active]), None); + // released again; a fresh 10s window starts from t=14 + assert_eq!( + d.tick( + base + Duration::from_secs(14), + std::slice::from_ref(&released) + ), + None + ); + assert_eq!( + d.tick( + base + Duration::from_secs(22), + std::slice::from_ref(&released) + ), + None + ); + assert_eq!( + d.tick(base + Duration::from_secs(24), &[released]), + Some(DetectorEvent::CallEnded) + ); + } + + #[test] + fn ignores_non_allowlisted_and_own_pid() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let other = session("spotify.exe", 50, 50, true); + let own_direct = session("teams.exe", 9_999, 9_999, true); + let own_child = session("teams.exe", 500, 9_999, true); + + for t in 0..6 { + assert_eq!( + d.tick( + base + Duration::from_secs(t), + &[other.clone(), own_direct.clone(), own_child.clone()] + ), + None, + "t={t}" + ); + } + } + + #[test] + fn exe_match_is_case_insensitive() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let teams = session("MS-Teams.EXE", 100, 100, true); + + assert_eq!(d.tick(base, std::slice::from_ref(&teams)), None); + assert_eq!( + d.tick(base + Duration::from_secs(3), &[teams]), + Some(DetectorEvent::CallStarted { + exe: "MS-Teams.EXE".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + } + + #[test] + fn call_bound_to_starting_app() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let teams = session("teams.exe", 100, 100, true); + let teams_released = session("teams.exe", 100, 100, false); + let chrome = session("chrome.exe", 200, 200, true); + + d.tick(base, std::slice::from_ref(&teams)); + assert_eq!( + d.tick(base + Duration::from_secs(3), std::slice::from_ref(&teams)), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + // Chrome also grabs the mic: ignored, call stays bound to Teams. + assert_eq!( + d.tick( + base + Duration::from_secs(5), + &[teams.clone(), chrome.clone()] + ), + None + ); + // Teams released, Chrome still active. + assert_eq!( + d.tick( + base + Duration::from_secs(6), + &[teams_released.clone(), chrome.clone()] + ), + None + ); + assert_eq!( + d.tick( + base + Duration::from_secs(15), + &[teams_released.clone(), chrome.clone()] + ), + None + ); + assert_eq!( + d.tick( + base + Duration::from_secs(16), + &[teams_released, chrome.clone()] + ), + Some(DetectorEvent::CallEnded) + ); + // Chrome starts its own hold from here. + assert_eq!( + d.tick( + base + Duration::from_secs(17), + std::slice::from_ref(&chrome) + ), + None + ); + assert_eq!( + d.tick( + base + Duration::from_secs(19), + std::slice::from_ref(&chrome) + ), + None + ); + assert_eq!( + d.tick(base + Duration::from_secs(20), &[chrome]), + Some(DetectorEvent::CallStarted { + exe: "chrome.exe".into(), + app: "Chrome".into(), + root_pid: 200, + }) + ); + } + + #[test] + fn manual_stop_suppresses_until_release() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let teams = session("teams.exe", 100, 100, true); + let released = session("teams.exe", 100, 100, false); + + d.tick(base, std::slice::from_ref(&teams)); + d.tick(base + Duration::from_secs(3), std::slice::from_ref(&teams)); + d.manual_stop(); + + for t in (4..64).step_by(5) { + assert_eq!( + d.tick(base + Duration::from_secs(t), std::slice::from_ref(&teams)), + None, + "t={t}" + ); + } + // release clears the suppression + assert_eq!(d.tick(base + Duration::from_secs(64), &[released]), None); + // a fresh 3s hold is required before it fires again + assert_eq!( + d.tick(base + Duration::from_secs(65), std::slice::from_ref(&teams)), + None + ); + assert_eq!( + d.tick(base + Duration::from_secs(68), &[teams]), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + } + + #[test] + fn manual_stop_from_idle_with_active_exe_suppresses() { + let base = Instant::now(); + let mut not_yet_allowed = cfg(); + not_yet_allowed.allowlist = vec!["chrome.exe".into()]; + let mut d = CallDetector::new(not_yet_allowed); + let teams = session("teams.exe", 100, 100, true); + let released = session("teams.exe", 100, 100, false); + + // Teams isn't allowlisted yet: stays Idle, but last_sessions records it. + assert_eq!(d.tick(base, std::slice::from_ref(&teams)), None); + + // Now Teams becomes allowlisted (e.g. the user changes settings). + d.set_config(cfg()); + + // A manual recording of Teams is stopped while the detector is + // still Idle: it must suppress Teams based on the last snapshot. + d.manual_stop(); + assert_eq!( + d.tick(base + Duration::from_secs(1), std::slice::from_ref(&teams)), + None + ); + assert_eq!(d.tick(base + Duration::from_secs(2), &[released]), None); + assert_eq!( + d.tick(base + Duration::from_secs(3), std::slice::from_ref(&teams)), + None + ); + assert_eq!( + d.tick(base + Duration::from_secs(6), &[teams]), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + } + + #[test] + fn set_config_drops_in_call_and_ends_on_next_tick() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let teams = session("teams.exe", 100, 100, true); + + d.tick(base, std::slice::from_ref(&teams)); + assert_eq!( + d.tick(base + Duration::from_secs(3), std::slice::from_ref(&teams)), + Some(DetectorEvent::CallStarted { + exe: "teams.exe".into(), + app: "Microsoft Teams".into(), + root_pid: 100, + }) + ); + + let mut without_teams = cfg(); + without_teams.allowlist.retain(|e| e != "teams.exe"); + d.set_config(without_teams); + + // CallEnded is deferred to (and fires on) the very next tick. + assert_eq!( + d.tick(base + Duration::from_secs(4), std::slice::from_ref(&teams)), + Some(DetectorEvent::CallEnded) + ); + // Teams is no longer allowlisted, so it doesn't restart detection. + assert_eq!(d.tick(base + Duration::from_secs(5), &[teams]), None); + } + + #[test] + fn set_config_drops_pending_without_call_ended() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let teams = session("teams.exe", 100, 100, true); + + d.tick(base, std::slice::from_ref(&teams)); // Pending, no call started yet + + let mut without_teams = cfg(); + without_teams.allowlist.retain(|e| e != "teams.exe"); + d.set_config(without_teams); + + assert_eq!(d.tick(base + Duration::from_secs(1), &[teams]), None); + } + + #[test] + fn browser_child_pid_uses_root_pid() { + let base = Instant::now(); + let mut d = CallDetector::new(cfg()); + let s = session("chrome.exe", 200, 100, true); + + d.tick(base, std::slice::from_ref(&s)); + assert_eq!( + d.tick(base + Duration::from_secs(3), &[s]), + Some(DetectorEvent::CallStarted { + exe: "chrome.exe".into(), + app: "Chrome".into(), + root_pid: 100, + }) + ); + } + + #[test] + fn display_name_known_and_unknown_exes() { + assert_eq!(display_name("ms-teams.exe"), "Microsoft Teams"); + assert_eq!(display_name("Teams.EXE"), "Microsoft Teams"); + assert_eq!(display_name("microsip.exe"), "MicroSIP"); + assert_eq!(display_name("msedge.exe"), "Edge"); + assert_eq!(display_name("chrome.exe"), "Chrome"); + assert_eq!(display_name("firefox.exe"), "Firefox"); + assert_eq!(display_name("Slack.exe"), "Slack"); + assert_eq!(display_name("myapp"), "myapp"); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 9b42210..7b94fe0 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -6,6 +6,7 @@ pub mod audio; pub mod capture; +pub mod detect; pub mod model; pub mod recorder; pub mod retention;