Skip to main content

meeting_record/
lib.rs

1//! System-audio and microphone capture with meeting detection for macOS,
2//! Windows, and Linux.
3//!
4//! ```no_run
5//! use meeting_record::{meetings, Error, MeetingEvent, Platform};
6//!
7//! # fn main() -> Result<(), Error> {
8//! let watcher = meetings::watch(|event, meeting| {
9//!     if event == MeetingEvent::Started && meeting.should_record {
10//!         // `platform` is a stable identifier, not a label: match on it.
11//!         match meeting.platform {
12//!             Platform::Zoom | Platform::Teams => { /* ... */ }
13//!             _ => {}
14//!         }
15//!     }
16//! })?;
17//! # Ok(())
18//! # }
19//! ```
20//!
21//! Capture and watching are process-wide singletons. Both return a guard that
22//! stops them on drop.
23
24mod mixed_audio;
25mod mixer;
26mod sys;
27
28pub use mixed_audio::{MixedAudio, MixedAudioChunk, MixedAudioOptions};
29
30use std::{
31    cell::UnsafeCell,
32    collections::VecDeque,
33    error::Error as StdError,
34    ffi::{c_char, c_int, c_void, CStr},
35    fmt::{Display, Formatter, Result as FmtResult},
36    mem,
37    panic::{self, AssertUnwindSafe},
38    ptr, slice,
39    sync::{
40        atomic::{AtomicBool, AtomicUsize, Ordering},
41        Arc, Condvar, Mutex, OnceLock, Weak,
42    },
43    thread,
44    time::Duration,
45};
46
47use sys::{AudioCallback as RawAudioCallback, Meeting as RawMeeting, Process as RawProcess};
48
49/// Failure from a permission, detection, or capture operation.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum Error {
52    /// The current OS version does not support the requested operation.
53    UnsupportedOs,
54    /// Required system-audio or microphone access has not been granted.
55    Permission(String),
56    /// A process-wide recording or watcher is already active.
57    AlreadyRunning,
58    /// Capture options, the target process, or an audio device are unavailable or invalid.
59    Capture(String),
60    /// Native initialization or another internal operation failed.
61    Internal(String),
62    /// Capture startup or a permission wait was cancelled.
63    Cancelled,
64}
65
66impl Display for Error {
67    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
68        match self {
69            Error::UnsupportedOs => f.write_str("unsupported OS version"),
70            Error::Permission(message) => write!(f, "permission not granted: {message}"),
71            Error::AlreadyRunning => f.write_str("already running"),
72            Error::Capture(message) => write!(f, "capture failed: {message}"),
73            Error::Internal(message) => write!(f, "internal error: {message}"),
74            Error::Cancelled => f.write_str("operation cancelled"),
75        }
76    }
77}
78
79impl StdError for Error {}
80
81fn last_error() -> String {
82    unsafe {
83        let ptr = sys::mrec_last_error();
84        if ptr.is_null() {
85            String::new()
86        } else {
87            CStr::from_ptr(ptr).to_string_lossy().into_owned()
88        }
89    }
90}
91
92fn check(status: i32) -> Result<(), Error> {
93    match status {
94        sys::MREC_OK => Ok(()),
95        sys::MREC_ERR_UNSUPPORTED_OS => Err(Error::UnsupportedOs),
96        sys::MREC_ERR_PERMISSION => Err(Error::Permission(error_detail(status))),
97        sys::MREC_ERR_ALREADY_RUNNING => Err(Error::AlreadyRunning),
98        sys::MREC_ERR_NOT_RUNNING
99        | sys::MREC_ERR_NO_PROCESSES
100        | sys::MREC_ERR_TAP_FAILED
101        | sys::MREC_ERR_DEVICE_FAILED
102        | sys::MREC_ERR_IOPROC_FAILED => Err(Error::Capture(error_detail(status))),
103        _ => Err(Error::Internal(error_detail(status))),
104    }
105}
106
107fn error_detail(status: i32) -> String {
108    let detail = last_error();
109    if detail.is_empty() || detail == "no error" {
110        default_error_message(status).to_owned()
111    } else {
112        detail
113    }
114}
115
116fn default_error_message(status: i32) -> &'static str {
117    match status {
118        sys::MREC_ERR_UNSUPPORTED_OS => "unsupported OS version",
119        sys::MREC_ERR_PERMISSION => "permission not granted",
120        sys::MREC_ERR_ALREADY_RUNNING => "already running",
121        sys::MREC_ERR_NOT_RUNNING => "not running",
122        sys::MREC_ERR_NO_PROCESSES => "no process to capture",
123        sys::MREC_ERR_TAP_FAILED => "audio tap failed",
124        sys::MREC_ERR_DEVICE_FAILED => "audio device failed",
125        sys::MREC_ERR_IOPROC_FAILED => "audio callback failed",
126        _ => "meeting-record failed",
127    }
128}
129
130fn c_string(bytes: &[c_char]) -> String {
131    unsafe {
132        CStr::from_ptr(bytes.as_ptr())
133            .to_string_lossy()
134            .into_owned()
135    }
136}
137
138/// Shared cancellation for capture and permission waits. Cancellation is permanent.
139#[derive(Clone, Default)]
140pub struct CancellationToken {
141    inner: Arc<CancellationState>,
142}
143
144#[derive(Default)]
145struct CancellationState {
146    data: Mutex<CancellationData>,
147    wake: Condvar,
148}
149
150#[derive(Default)]
151struct CancellationData {
152    cancelled: bool,
153    capture: Weak<CaptureControl>,
154}
155
156impl std::fmt::Debug for CancellationToken {
157    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
158        formatter
159            .debug_struct("CancellationToken")
160            .field("cancelled", &self.is_cancelled())
161            .finish()
162    }
163}
164
165impl CancellationToken {
166    /// Create an uncancelled token. Clones share its cancellation state.
167    pub fn new() -> Self {
168        Self::default()
169    }
170
171    /// Cancel waiting operations and stop the associated recording.
172    /// Repeated calls are harmless.
173    pub fn cancel(&self) {
174        let capture = {
175            let mut data = self
176                .inner
177                .data
178                .lock()
179                .unwrap_or_else(|error| error.into_inner());
180            data.cancelled = true;
181            self.inner.wake.notify_all();
182            mem::take(&mut data.capture).upgrade()
183        };
184        if let Some(capture) = capture {
185            capture.stop();
186        }
187    }
188
189    /// Whether cancellation has been requested through this token or a clone.
190    pub fn is_cancelled(&self) -> bool {
191        self.inner
192            .data
193            .lock()
194            .unwrap_or_else(|error| error.into_inner())
195            .cancelled
196    }
197
198    fn check(&self) -> Result<(), Error> {
199        if self.is_cancelled() {
200            Err(Error::Cancelled)
201        } else {
202            Ok(())
203        }
204    }
205
206    fn register(&self, capture: &Arc<CaptureControl>) -> Result<(), Error> {
207        let mut data = self
208            .inner
209            .data
210            .lock()
211            .unwrap_or_else(|error| error.into_inner());
212        if data.cancelled {
213            return Err(Error::Cancelled);
214        }
215        data.capture = Arc::downgrade(capture);
216        Ok(())
217    }
218
219    fn wait(&self, timeout: Duration) -> Result<(), Error> {
220        let data = self
221            .inner
222            .data
223            .lock()
224            .unwrap_or_else(|error| error.into_inner());
225        let (data, _) = self
226            .inner
227            .wake
228            .wait_timeout_while(data, timeout, |data| !data.cancelled)
229            .unwrap_or_else(|error| error.into_inner());
230        if data.cancelled {
231            Err(Error::Cancelled)
232        } else {
233            Ok(())
234        }
235    }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum Permission {
240    SystemAudio,
241    Microphone,
242    Accessibility,
243}
244
245/// Windows has no prompts: system audio and accessibility are always granted,
246/// and the microphone follows its privacy settings.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub enum PermissionStatus {
249    Unknown,
250    Granted,
251    Denied,
252}
253
254impl From<i32> for PermissionStatus {
255    fn from(value: i32) -> Self {
256        match value {
257            1 => PermissionStatus::Granted,
258            2 => PermissionStatus::Denied,
259            _ => PermissionStatus::Unknown,
260        }
261    }
262}
263
264pub mod permissions {
265    use std::{
266        thread,
267        time::{Duration, Instant},
268    };
269
270    use super::{sys, CancellationToken, Error, Permission, PermissionStatus};
271
272    /// Check the current permission without prompting.
273    pub fn status(permission: Permission) -> PermissionStatus {
274        match permission {
275            Permission::SystemAudio => unsafe { sys::mrec_audio_permission_status() }.into(),
276            Permission::Microphone => unsafe { sys::mrec_microphone_permission_status() }.into(),
277            Permission::Accessibility => {
278                unsafe { sys::mrec_accessibility_permission_status() }.into()
279            }
280        }
281    }
282
283    /// Show the system prompt for a permission.
284    ///
285    /// Audio requests return immediately; poll [`status`] for the answer.
286    /// Accessibility opens System Settings and takes effect after an app
287    /// relaunch.
288    ///
289    /// # Errors
290    /// Returns a platform or permission error if the OS request cannot be started.
291    pub fn request(permission: Permission) -> Result<(), Error> {
292        let status = match permission {
293            Permission::SystemAudio => unsafe { sys::mrec_request_audio_permission() },
294            Permission::Microphone => unsafe { sys::mrec_request_microphone_permission() },
295            Permission::Accessibility => unsafe { sys::mrec_request_accessibility_permission() },
296        };
297        super::check(status)
298    }
299
300    /// Request and wait for the answer, returning the current status on timeout.
301    /// Accessibility returns immediately; its grant requires an app relaunch.
302    ///
303    /// # Errors
304    /// Returns [`Error::Cancelled`] if cancelled, or an error from [`request`].
305    pub fn request_and_wait(
306        permission: Permission,
307        timeout: Duration,
308        cancellation: Option<&CancellationToken>,
309    ) -> Result<PermissionStatus, Error> {
310        if let Some(token) = cancellation {
311            token.check()?;
312        }
313        let current = status(permission);
314        if current == PermissionStatus::Granted {
315            return Ok(current);
316        }
317        request(permission)?;
318        if permission == Permission::Accessibility {
319            return Ok(status(permission));
320        }
321        let start = Instant::now();
322        while start.elapsed() < timeout {
323            let delay = Duration::from_millis(500).min(timeout.saturating_sub(start.elapsed()));
324            if let Some(token) = cancellation {
325                token.wait(delay)?;
326            } else {
327                thread::sleep(delay);
328            }
329            let current = status(permission);
330            if current != PermissionStatus::Unknown {
331                return Ok(current);
332            }
333        }
334        if let Some(token) = cancellation {
335            token.check()?;
336        }
337        Ok(status(permission))
338    }
339}
340
341#[derive(Debug, Clone)]
342pub struct AudioProcess {
343    pub pid: u32,
344    pub name: String,
345    pub bundle_id: String,
346    pub is_playing_audio: bool,
347    pub is_using_mic: bool,
348}
349
350impl From<&RawProcess> for AudioProcess {
351    fn from(raw: &RawProcess) -> Self {
352        Self {
353            pid: raw.pid,
354            name: c_string(&raw.name),
355            bundle_id: c_string(&raw.bundle_id),
356            is_playing_audio: raw.is_running_output != 0,
357            is_using_mic: raw.is_running_input != 0,
358        }
359    }
360}
361
362/// Every live process doing audio IO.
363fn list_audio_processes() -> Result<Vec<AudioProcess>, Error> {
364    collect_processes(sys::mrec_list_audio_processes)
365}
366
367/// Applications doing audio IO, with helper processes folded into their app.
368fn list_audio_apps() -> Result<Vec<AudioProcess>, Error> {
369    collect_processes(sys::mrec_list_audio_apps)
370}
371
372fn collect_processes(
373    list: unsafe extern "C" fn(*mut RawProcess, usize, *mut usize) -> std::os::raw::c_int,
374) -> Result<Vec<AudioProcess>, Error> {
375    let mut buffer = vec![
376        RawProcess {
377            pid: 0,
378            is_running_output: 0,
379            is_running_input: 0,
380            bundle_id: [0; 256],
381            name: [0; 256],
382        };
383        256
384    ];
385    let mut count = 0usize;
386    loop {
387        let status = unsafe { list(buffer.as_mut_ptr(), buffer.len(), &mut count) };
388        if status == sys::MREC_ERR_BUFFER_TOO_SMALL {
389            buffer.resize(buffer.len() * 2, unsafe { mem::zeroed::<RawProcess>() });
390            continue;
391        }
392        check(status)?;
393        return Ok(buffer.iter().take(count).map(AudioProcess::from).collect());
394    }
395}
396
397/// Conferencing platform with a stable [`Platform::as_str`] identifier.
398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
399#[non_exhaustive]
400pub enum Platform {
401    Unknown,
402    Zoom,
403    Teams,
404    Meet,
405    Webex,
406    Slack,
407    Discord,
408    /// A browser tab on a call URL we recognise but cannot attribute further.
409    Browser,
410    GoTo,
411    Dialpad,
412    WhatsApp,
413    Aircall,
414    RingCentral,
415    EightByEight,
416    VooV,
417    Tuple,
418    Gather,
419    Lark,
420    Roam,
421    ClickUp,
422    Telemost,
423    Telegram,
424    Signal,
425    Viber,
426    Line,
427    WeChat,
428    Zalo,
429    Jitsi,
430    Element,
431    Mattermost,
432    NextcloudTalk,
433    Jami,
434    TencentMeeting,
435    WeCom,
436}
437
438impl From<i32> for Platform {
439    fn from(value: i32) -> Self {
440        match value {
441            1 => Platform::Zoom,
442            2 => Platform::Teams,
443            3 => Platform::Meet,
444            4 => Platform::Webex,
445            5 => Platform::Slack,
446            6 => Platform::Discord,
447            7 => Platform::Browser,
448            8 => Platform::GoTo,
449            9 => Platform::Dialpad,
450            10 => Platform::WhatsApp,
451            11 => Platform::Aircall,
452            12 => Platform::RingCentral,
453            13 => Platform::EightByEight,
454            14 => Platform::VooV,
455            15 => Platform::Tuple,
456            16 => Platform::Gather,
457            17 => Platform::Lark,
458            18 => Platform::Roam,
459            19 => Platform::ClickUp,
460            20 => Platform::Telemost,
461            21 => Platform::Telegram,
462            22 => Platform::Signal,
463            23 => Platform::Viber,
464            24 => Platform::Line,
465            25 => Platform::WeChat,
466            26 => Platform::Zalo,
467            27 => Platform::Jitsi,
468            28 => Platform::Element,
469            29 => Platform::Mattermost,
470            30 => Platform::NextcloudTalk,
471            31 => Platform::Jami,
472            32 => Platform::TencentMeeting,
473            33 => Platform::WeCom,
474            _ => Platform::Unknown,
475        }
476    }
477}
478
479impl Platform {
480    /// Stable platform identifier, suitable for storage and API responses.
481    pub const fn as_str(self) -> &'static str {
482        match self {
483            Platform::Unknown => "unknown",
484            Platform::Zoom => "zoom",
485            Platform::Teams => "teams",
486            Platform::Meet => "meet",
487            Platform::Webex => "webex",
488            Platform::Slack => "slack",
489            Platform::Discord => "discord",
490            Platform::Browser => "browser",
491            Platform::GoTo => "goto",
492            Platform::Dialpad => "dialpad",
493            Platform::WhatsApp => "whatsapp",
494            Platform::Aircall => "aircall",
495            Platform::RingCentral => "ringcentral",
496            Platform::EightByEight => "8x8",
497            Platform::VooV => "voov",
498            Platform::Tuple => "tuple",
499            Platform::Gather => "gather",
500            Platform::Lark => "lark",
501            Platform::Roam => "roam",
502            Platform::ClickUp => "clickup",
503            Platform::Telemost => "telemost",
504            Platform::Telegram => "telegram",
505            Platform::Signal => "signal",
506            Platform::Viber => "viber",
507            Platform::Line => "line",
508            Platform::WeChat => "wechat",
509            Platform::Zalo => "zalo",
510            Platform::Jitsi => "jitsi",
511            Platform::Element => "element",
512            Platform::Mattermost => "mattermost",
513            Platform::NextcloudTalk => "nextcloud-talk",
514            Platform::Jami => "jami",
515            Platform::TencentMeeting => "tencent-meeting",
516            Platform::WeCom => "wecom",
517        }
518    }
519}
520
521#[cfg(test)]
522mod platform_tests {
523    use super::{Meeting, Platform, RawMeeting};
524    use std::{ffi::CStr, os::raw::c_char};
525
526    extern "C" {
527        fn mrec_platform_id(platform: i32) -> *const c_char;
528    }
529
530    #[test]
531    fn platforms_match_native_abi_and_ids() {
532        let platforms = [
533            (Platform::Unknown, "unknown"),
534            (Platform::Zoom, "zoom"),
535            (Platform::Teams, "teams"),
536            (Platform::Meet, "meet"),
537            (Platform::Webex, "webex"),
538            (Platform::Slack, "slack"),
539            (Platform::Discord, "discord"),
540            (Platform::Browser, "browser"),
541            (Platform::GoTo, "goto"),
542            (Platform::Dialpad, "dialpad"),
543            (Platform::WhatsApp, "whatsapp"),
544            (Platform::Aircall, "aircall"),
545            (Platform::RingCentral, "ringcentral"),
546            (Platform::EightByEight, "8x8"),
547            (Platform::VooV, "voov"),
548            (Platform::Tuple, "tuple"),
549            (Platform::Gather, "gather"),
550            (Platform::Lark, "lark"),
551            (Platform::Roam, "roam"),
552            (Platform::ClickUp, "clickup"),
553            (Platform::Telemost, "telemost"),
554            (Platform::Telegram, "telegram"),
555            (Platform::Signal, "signal"),
556            (Platform::Viber, "viber"),
557            (Platform::Line, "line"),
558            (Platform::WeChat, "wechat"),
559            (Platform::Zalo, "zalo"),
560            (Platform::Jitsi, "jitsi"),
561            (Platform::Element, "element"),
562            (Platform::Mattermost, "mattermost"),
563            (Platform::NextcloudTalk, "nextcloud-talk"),
564            (Platform::Jami, "jami"),
565            (Platform::TencentMeeting, "tencent-meeting"),
566            (Platform::WeCom, "wecom"),
567        ];
568        for (raw, (platform, id)) in platforms.into_iter().enumerate() {
569            assert_eq!(Platform::from(raw as i32), platform);
570            assert_eq!(platform.as_str(), id);
571            let native_id = unsafe { CStr::from_ptr(mrec_platform_id(raw as i32)) };
572            assert_eq!(native_id.to_str().unwrap(), id);
573            let mut meeting: RawMeeting = unsafe { std::mem::zeroed() };
574            meeting.platform = raw as i32;
575            assert_eq!(Meeting::from(&meeting).platform, platform);
576        }
577        assert_eq!(Platform::from(-1), Platform::Unknown);
578        assert_eq!(Platform::from(i32::MAX), Platform::Unknown);
579    }
580}
581
582#[derive(Debug, Clone)]
583pub struct Meeting {
584    pub platform: Platform,
585    /// The user-visible application. Use this with [`CaptureTarget::Process`].
586    pub pid: u32,
587    pub app_name: String,
588    /// Window or tab title. Requires the accessibility permission on macOS;
589    /// empty otherwise.
590    pub title: String,
591    /// The active tab's address for browser meetings. Requires the
592    /// accessibility permission on macOS; empty otherwise, or when the call
593    /// is in a background tab.
594    pub url: String,
595    pub is_using_mic: bool,
596    pub is_playing_audio: bool,
597    pub confidence: i32,
598    /// Prefer this to comparing `confidence`; the weights may change.
599    pub should_record: bool,
600}
601
602impl From<&RawMeeting> for Meeting {
603    fn from(raw: &RawMeeting) -> Self {
604        Self {
605            platform: raw.platform.into(),
606            pid: raw.pid,
607            app_name: c_string(&raw.app_name),
608            title: c_string(&raw.title),
609            url: c_string(&raw.url),
610            is_using_mic: raw.is_using_mic != 0,
611            is_playing_audio: raw.is_playing_audio != 0,
612            confidence: raw.confidence,
613            should_record: raw.should_record != 0,
614        }
615    }
616}
617
618/// Point-in-time scan, highest confidence first.
619fn scan_meetings() -> Result<Vec<Meeting>, Error> {
620    let mut buffer = vec![unsafe { mem::zeroed::<RawMeeting>() }; 16];
621    let mut count = 0usize;
622    loop {
623        let status = unsafe { sys::mrec_scan(buffer.as_mut_ptr(), buffer.len(), &mut count) };
624        if status == sys::MREC_ERR_BUFFER_TOO_SMALL {
625            buffer.resize(buffer.len() * 2, unsafe { mem::zeroed::<RawMeeting>() });
626            continue;
627        }
628        check(status)?;
629        return Ok(buffer.iter().take(count).map(Meeting::from).collect());
630    }
631}
632
633#[derive(Debug, Clone, Copy, PartialEq, Eq)]
634pub enum MeetingEvent {
635    Started,
636    Updated,
637    /// The meeting is no longer detected. Only platform and pid are meaningful
638    /// in its payload; other fields may be stale. Does not stop capture.
639    Ended,
640}
641
642impl From<i32> for MeetingEvent {
643    fn from(value: i32) -> Self {
644        match value {
645            0 => MeetingEvent::Started,
646            2 => MeetingEvent::Ended,
647            _ => MeetingEvent::Updated,
648        }
649    }
650}
651
652type MeetingHandler = Box<dyn FnMut(MeetingEvent, &Meeting) + Send + 'static>;
653
654// The watcher is a process-wide singleton, so the handler lives here rather
655// than in the C API's `void*`.
656struct MeetingHandlerSlot {
657    handler: Option<MeetingHandler>,
658    generation: u64,
659}
660
661static MEETING_HANDLER: Mutex<MeetingHandlerSlot> = Mutex::new(MeetingHandlerSlot {
662    handler: None,
663    generation: 0,
664});
665
666unsafe extern "C" fn meeting_trampoline(
667    meeting: *const RawMeeting,
668    event: c_int,
669    _user_data: *mut c_void,
670) {
671    if meeting.is_null() {
672        return;
673    }
674    let event = event.into();
675    let parsed = Meeting::from(&*meeting);
676
677    let (handler, generation) = match MEETING_HANDLER.lock() {
678        Ok(mut slot) => (slot.handler.take(), slot.generation),
679        Err(_) => return,
680    };
681    let Some(mut handler) = handler else { return };
682
683    // A panic must not cross the FFI boundary. Invoke without holding the slot
684    // lock so a handler can drop its own watcher without deadlocking.
685    let result = panic::catch_unwind(AssertUnwindSafe(|| handler(event, &parsed)));
686    if result.is_ok() {
687        if let Ok(mut slot) = MEETING_HANDLER.lock() {
688            if slot.generation == generation && slot.handler.is_none() {
689                slot.handler = Some(handler);
690            }
691        }
692    }
693}
694
695/// Stops watching when dropped.
696#[must_use = "watching stops when this guard is dropped"]
697pub struct Watcher {
698    _private: (),
699}
700
701impl Drop for Watcher {
702    fn drop(&mut self) {
703        unsafe { sys::mrec_watch_stop() };
704        if let Ok(mut slot) = MEETING_HANDLER.lock() {
705            slot.generation = slot.generation.wrapping_add(1);
706            slot.handler = None;
707        }
708    }
709}
710
711/// Watch for meetings starting, changing and ending.
712///
713/// The handler runs on an internal serial queue, so it may allocate and block.
714fn watch_meetings<F>(handler: F) -> Result<Watcher, Error>
715where
716    F: FnMut(MeetingEvent, &Meeting) + Send + 'static,
717{
718    let mut slot = MEETING_HANDLER
719        .lock()
720        .map_err(|error| Error::Internal(error.to_string()))?;
721    if slot.handler.is_some() || unsafe { sys::mrec_is_watching() } != 0 {
722        return Err(Error::AlreadyRunning);
723    }
724    slot.generation = slot.generation.wrapping_add(1);
725    slot.handler = Some(Box::new(handler));
726
727    let status = unsafe { sys::mrec_watch_start(Some(meeting_trampoline), ptr::null_mut()) };
728    if status != sys::MREC_OK {
729        slot.generation = slot.generation.wrapping_add(1);
730        slot.handler = None;
731        return check(status).map(|_| unreachable!());
732    }
733    drop(slot);
734    Ok(Watcher { _private: () })
735}
736
737#[derive(Debug, Clone, Copy, PartialEq, Eq)]
738pub enum CaptureTarget {
739    /// A detected meeting's app pid, or any audio-producing process pid.
740    Process { pid: u32 },
741    /// All application output.
742    System,
743}
744
745#[derive(Debug, Clone, Copy, PartialEq, Eq)]
746pub enum MicrophoneSource {
747    /// Follow the OS default input device.
748    Default,
749    /// Prefer the captured app's microphone, then the default (communications
750    /// default on Windows). Ambiguous app inputs use the default on macOS.
751    Auto,
752}
753
754/// Optional microphone effects for input rates from 8 to 192 kHz. All default off.
755#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
756pub struct MicrophoneProcessing {
757    /// Cancel echo using the captured system track as the playback reference.
758    pub echo_cancellation: bool,
759    /// Suppress background noise in the microphone track.
760    pub noise_suppression: bool,
761    /// Adjust microphone gain automatically.
762    pub auto_gain_control: bool,
763}
764
765impl MicrophoneProcessing {
766    fn flags(self) -> i32 {
767        (if self.echo_cancellation { 0x100 } else { 0 })
768            | (if self.noise_suppression { 0x200 } else { 0 })
769            | (if self.auto_gain_control { 0x400 } else { 0 })
770    }
771}
772
773#[derive(Debug, Clone)]
774pub struct CaptureOptions {
775    /// Windows: permit whole-output capture for known process-loopback
776    /// incompatibilities. With System, explicitly capture all outputs.
777    /// Defaults to true. Includes other apps/recorder playback; output volume
778    /// and mute may affect samples. Other platforms retain their normal path.
779    pub allow_system_audio_fallback: bool,
780    /// Mono mixdown for system audio only. The microphone keeps its format. Defaults to true.
781    pub mono: bool,
782    /// Optional microphone track. Defaults to none. Unavailable devices recover
783    /// while system capture continues.
784    pub microphone: Option<MicrophoneSource>,
785    /// Microphone effects, all off by default. Requires a microphone source.
786    pub microphone_processing: MicrophoneProcessing,
787    /// Additional timestamp-aligned mono s16le output.
788    pub mix: Option<MixedAudioOptions>,
789    /// Cancellation stops capture, including a pending start.
790    pub cancellation: Option<CancellationToken>,
791}
792
793impl Default for CaptureOptions {
794    fn default() -> Self {
795        Self {
796            mono: true,
797            allow_system_audio_fallback: true,
798            microphone: None,
799            microphone_processing: MicrophoneProcessing::default(),
800            mix: None,
801            cancellation: None,
802        }
803    }
804}
805
806#[derive(Debug, Clone, Copy, PartialEq, Eq)]
807pub enum CaptureState {
808    /// Audio frames are available from the tracks.
809    Recording,
810    /// Incoming frames are discarded. No silence is synthesized.
811    Paused,
812    Stopped,
813}
814
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
816pub enum Track {
817    SystemAudio,
818    Microphone,
819}
820
821/// Details present only when the backend selects a fallback capture path.
822#[derive(Debug, Clone, PartialEq, Eq)]
823pub enum CaptureFallback {
824    /// A known source cannot be captured reliably with process isolation.
825    ProcessCaptureIncompatible {
826        /// Native catalog identity that triggered fallback, if known.
827        app_id: Option<String>,
828    },
829}
830
831/// Actual capture scope and capabilities, reported by the native backend.
832#[derive(Debug, Clone, PartialEq, Eq)]
833pub struct CaptureInfo {
834    /// Target requested by the caller, including the PID for a process target.
835    pub requested_target: CaptureTarget,
836    /// Target actually recorded; system-wide only when fallback is permitted or requested.
837    pub actual_target: CaptureTarget,
838    /// Present when a permitted alternative capture path was selected.
839    pub fallback: Option<CaptureFallback>,
840    /// Output-device volume/mute may affect samples. Not a mute-state detector.
841    pub volume_dependent: bool,
842    /// Whether recorder playback and its child processes are included.
843    pub includes_recorder_audio: bool,
844}
845
846impl CaptureInfo {
847    fn from_raw(info: &sys::CaptureInfo, target: CaptureTarget) -> Self {
848        let app = c_string(&info.app_id);
849        Self {
850            requested_target: target,
851            actual_target: if info.actual_scope == 1 {
852                CaptureTarget::System
853            } else {
854                target
855            },
856            fallback: if info.reason == 1 {
857                Some(CaptureFallback::ProcessCaptureIncompatible {
858                    app_id: if app.is_empty() { None } else { Some(app) },
859                })
860            } else {
861                None
862            },
863            volume_dependent: info.volume_dependent != 0,
864            includes_recorder_audio: info.includes_recorder != 0,
865        }
866    }
867}
868
869/// Reason for source loss.
870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871#[non_exhaustive]
872pub enum InterruptionReason {
873    /// Unplugged, disabled, or none left.
874    DeviceRemoved,
875    /// The device in use changed and did not reopen.
876    DeviceChanged,
877    FormatChanged,
878    /// Every captured app exited.
879    AppExited,
880    /// The audio service restarted.
881    ServiceReset,
882    Unknown,
883}
884
885impl From<i32> for InterruptionReason {
886    fn from(value: i32) -> Self {
887        match value {
888            sys::MREC_TRACK_REASON_DEVICE_REMOVED => InterruptionReason::DeviceRemoved,
889            sys::MREC_TRACK_REASON_DEVICE_CHANGED => InterruptionReason::DeviceChanged,
890            sys::MREC_TRACK_REASON_FORMAT_CHANGED => InterruptionReason::FormatChanged,
891            sys::MREC_TRACK_REASON_APP_EXITED => InterruptionReason::AppExited,
892            sys::MREC_TRACK_REASON_SERVICE_RESET => InterruptionReason::ServiceReset,
893            _ => InterruptionReason::Unknown,
894        }
895    }
896}
897
898/// Source availability changes independently of recording pause and stop.
899/// Lost devices are retried; exited apps require selecting a new process target.
900#[derive(Debug, Clone, PartialEq, Eq)]
901#[non_exhaustive]
902pub enum TrackEvent {
903    /// Initial native capture path, or a later change, without source loss.
904    CaptureChanged(CaptureInfo),
905    /// No source is available; `Degraded` or `Resumed` reports recovery.
906    Interrupted {
907        track: Track,
908        reason: InterruptionReason,
909        message: String,
910    },
911    Resumed {
912        track: Track,
913    },
914    /// Some sources are unavailable; the others continue delivering audio.
915    Degraded {
916        track: Track,
917        reason: InterruptionReason,
918        message: String,
919    },
920    /// The microphone moved to another device.
921    DeviceChanged {
922        device_name: String,
923    },
924}
925
926/// What the system-audio track's events have said so far.
927#[derive(Default)]
928struct SystemAudioStatus {
929    availability: Arc<AtomicUsize>,
930    /// Set by the capture-changed event native start publishes before returning.
931    capture_info: OnceLock<Arc<Mutex<CaptureInfo>>>,
932}
933
934/// What the microphone track's events have said so far.
935#[derive(Default)]
936struct MicrophoneStatus {
937    availability: Arc<AtomicUsize>,
938    device_name: Arc<Mutex<Option<String>>>,
939}
940
941/// Track events in arrival order, until capture stops.
942#[derive(Default)]
943struct EventQueue {
944    events: Mutex<VecDeque<TrackEvent>>,
945    ready: Condvar,
946    closed: AtomicBool,
947}
948
949impl EventQueue {
950    fn push(&self, event: TrackEvent) {
951        self.events
952            .lock()
953            .unwrap_or_else(|error| error.into_inner())
954            .push_back(event);
955        self.ready.notify_all();
956    }
957
958    fn close(&self) {
959        let _events = self
960            .events
961            .lock()
962            .unwrap_or_else(|error| error.into_inner());
963        self.closed.store(true, Ordering::Release);
964        self.ready.notify_all();
965    }
966
967    fn recv(&self) -> Option<TrackEvent> {
968        let mut events = self
969            .events
970            .lock()
971            .unwrap_or_else(|error| error.into_inner());
972        loop {
973            if let Some(event) = events.pop_front() {
974                return Some(event);
975            }
976            if self.closed.load(Ordering::Acquire) {
977                return None;
978            }
979            events = self
980                .ready
981                .wait(events)
982                .unwrap_or_else(|error| error.into_inner());
983        }
984    }
985
986    fn try_recv(&self) -> Option<TrackEvent> {
987        self.events
988            .lock()
989            .unwrap_or_else(|error| error.into_inner())
990            .pop_front()
991    }
992}
993
994struct EventContext {
995    target: CaptureTarget,
996    queue: Arc<EventQueue>,
997    system_audio: Arc<SystemAudioStatus>,
998    microphone: Arc<MicrophoneStatus>,
999}
1000
1001unsafe extern "C" fn track_event_trampoline(event: *const sys::TrackEvent, user_data: *mut c_void) {
1002    if event.is_null() || user_data.is_null() {
1003        return;
1004    }
1005    let context = &*(user_data as *const EventContext);
1006    let event = &*event;
1007    let (track, availability) = match event.track {
1008        sys::MREC_TRACK_SYSTEM_AUDIO => (Track::SystemAudio, &context.system_audio.availability),
1009        sys::MREC_TRACK_MICROPHONE => (Track::Microphone, &context.microphone.availability),
1010        _ => return,
1011    };
1012    let event = match event.kind {
1013        sys::MREC_TRACK_CAPTURE_CHANGED => {
1014            if track != Track::SystemAudio {
1015                return;
1016            }
1017            let info = CaptureInfo::from_raw(&event.capture_info, context.target);
1018            *context
1019                .system_audio
1020                .capture_info
1021                .get_or_init(|| Arc::new(Mutex::new(info.clone())))
1022                .lock()
1023                .unwrap_or_else(|error| error.into_inner()) = info.clone();
1024            TrackEvent::CaptureChanged(info)
1025        }
1026        sys::MREC_TRACK_INTERRUPTED => {
1027            availability.store(2, Ordering::Release);
1028            TrackEvent::Interrupted {
1029                track,
1030                reason: event.reason.into(),
1031                message: c_string(&event.message),
1032            }
1033        }
1034        sys::MREC_TRACK_RESUMED => {
1035            availability.store(0, Ordering::Release);
1036            TrackEvent::Resumed { track }
1037        }
1038        sys::MREC_TRACK_DEGRADED => {
1039            availability.store(1, Ordering::Release);
1040            TrackEvent::Degraded {
1041                track,
1042                reason: event.reason.into(),
1043                message: c_string(&event.message),
1044            }
1045        }
1046        sys::MREC_TRACK_DEVICE_CHANGED => {
1047            if track != Track::Microphone {
1048                return;
1049            }
1050            let device_name = c_string(&event.device_name);
1051            *context
1052                .microphone
1053                .device_name
1054                .lock()
1055                .unwrap_or_else(|error| error.into_inner()) = Some(device_name.clone());
1056            TrackEvent::DeviceChanged { device_name }
1057        }
1058        _ => return,
1059    };
1060    context.queue.push(event);
1061}
1062
1063#[derive(Debug)]
1064pub struct AudioChunk {
1065    /// Interleaved float32 PCM.
1066    pub frames: Vec<f32>,
1067    /// First frame's monotonic timestamp in nanoseconds, shared across tracks.
1068    pub host_time_ns: u64,
1069    /// Number of frames per channel in this packet.
1070    pub frame_count: u32,
1071    pub channels: u32,
1072    /// This packet's rate in Hz; it may change after device recovery.
1073    pub sample_rate: f64,
1074    /// Interleaved samples discarded since the previous delivered chunk.
1075    pub dropped_samples: usize,
1076}
1077
1078const TRACK_CAPACITY: usize = 1 << 20;
1079const TRACK_PACKET_CAPACITY: usize = 1 << 12;
1080// Low bits hold the phase; upper bits identify segments across pause/resume.
1081const STATE_RECORDING: usize = 0;
1082const STATE_PAUSED: usize = 1;
1083const STATE_STOPPED: usize = 2;
1084const STATE_MASK: usize = 3;
1085
1086#[derive(Clone, Copy, Default)]
1087struct PacketMeta {
1088    sample_start: usize,
1089    sample_count: usize,
1090    frame_count: u32,
1091    channels: u32,
1092    sample_rate: f64,
1093    host_time_ns: u64,
1094    dropped_before: usize,
1095    segment: usize,
1096}
1097
1098struct QueuedChunk {
1099    audio: AudioChunk,
1100    segment: usize,
1101}
1102
1103struct TrackQueue {
1104    buffer: Box<[UnsafeCell<f32>]>,
1105    mask: usize,
1106    packets: Box<[UnsafeCell<PacketMeta>]>,
1107    packet_mask: usize,
1108    head: AtomicUsize,
1109    tail: AtomicUsize,
1110    packet_head: AtomicUsize,
1111    packet_tail: AtomicUsize,
1112    dropped: AtomicUsize,
1113    dropped_since_read: AtomicUsize,
1114    writing: AtomicBool,
1115    closed: AtomicBool,
1116    read_lock: Mutex<()>,
1117    wake_lock: Mutex<()>,
1118    wake: Condvar,
1119}
1120
1121// SAFETY: producers are serialized by `writing`, consumers by `read_lock`, and
1122// published regions are transferred with the atomic head and tail positions.
1123unsafe impl Sync for TrackQueue {}
1124
1125impl TrackQueue {
1126    fn new() -> Self {
1127        let buffer = (0..TRACK_CAPACITY)
1128            .map(|_| UnsafeCell::new(0.0))
1129            .collect::<Vec<_>>()
1130            .into_boxed_slice();
1131        Self {
1132            buffer,
1133            mask: TRACK_CAPACITY - 1,
1134            packets: (0..TRACK_PACKET_CAPACITY)
1135                .map(|_| UnsafeCell::new(PacketMeta::default()))
1136                .collect::<Vec<_>>()
1137                .into_boxed_slice(),
1138            packet_mask: TRACK_PACKET_CAPACITY - 1,
1139            head: AtomicUsize::new(0),
1140            tail: AtomicUsize::new(0),
1141            packet_head: AtomicUsize::new(0),
1142            packet_tail: AtomicUsize::new(0),
1143            dropped: AtomicUsize::new(0),
1144            dropped_since_read: AtomicUsize::new(0),
1145            writing: AtomicBool::new(false),
1146            closed: AtomicBool::new(false),
1147            read_lock: Mutex::new(()),
1148            wake_lock: Mutex::new(()),
1149            wake: Condvar::new(),
1150        }
1151    }
1152
1153    fn write(&self, frames: &[f32], mut packet: PacketMeta, state: &AtomicUsize) {
1154        if self
1155            .writing
1156            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
1157            .is_err()
1158        {
1159            self.dropped.fetch_add(frames.len(), Ordering::Relaxed);
1160            self.dropped_since_read
1161                .fetch_add(frames.len(), Ordering::Relaxed);
1162            return;
1163        }
1164
1165        if self.closed.load(Ordering::Acquire)
1166            || state.load(Ordering::Acquire) != packet.segment << 2
1167        {
1168            self.writing.store(false, Ordering::Release);
1169            return;
1170        }
1171
1172        let head = self.head.load(Ordering::Relaxed);
1173        let tail = self.tail.load(Ordering::Acquire);
1174        let used = head.wrapping_sub(tail);
1175        let packet_head = self.packet_head.load(Ordering::Relaxed);
1176        let packet_tail = self.packet_tail.load(Ordering::Acquire);
1177        if !frames.is_empty()
1178            && frames.len() <= TRACK_CAPACITY.saturating_sub(used)
1179            && packet_head.wrapping_sub(packet_tail) < TRACK_PACKET_CAPACITY
1180        {
1181            for (offset, sample) in frames.iter().enumerate() {
1182                unsafe { *self.buffer[(head + offset) & self.mask].get() = *sample };
1183            }
1184            packet.sample_start = head;
1185            packet.sample_count = frames.len();
1186            packet.dropped_before = self.dropped_since_read.swap(0, Ordering::Relaxed);
1187            unsafe {
1188                *self.packets[packet_head & self.packet_mask].get() = packet;
1189            }
1190            self.head
1191                .store(head.wrapping_add(frames.len()), Ordering::Release);
1192            self.packet_head
1193                .store(packet_head.wrapping_add(1), Ordering::Release);
1194            self.wake.notify_one();
1195        } else {
1196            self.dropped.fetch_add(frames.len(), Ordering::Relaxed);
1197            self.dropped_since_read
1198                .fetch_add(frames.len(), Ordering::Relaxed);
1199        }
1200        self.writing.store(false, Ordering::Release);
1201    }
1202
1203    fn try_recv(&self) -> Option<QueuedChunk> {
1204        let _read = self
1205            .read_lock
1206            .lock()
1207            .unwrap_or_else(|error| error.into_inner());
1208        let packet_tail = self.packet_tail.load(Ordering::Relaxed);
1209        let packet_head = self.packet_head.load(Ordering::Acquire);
1210        if packet_tail == packet_head {
1211            return None;
1212        }
1213        let first = unsafe { *self.packets[packet_tail & self.packet_mask].get() };
1214        let mut next_packet = packet_tail;
1215        let mut sample_count = 0usize;
1216        let mut frame_count = 0u32;
1217        while next_packet != packet_head {
1218            let packet = unsafe { *self.packets[next_packet & self.packet_mask].get() };
1219            if packet.channels != first.channels
1220                || packet.sample_rate != first.sample_rate
1221                || packet.segment != first.segment
1222                || (next_packet != packet_tail
1223                    && (packet.dropped_before != 0
1224                        || !Self::packets_are_contiguous(&first, frame_count, &packet)))
1225            {
1226                break;
1227            }
1228            sample_count += packet.sample_count;
1229            frame_count = frame_count.saturating_add(packet.frame_count);
1230            next_packet = next_packet.wrapping_add(1);
1231        }
1232        let mut frames = Vec::with_capacity(sample_count);
1233        for offset in 0..sample_count {
1234            frames.push(unsafe { *self.buffer[(first.sample_start + offset) & self.mask].get() });
1235        }
1236        self.tail.store(
1237            first.sample_start.wrapping_add(sample_count),
1238            Ordering::Release,
1239        );
1240        self.packet_tail.store(next_packet, Ordering::Release);
1241        Some(QueuedChunk {
1242            audio: AudioChunk {
1243                frames,
1244                host_time_ns: first.host_time_ns,
1245                frame_count,
1246                channels: first.channels,
1247                sample_rate: first.sample_rate,
1248                dropped_samples: first.dropped_before,
1249            },
1250            segment: first.segment,
1251        })
1252    }
1253
1254    fn recv(&self) -> Option<AudioChunk> {
1255        loop {
1256            // Closure precedes the final read so EOF includes the last publication.
1257            let closed = self.closed.load(Ordering::Acquire);
1258            if let Some(packet) = self.try_recv() {
1259                return Some(packet.audio);
1260            }
1261            if closed {
1262                return None;
1263            }
1264            let guard = self
1265                .wake_lock
1266                .lock()
1267                .unwrap_or_else(|error| error.into_inner());
1268            let _ = self
1269                .wake
1270                .wait_timeout(guard, Duration::from_millis(100))
1271                .unwrap_or_else(|error| error.into_inner());
1272        }
1273    }
1274
1275    fn barrier(&self) {
1276        self.wait_for_writer();
1277        self.writing.store(false, Ordering::Release);
1278    }
1279
1280    fn wait_for_writer(&self) {
1281        while self
1282            .writing
1283            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
1284            .is_err()
1285        {
1286            thread::yield_now();
1287        }
1288    }
1289
1290    fn clear(&self) {
1291        self.wait_for_writer();
1292        let _read = self
1293            .read_lock
1294            .lock()
1295            .unwrap_or_else(|error| error.into_inner());
1296        self.tail
1297            .store(self.head.load(Ordering::Acquire), Ordering::Release);
1298        self.packet_tail
1299            .store(self.packet_head.load(Ordering::Acquire), Ordering::Release);
1300        self.dropped_since_read.store(0, Ordering::Relaxed);
1301        self.writing.store(false, Ordering::Release);
1302    }
1303
1304    fn packets_are_contiguous(
1305        first: &PacketMeta,
1306        preceding_frames: u32,
1307        next: &PacketMeta,
1308    ) -> bool {
1309        if first.host_time_ns == 0 || next.host_time_ns == 0 || first.sample_rate <= 0.0 {
1310            return true;
1311        }
1312        let elapsed =
1313            (f64::from(preceding_frames) * 1_000_000_000.0 / first.sample_rate).round() as u64;
1314        let expected = first.host_time_ns.saturating_add(elapsed);
1315        expected.abs_diff(next.host_time_ns) <= 2_000_000
1316    }
1317
1318    fn close(&self) {
1319        self.wait_for_writer();
1320        self.closed.store(true, Ordering::Release);
1321        self.writing.store(false, Ordering::Release);
1322        self.wake.notify_all();
1323    }
1324}
1325
1326/// Availability of a track's sources, independent of pause and stop.
1327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1328pub enum TrackAvailability {
1329    Live,
1330    Degraded,
1331    Interrupted,
1332}
1333
1334/// One interleaved float32 PCM track; `Source` adds what only that track reports.
1335pub struct AudioTrack<Source> {
1336    sample_rate: f64,
1337    channels: u32,
1338    queue: Arc<TrackQueue>,
1339    availability: Arc<AtomicUsize>,
1340    source: Source,
1341}
1342
1343/// What only the system-audio track reports.
1344pub struct SystemAudio {
1345    capture_info: Arc<Mutex<CaptureInfo>>,
1346}
1347
1348/// What only the microphone track reports.
1349pub struct Microphone {
1350    device_name: Arc<Mutex<Option<String>>>,
1351}
1352
1353pub type SystemAudioTrack = AudioTrack<SystemAudio>;
1354pub type MicrophoneTrack = AudioTrack<Microphone>;
1355
1356impl<Source> AudioTrack<Source> {
1357    /// Initial negotiated rate, or zero while the microphone is unavailable.
1358    /// A recovered device may change it; each
1359    /// [`AudioChunk::sample_rate`] is authoritative.
1360    pub fn sample_rate(&self) -> f64 {
1361        self.sample_rate
1362    }
1363
1364    /// Initial channel count. A recovered device may change it; each
1365    /// [`AudioChunk::channels`] is authoritative.
1366    pub fn channels(&self) -> u32 {
1367        self.channels
1368    }
1369
1370    /// Number of interleaved samples discarded because the bounded queue could
1371    /// not accept them.
1372    pub fn dropped_samples(&self) -> usize {
1373        self.queue.dropped.load(Ordering::Relaxed)
1374    }
1375
1376    /// Wait for the next chunk, or return `None` after capture stops and the
1377    /// queued audio has been drained. Read on a worker thread while controlling
1378    /// the session elsewhere.
1379    pub fn recv(&self) -> Option<AudioChunk> {
1380        self.queue.recv()
1381    }
1382
1383    /// True when none of this track's sources are available.
1384    pub fn is_interrupted(&self) -> bool {
1385        self.availability() == TrackAvailability::Interrupted
1386    }
1387
1388    /// Current source availability, independent of pause and stop.
1389    pub fn availability(&self) -> TrackAvailability {
1390        match self.availability.load(Ordering::Acquire) {
1391            1 => TrackAvailability::Degraded,
1392            2 => TrackAvailability::Interrupted,
1393            _ => TrackAvailability::Live,
1394        }
1395    }
1396}
1397
1398impl AudioTrack<SystemAudio> {
1399    /// Actual playback capture scope/capabilities; [`TrackEvent::CaptureChanged`]
1400    /// announces changes. Retains its last value after stop.
1401    pub fn capture_info(&self) -> CaptureInfo {
1402        self.source
1403            .capture_info
1404            .lock()
1405            .unwrap_or_else(|error| error.into_inner())
1406            .clone()
1407    }
1408}
1409
1410impl AudioTrack<Microphone> {
1411    /// The device in use; `None` while no microphone is available.
1412    pub fn device_name(&self) -> Option<String> {
1413        self.source
1414            .device_name
1415            .lock()
1416            .unwrap_or_else(|error| error.into_inner())
1417            .clone()
1418    }
1419}
1420
1421struct TrackCallbackContext {
1422    queue: Arc<TrackQueue>,
1423    mix_queue: Option<Arc<TrackQueue>>,
1424    state: Arc<AtomicUsize>,
1425}
1426
1427struct CaptureCallbackContexts {
1428    system_audio: Box<TrackCallbackContext>,
1429    microphone: Option<Box<TrackCallbackContext>>,
1430    events: Box<EventContext>,
1431}
1432
1433static CAPTURE_CONTEXTS: Mutex<Option<CaptureCallbackContexts>> = Mutex::new(None);
1434
1435unsafe extern "C" fn audio_trampoline(
1436    frames: *const f32,
1437    frame_count: u32,
1438    channels: u32,
1439    sample_rate: f64,
1440    host_time_ns: u64,
1441    user_data: *mut c_void,
1442) {
1443    if frames.is_null() || frame_count == 0 || user_data.is_null() {
1444        return;
1445    }
1446    let context = &*(user_data as *const TrackCallbackContext);
1447    let state = context.state.load(Ordering::Acquire);
1448    if state & STATE_MASK != STATE_RECORDING {
1449        return;
1450    }
1451    let len = frame_count as usize * channels.max(1) as usize;
1452    let samples = slice::from_raw_parts(frames, len);
1453    let packet = PacketMeta {
1454        frame_count,
1455        channels,
1456        sample_rate,
1457        host_time_ns,
1458        segment: state >> 2,
1459        ..PacketMeta::default()
1460    };
1461    context.queue.write(samples, packet, &context.state);
1462    if let Some(queue) = &context.mix_queue {
1463        queue.write(samples, packet, &context.state);
1464    }
1465}
1466
1467struct CaptureControl {
1468    state: Arc<AtomicUsize>,
1469    queues: Vec<Arc<TrackQueue>>,
1470    raw_queues: Vec<Arc<TrackQueue>>,
1471    events: Arc<EventQueue>,
1472    lifecycle: Mutex<()>,
1473}
1474
1475impl CaptureControl {
1476    fn phase(&self) -> usize {
1477        self.state.load(Ordering::Acquire) & STATE_MASK
1478    }
1479
1480    fn pause(&self) {
1481        let _guard = self
1482            .lifecycle
1483            .lock()
1484            .unwrap_or_else(|error| error.into_inner());
1485        if self.phase() != STATE_RECORDING {
1486            return;
1487        }
1488        self.state.fetch_or(STATE_PAUSED, Ordering::AcqRel);
1489        for queue in &self.queues {
1490            queue.barrier();
1491        }
1492        for queue in &self.raw_queues {
1493            queue.clear();
1494        }
1495    }
1496
1497    fn resume(&self) {
1498        let _guard = self
1499            .lifecycle
1500            .lock()
1501            .unwrap_or_else(|error| error.into_inner());
1502        let state = self.state.load(Ordering::Acquire);
1503        if state & STATE_MASK != STATE_PAUSED {
1504            return;
1505        }
1506        for queue in &self.raw_queues {
1507            queue.clear();
1508        }
1509        self.state
1510            .store((state & !STATE_MASK).wrapping_add(4), Ordering::Release);
1511    }
1512
1513    fn stop(&self) {
1514        self.stop_with(|| {
1515            unsafe { sys::mrec_stop() };
1516        });
1517    }
1518
1519    fn stop_with(&self, stop_native: impl FnOnce()) {
1520        let _guard = self
1521            .lifecycle
1522            .lock()
1523            .unwrap_or_else(|error| error.into_inner());
1524        let state = self.state.load(Ordering::Acquire);
1525        if state & STATE_MASK == STATE_STOPPED {
1526            return;
1527        }
1528        // Accept final callbacks until native teardown finishes.
1529        stop_native();
1530        self.state
1531            .store((state & !STATE_MASK) | STATE_STOPPED, Ordering::Release);
1532        for queue in &self.queues {
1533            queue.close();
1534        }
1535        self.events.close();
1536        *CAPTURE_CONTEXTS
1537            .lock()
1538            .unwrap_or_else(|error| error.into_inner()) = None;
1539    }
1540}
1541
1542/// Owns the audio tracks and their shared recording lifecycle.
1543#[must_use = "capture stops when this session is dropped"]
1544pub struct CaptureSession {
1545    system_audio: SystemAudioTrack,
1546    microphone: Option<MicrophoneTrack>,
1547    mixed_audio: Option<MixedAudio>,
1548    control: Arc<CaptureControl>,
1549}
1550
1551impl CaptureSession {
1552    /// The system-audio track.
1553    pub fn system_audio(&self) -> &SystemAudioTrack {
1554        &self.system_audio
1555    }
1556    /// The microphone track, if requested in [`CaptureOptions`].
1557    pub fn microphone(&self) -> Option<&MicrophoneTrack> {
1558        self.microphone.as_ref()
1559    }
1560    /// The mono s16le mixed output, if configured in [`CaptureOptions`].
1561    pub fn mixed_audio(&self) -> Option<&MixedAudio> {
1562        self.mixed_audio.as_ref()
1563    }
1564
1565    /// Current recording state, independent of individual source availability.
1566    pub fn state(&self) -> CaptureState {
1567        match self.control.phase() {
1568            STATE_PAUSED => CaptureState::Paused,
1569            STATE_STOPPED => CaptureState::Stopped,
1570            _ => CaptureState::Recording,
1571        }
1572    }
1573
1574    /// Waits for the next source change, or returns `None` once capture stops.
1575    pub fn recv_event(&self) -> Option<TrackEvent> {
1576        self.control.events.recv()
1577    }
1578
1579    /// The next source change, if one is waiting.
1580    pub fn try_recv_event(&self) -> Option<TrackEvent> {
1581        self.control.events.try_recv()
1582    }
1583
1584    /// Discard incoming frames until resume; paused time is omitted.
1585    pub fn pause(&self) {
1586        self.control.pause();
1587    }
1588    /// Resume all tracks after a pause.
1589    pub fn resume(&self) {
1590        self.control.resume();
1591    }
1592
1593    /// Stop capture. Tracks retain their queued tail until drained.
1594    pub fn stop(&self) {
1595        self.control.stop();
1596    }
1597}
1598
1599impl Drop for CaptureSession {
1600    fn drop(&mut self) {
1601        self.stop();
1602    }
1603}
1604
1605fn start_capture(target: CaptureTarget, options: CaptureOptions) -> Result<CaptureSession, Error> {
1606    if let Some(token) = &options.cancellation {
1607        token.check()?;
1608    }
1609    if options.mix.is_some_and(|mix| mix.sample_rate == 0) {
1610        return Err(Error::Capture(
1611            "mix sample rate must be non-zero".to_owned(),
1612        ));
1613    }
1614    let processing = options.microphone_processing.flags();
1615    if processing != 0 && options.microphone.is_none() {
1616        return Err(Error::Capture(
1617            "microphone processing requires a microphone source".to_owned(),
1618        ));
1619    }
1620    if unsafe { sys::mrec_is_running() } != 0 {
1621        return Err(Error::AlreadyRunning);
1622    }
1623    let (pids, system_wide) = match target {
1624        CaptureTarget::Process { pid: 0 } => {
1625            return Err(Error::Capture("process pid must be non-zero".to_owned()))
1626        }
1627        CaptureTarget::Process { pid } => (vec![pid], false),
1628        CaptureTarget::System => (Vec::new(), true),
1629    };
1630    let state = Arc::new(AtomicUsize::new(STATE_RECORDING));
1631    let system_queue = Arc::new(TrackQueue::new());
1632    let microphone_queue = options.microphone.map(|_| Arc::new(TrackQueue::new()));
1633    let events = Arc::new(EventQueue::default());
1634    let system_status = Arc::new(SystemAudioStatus::default());
1635    let microphone_status = Arc::new(MicrophoneStatus::default());
1636    let system_mix_queue = options.mix.map(|_| Arc::new(TrackQueue::new()));
1637    let microphone_mix_queue = options
1638        .mix
1639        .and(options.microphone)
1640        .map(|_| Arc::new(TrackQueue::new()));
1641    let raw_queues: Vec<_> = std::iter::once(Arc::clone(&system_queue))
1642        .chain(microphone_queue.iter().cloned())
1643        .collect();
1644    let mix_queues: Vec<_> = system_mix_queue
1645        .iter()
1646        .cloned()
1647        .chain(microphone_mix_queue.iter().cloned())
1648        .collect();
1649    let mut contexts = CaptureCallbackContexts {
1650        system_audio: Box::new(TrackCallbackContext {
1651            queue: Arc::clone(&system_queue),
1652            mix_queue: system_mix_queue,
1653            state: Arc::clone(&state),
1654        }),
1655        microphone: microphone_queue.as_ref().map(|queue| {
1656            Box::new(TrackCallbackContext {
1657                queue: Arc::clone(queue),
1658                mix_queue: microphone_mix_queue,
1659                state: Arc::clone(&state),
1660            })
1661        }),
1662        events: Box::new(EventContext {
1663            target,
1664            queue: Arc::clone(&events),
1665            system_audio: Arc::clone(&system_status),
1666            microphone: Arc::clone(&microphone_status),
1667        }),
1668    };
1669    let system_context = (&mut *contexts.system_audio) as *mut TrackCallbackContext as *mut c_void;
1670    let microphone_context = contexts
1671        .microphone
1672        .as_mut()
1673        .map(|context| (&mut **context) as *mut TrackCallbackContext as *mut c_void)
1674        .unwrap_or(ptr::null_mut());
1675    let event_context = (&mut *contexts.events) as *mut EventContext as *mut c_void;
1676    let mut context_slot = CAPTURE_CONTEXTS
1677        .lock()
1678        .map_err(|error| Error::Internal(error.to_string()))?;
1679    if context_slot.is_some() {
1680        return Err(Error::AlreadyRunning);
1681    }
1682    *context_slot = Some(contexts);
1683    drop(context_slot);
1684    let control = Arc::new(CaptureControl {
1685        state: Arc::clone(&state),
1686        queues: raw_queues
1687            .iter()
1688            .cloned()
1689            .chain(mix_queues.iter().cloned())
1690            .collect(),
1691        raw_queues,
1692        events,
1693        lifecycle: Mutex::new(()),
1694    });
1695    let result = (|| {
1696        let status = unsafe {
1697            sys::mrec_start_tracks_raw(
1698                if pids.is_empty() {
1699                    ptr::null()
1700                } else {
1701                    pids.as_ptr()
1702                },
1703                pids.len(),
1704                (system_wide as i32)
1705                    | if options.allow_system_audio_fallback {
1706                        2
1707                    } else {
1708                        0
1709                    },
1710                options.mono as i32,
1711                0,
1712                processing
1713                    | match options.microphone {
1714                        Some(MicrophoneSource::Default) => 1,
1715                        Some(MicrophoneSource::Auto) => 2,
1716                        None => 0,
1717                    },
1718                Some(audio_trampoline),
1719                system_context,
1720                options
1721                    .microphone
1722                    .map(|_| audio_trampoline as RawAudioCallback),
1723                microphone_context,
1724                Some(track_event_trampoline),
1725                event_context,
1726            )
1727        };
1728        if let Some(token) = &options.cancellation {
1729            token.check()?;
1730        }
1731        check(status)?;
1732        let mut system_sample_rate = 0.0;
1733        let mut system_channels = 0;
1734        check(unsafe { sys::mrec_current_format(&mut system_sample_rate, &mut system_channels) })?;
1735        let microphone = if let Some(queue) = microphone_queue {
1736            let mut sample_rate = 0.0;
1737            let mut channels = 0;
1738            check(unsafe { sys::mrec_current_microphone_format(&mut sample_rate, &mut channels) })?;
1739            let mut name = [0 as c_char; 256];
1740            if unsafe { sys::mrec_current_microphone_name(name.as_mut_ptr(), name.len()) }
1741                == sys::MREC_OK
1742            {
1743                *microphone_status
1744                    .device_name
1745                    .lock()
1746                    .unwrap_or_else(|error| error.into_inner()) = Some(c_string(&name));
1747            }
1748            Some(AudioTrack {
1749                sample_rate,
1750                channels,
1751                queue,
1752                availability: Arc::clone(&microphone_status.availability),
1753                source: Microphone {
1754                    device_name: Arc::clone(&microphone_status.device_name),
1755                },
1756            })
1757        } else {
1758            None
1759        };
1760        let mixed_audio = options
1761            .mix
1762            .map(|mix| MixedAudio::new(mix.sample_rate, mix_queues, state))
1763            .transpose()?;
1764        let capture_info =
1765            system_status.capture_info.get().cloned().ok_or_else(|| {
1766                Error::Internal("capture started without capture info".to_owned())
1767            })?;
1768        if let Some(token) = &options.cancellation {
1769            token.register(&control)?;
1770        }
1771        Ok(CaptureSession {
1772            system_audio: AudioTrack {
1773                sample_rate: system_sample_rate,
1774                channels: system_channels,
1775                queue: system_queue,
1776                availability: Arc::clone(&system_status.availability),
1777                source: SystemAudio { capture_info },
1778            },
1779            microphone,
1780            mixed_audio,
1781            control: Arc::clone(&control),
1782        })
1783    })();
1784    if result.is_err() {
1785        control.stop();
1786    }
1787    result
1788}
1789
1790fn capture_running() -> bool {
1791    (unsafe { sys::mrec_is_running() != 0 })
1792        || CAPTURE_CONTEXTS
1793            .lock()
1794            .map(|contexts| contexts.is_some())
1795            .unwrap_or(true)
1796}
1797
1798fn meetings_watching() -> bool {
1799    unsafe { sys::mrec_is_watching() != 0 }
1800}
1801
1802pub mod meetings {
1803    use super::{AudioProcess, Error, Meeting, MeetingEvent, Watcher};
1804
1805    /// Every live process doing audio IO.
1806    ///
1807    /// # Errors
1808    /// Returns a platform or audio-service error if enumeration fails.
1809    pub fn audio_processes() -> Result<Vec<AudioProcess>, Error> {
1810        super::list_audio_processes()
1811    }
1812
1813    /// Applications doing audio IO, grouped by owning PID, including helpers.
1814    /// Pass `pid` to capture the app; no meeting scan or Accessibility grant is needed.
1815    ///
1816    /// # Errors
1817    /// Returns a platform or audio-service error if enumeration fails.
1818    pub fn audio_apps() -> Result<Vec<AudioProcess>, Error> {
1819        super::list_audio_apps()
1820    }
1821
1822    /// Point-in-time scan, highest confidence first.
1823    /// Use [`Meeting::should_record`] to select calls.
1824    ///
1825    /// # Errors
1826    /// Returns a platform or audio-service error if scanning fails.
1827    pub fn scan() -> Result<Vec<Meeting>, Error> {
1828        super::scan_meetings()
1829    }
1830
1831    /// Watch for meetings starting, changing and ending.
1832    ///
1833    /// The handler runs on an internal serial queue, so it may allocate and
1834    /// block.
1835    ///
1836    /// # Errors
1837    /// Returns [`Error::AlreadyRunning`] if a watcher is active, or a platform
1838    /// or initialization error if the watcher cannot start.
1839    pub fn watch<F>(handler: F) -> Result<Watcher, Error>
1840    where
1841        F: FnMut(MeetingEvent, &Meeting) + Send + 'static,
1842    {
1843        super::watch_meetings(handler)
1844    }
1845
1846    /// Whether the process-wide meeting watcher is active.
1847    pub fn watching() -> bool {
1848        super::meetings_watching()
1849    }
1850}
1851
1852pub mod capture {
1853    use super::{CaptureOptions, CaptureSession, CaptureTarget, Error};
1854
1855    /// Start capturing one process target or the system mix.
1856    ///
1857    /// Native initialization may block for six seconds. Cancellation during
1858    /// initialization is returned after that attempt has been cleaned up.
1859    ///
1860    /// # Errors
1861    /// Returns [`Error::AlreadyRunning`] if another recording is active,
1862    /// [`Error::Permission`] if access is denied, [`Error::Capture`] for invalid
1863    /// options or unavailable system audio, or [`Error::Cancelled`] if startup
1864    /// is cancelled. Platform and initialization failures return
1865    /// [`Error::UnsupportedOs`] or [`Error::Internal`].
1866    pub fn start(target: CaptureTarget, options: CaptureOptions) -> Result<CaptureSession, Error> {
1867        super::start_capture(target, options)
1868    }
1869
1870    /// Whether capture is active, including while paused or a source is interrupted.
1871    pub fn running() -> bool {
1872        super::capture_running()
1873    }
1874}
1875
1876#[cfg(test)]
1877mod capture_tests {
1878    use std::sync::atomic::AtomicUsize;
1879
1880    use super::{PacketMeta, TrackQueue, STATE_PAUSED, STATE_RECORDING};
1881
1882    fn write(
1883        queue: &TrackQueue,
1884        frames: &[f32],
1885        frame_count: u32,
1886        channels: u32,
1887        sample_rate: f64,
1888        host_time_ns: u64,
1889        state: &AtomicUsize,
1890    ) {
1891        queue.write(
1892            frames,
1893            PacketMeta {
1894                frame_count,
1895                channels,
1896                sample_rate,
1897                host_time_ns,
1898                segment: state.load(std::sync::atomic::Ordering::Acquire) >> 2,
1899                ..PacketMeta::default()
1900            },
1901            state,
1902        );
1903    }
1904
1905    struct CaptureHarness {
1906        session: super::CaptureSession,
1907        system_audio: super::TrackCallbackContext,
1908        microphone: super::TrackCallbackContext,
1909        events: super::EventContext,
1910    }
1911
1912    impl CaptureHarness {
1913        fn new(system_channels: u32) -> Self {
1914            use std::sync::{Arc, Mutex};
1915            let state = Arc::new(AtomicUsize::new(STATE_RECORDING));
1916            let system_queue = Arc::new(TrackQueue::new());
1917            let microphone_queue = Arc::new(TrackQueue::new());
1918            let system_status = Arc::new(super::SystemAudioStatus::default());
1919            let microphone_status = Arc::new(super::MicrophoneStatus::default());
1920            *microphone_status.device_name.lock().unwrap() = Some("Initial microphone".into());
1921            let target = super::CaptureTarget::Process { pid: 123 };
1922            let capture_info = Arc::clone(system_status.capture_info.get_or_init(|| {
1923                Arc::new(Mutex::new(super::CaptureInfo {
1924                    requested_target: target,
1925                    actual_target: target,
1926                    fallback: None,
1927                    volume_dependent: false,
1928                    includes_recorder_audio: false,
1929                }))
1930            }));
1931            let events = Arc::new(super::EventQueue::default());
1932            Self {
1933                session: super::CaptureSession {
1934                    system_audio: super::AudioTrack {
1935                        sample_rate: 48_000.0,
1936                        channels: system_channels,
1937                        queue: Arc::clone(&system_queue),
1938                        availability: Arc::clone(&system_status.availability),
1939                        source: super::SystemAudio { capture_info },
1940                    },
1941                    microphone: Some(super::AudioTrack {
1942                        sample_rate: 44_100.0,
1943                        channels: 2,
1944                        queue: Arc::clone(&microphone_queue),
1945                        availability: Arc::clone(&microphone_status.availability),
1946                        source: super::Microphone {
1947                            device_name: Arc::clone(&microphone_status.device_name),
1948                        },
1949                    }),
1950                    mixed_audio: None,
1951                    control: Arc::new(super::CaptureControl {
1952                        state: Arc::clone(&state),
1953                        queues: vec![Arc::clone(&system_queue), Arc::clone(&microphone_queue)],
1954                        raw_queues: vec![Arc::clone(&system_queue), Arc::clone(&microphone_queue)],
1955                        events: Arc::clone(&events),
1956                        lifecycle: Mutex::new(()),
1957                    }),
1958                },
1959                system_audio: super::TrackCallbackContext {
1960                    queue: system_queue,
1961                    mix_queue: None,
1962                    state: Arc::clone(&state),
1963                },
1964                microphone: super::TrackCallbackContext {
1965                    queue: microphone_queue,
1966                    mix_queue: None,
1967                    state,
1968                },
1969                events: super::EventContext {
1970                    target,
1971                    queue: events,
1972                    system_audio: system_status,
1973                    microphone: microphone_status,
1974                },
1975            }
1976        }
1977
1978        fn audio(&self, track: super::Track, samples: &[f32], channels: u32, rate: f64, time: u64) {
1979            let context = match track {
1980                super::Track::SystemAudio => &self.system_audio,
1981                super::Track::Microphone => &self.microphone,
1982            };
1983            unsafe {
1984                super::audio_trampoline(
1985                    samples.as_ptr(),
1986                    (samples.len() / channels as usize) as u32,
1987                    channels,
1988                    rate,
1989                    time,
1990                    (context as *const super::TrackCallbackContext)
1991                        .cast_mut()
1992                        .cast(),
1993                );
1994            }
1995        }
1996
1997        fn event(&self, track: super::Track, kind: i32, reason: i32, device: &str, message: &str) {
1998            let mut event = super::sys::TrackEvent {
1999                track: match track {
2000                    super::Track::SystemAudio => super::sys::MREC_TRACK_SYSTEM_AUDIO,
2001                    super::Track::Microphone => super::sys::MREC_TRACK_MICROPHONE,
2002                },
2003                kind,
2004                reason,
2005                host_time_ns: 1_000_000_000,
2006                device_name: [0; 256],
2007                message: [0; 512],
2008                capture_info: unsafe { std::mem::zeroed() },
2009            };
2010            for (out, byte) in event.device_name.iter_mut().zip(device.bytes()) {
2011                *out = byte as _;
2012            }
2013            for (out, byte) in event.message.iter_mut().zip(message.bytes()) {
2014                *out = byte as _;
2015            }
2016            unsafe {
2017                super::track_event_trampoline(
2018                    &event,
2019                    (&self.events as *const super::EventContext)
2020                        .cast_mut()
2021                        .cast(),
2022                );
2023            }
2024        }
2025
2026        fn stop(&self) {
2027            self.session.control.stop_with(|| {});
2028        }
2029    }
2030
2031    #[test]
2032    fn track_events_keep_order_and_update_public_status_before_delivery() {
2033        use super::{
2034            sys::*, CaptureState, InterruptionReason::*, Track, TrackAvailability, TrackEvent,
2035        };
2036        let capture = CaptureHarness::new(1);
2037        let session = &capture.session;
2038        let system = session.system_audio();
2039        let microphone = session.microphone().unwrap();
2040        capture.event(
2041            Track::SystemAudio,
2042            MREC_TRACK_DEGRADED,
2043            MREC_TRACK_REASON_SERVICE_RESET,
2044            "",
2045            "one lost",
2046        );
2047        assert_eq!(system.availability(), TrackAvailability::Degraded);
2048        assert!(!system.is_interrupted());
2049        capture.event(
2050            Track::SystemAudio,
2051            MREC_TRACK_INTERRUPTED,
2052            MREC_TRACK_REASON_FORMAT_CHANGED,
2053            "",
2054            "all lost",
2055        );
2056        assert!(system.is_interrupted());
2057        capture.event(
2058            Track::Microphone,
2059            MREC_TRACK_INTERRUPTED,
2060            MREC_TRACK_REASON_DEVICE_CHANGED,
2061            "",
2062            "input changed",
2063        );
2064        assert!(microphone.is_interrupted());
2065        capture.event(
2066            Track::Microphone,
2067            MREC_TRACK_DEVICE_CHANGED,
2068            0,
2069            "Replacement microphone",
2070            "",
2071        );
2072        assert_eq!(
2073            microphone.device_name().as_deref(),
2074            Some("Replacement microphone")
2075        );
2076        assert!(microphone.is_interrupted());
2077        capture.event(Track::Microphone, MREC_TRACK_RESUMED, 0, "", "");
2078        assert_eq!(microphone.availability(), TrackAvailability::Live);
2079        capture.event(
2080            Track::SystemAudio,
2081            MREC_TRACK_DEGRADED,
2082            MREC_TRACK_REASON_SERVICE_RESET,
2083            "",
2084            "one recovered",
2085        );
2086        capture.event(Track::SystemAudio, MREC_TRACK_RESUMED, 0, "", "");
2087        assert_eq!(system.availability(), TrackAvailability::Live);
2088        assert_eq!(session.state(), CaptureState::Recording);
2089        let expected = [
2090            TrackEvent::Degraded {
2091                track: Track::SystemAudio,
2092                reason: ServiceReset,
2093                message: "one lost".into(),
2094            },
2095            TrackEvent::Interrupted {
2096                track: Track::SystemAudio,
2097                reason: FormatChanged,
2098                message: "all lost".into(),
2099            },
2100            TrackEvent::Interrupted {
2101                track: Track::Microphone,
2102                reason: DeviceChanged,
2103                message: "input changed".into(),
2104            },
2105            TrackEvent::DeviceChanged {
2106                device_name: "Replacement microphone".into(),
2107            },
2108            TrackEvent::Resumed {
2109                track: Track::Microphone,
2110            },
2111            TrackEvent::Degraded {
2112                track: Track::SystemAudio,
2113                reason: ServiceReset,
2114                message: "one recovered".into(),
2115            },
2116            TrackEvent::Resumed {
2117                track: Track::SystemAudio,
2118            },
2119        ];
2120        capture.stop();
2121        for event in expected {
2122            assert_eq!(session.recv_event(), Some(event));
2123        }
2124        assert_eq!(session.recv_event(), None);
2125    }
2126
2127    #[test]
2128    fn app_exit_keeps_the_microphone_and_session_available() {
2129        use super::{
2130            sys::*, CaptureState, InterruptionReason, Track, TrackAvailability, TrackEvent,
2131        };
2132        use std::sync::atomic::Ordering;
2133        let capture = CaptureHarness::new(1);
2134        capture.event(
2135            Track::SystemAudio,
2136            MREC_TRACK_INTERRUPTED,
2137            MREC_TRACK_REASON_APP_EXITED,
2138            "",
2139            "target exited",
2140        );
2141        let session = &capture.session;
2142        assert_eq!(session.state(), CaptureState::Recording);
2143        assert!(session.system_audio().is_interrupted());
2144        assert_eq!(
2145            session.microphone().unwrap().availability(),
2146            TrackAvailability::Live
2147        );
2148        assert!(!session.system_audio().queue.closed.load(Ordering::Acquire));
2149        capture.audio(
2150            Track::Microphone,
2151            &[0.25, -0.25, 0.5, -0.5],
2152            2,
2153            44_100.0,
2154            42,
2155        );
2156        capture.stop();
2157        let packet = session.microphone().unwrap().recv().unwrap();
2158        assert_eq!(packet.frames, [0.25, -0.25, 0.5, -0.5]);
2159        assert_eq!(
2160            (packet.frame_count, packet.channels, packet.sample_rate),
2161            (2, 2, 44_100.0)
2162        );
2163        assert_eq!(packet.host_time_ns, 42);
2164        assert_eq!(
2165            session.recv_event(),
2166            Some(TrackEvent::Interrupted {
2167                track: Track::SystemAudio,
2168                reason: InterruptionReason::AppExited,
2169                message: "target exited".into(),
2170            })
2171        );
2172        assert!(session.system_audio().recv().is_none());
2173        assert!(session.microphone().unwrap().recv().is_none());
2174        assert!(session.system_audio().is_interrupted());
2175    }
2176
2177    #[test]
2178    fn independent_tracks_keep_per_packet_formats_and_shared_timestamps() {
2179        use super::Track;
2180        for channels in [1, 2] {
2181            let capture = CaptureHarness::new(channels);
2182            let system_samples = vec![0.25; 2 * channels as usize];
2183            capture.audio(
2184                Track::SystemAudio,
2185                &system_samples,
2186                channels,
2187                48_000.0,
2188                1_000_000_000,
2189            );
2190            capture.audio(
2191                Track::Microphone,
2192                &[0.5, -0.5, 0.75, -0.75],
2193                2,
2194                44_100.0,
2195                1_000_000_000,
2196            );
2197            capture.audio(
2198                Track::SystemAudio,
2199                &[0.125, -0.125],
2200                2,
2201                32_000.0,
2202                2_000_000_000,
2203            );
2204            capture.stop();
2205            let system = capture.session.system_audio();
2206            let first = system.recv().unwrap();
2207            assert_eq!(first.frames, system_samples);
2208            assert_eq!(
2209                (first.frame_count, first.channels, first.sample_rate),
2210                (2, channels, 48_000.0)
2211            );
2212            let recovered = system.recv().unwrap();
2213            assert_eq!(recovered.frames, [0.125, -0.125]);
2214            assert_eq!(
2215                (
2216                    recovered.frame_count,
2217                    recovered.channels,
2218                    recovered.sample_rate
2219                ),
2220                (1, 2, 32_000.0)
2221            );
2222            assert_eq!(recovered.host_time_ns, 2_000_000_000);
2223            assert_eq!(
2224                (system.channels(), system.sample_rate()),
2225                (channels, 48_000.0)
2226            );
2227            let microphone = capture.session.microphone().unwrap().recv().unwrap();
2228            assert_eq!(
2229                (
2230                    microphone.frame_count,
2231                    microphone.channels,
2232                    microphone.sample_rate
2233                ),
2234                (2, 2, 44_100.0)
2235            );
2236            assert_eq!(microphone.host_time_ns, first.host_time_ns);
2237            assert_eq!(microphone.dropped_samples, 0);
2238        }
2239    }
2240
2241    #[test]
2242    fn silent_packets_keep_both_tracks_live_and_preserve_metadata() {
2243        use super::{CaptureState, Track, TrackAvailability};
2244        let capture = CaptureHarness::new(1);
2245        for track in [Track::SystemAudio, Track::Microphone] {
2246            capture.audio(track, &[0.0, 0.0], 1, 48_000.0, 1_120_000_000);
2247        }
2248        for track in [
2249            &capture.session.system_audio().queue,
2250            &capture.session.microphone().unwrap().queue,
2251        ] {
2252            let packet = track.recv().unwrap();
2253            assert_eq!(packet.frames, [0.0, 0.0]);
2254            assert_eq!(packet.frame_count, 2);
2255            assert_eq!(packet.channels, 1);
2256            assert_eq!(packet.sample_rate, 48_000.0);
2257            assert_eq!(packet.host_time_ns, 1_120_000_000);
2258            assert_eq!(packet.dropped_samples, 0);
2259        }
2260        assert_eq!(
2261            capture.session.system_audio().availability(),
2262            TrackAvailability::Live
2263        );
2264        assert_eq!(
2265            capture.session.microphone().unwrap().availability(),
2266            TrackAvailability::Live
2267        );
2268        assert_eq!(capture.session.state(), CaptureState::Recording);
2269        assert!(capture.session.try_recv_event().is_none());
2270        capture.stop();
2271    }
2272
2273    #[test]
2274    fn pause_excludes_both_raw_tracks_but_keeps_source_events() {
2275        use super::{sys::*, CaptureState, Track};
2276        let capture = CaptureHarness::new(1);
2277        for track in [Track::SystemAudio, Track::Microphone] {
2278            capture.audio(track, &[0.25], 1, 48_000.0, 1_000_000_000);
2279        }
2280        capture.session.pause();
2281        capture.session.pause();
2282        assert_eq!(capture.session.state(), CaptureState::Paused);
2283        for track in [Track::SystemAudio, Track::Microphone] {
2284            capture.audio(track, &[1.0], 1, 48_000.0, 2_000_000_000);
2285        }
2286        capture.event(
2287            Track::SystemAudio,
2288            MREC_TRACK_INTERRUPTED,
2289            MREC_TRACK_REASON_DEVICE_REMOVED,
2290            "",
2291            "device lost",
2292        );
2293        assert!(capture.session.system_audio().is_interrupted());
2294        assert!(capture.session.try_recv_event().is_some());
2295        capture.session.resume();
2296        capture.session.resume();
2297        for track in [Track::SystemAudio, Track::Microphone] {
2298            capture.audio(track, &[0.5], 1, 48_000.0, 60_000_000_000);
2299        }
2300        capture.stop();
2301        for track in [
2302            &capture.session.system_audio().queue,
2303            &capture.session.microphone().unwrap().queue,
2304        ] {
2305            let packet = track.recv().unwrap();
2306            assert_eq!(packet.frames, [0.5]);
2307            assert_eq!(packet.host_time_ns, 60_000_000_000);
2308            assert_eq!(packet.dropped_samples, 0);
2309            assert!(track.recv().is_none());
2310        }
2311    }
2312
2313    #[test]
2314    fn stop_drains_both_tracks_and_final_events_exactly_once() {
2315        use super::{sys::*, CaptureState, Track};
2316        use std::sync::atomic::Ordering;
2317        let capture = CaptureHarness::new(1);
2318        for track in [Track::SystemAudio, Track::Microphone] {
2319            capture.audio(track, &[0.25], 1, 48_000.0, 1_000_000_000);
2320        }
2321        let native_stops = AtomicUsize::new(0);
2322        capture.session.control.stop_with(|| {
2323            native_stops.fetch_add(1, Ordering::Relaxed);
2324            for track in [Track::SystemAudio, Track::Microphone] {
2325                capture.audio(track, &[0.5], 1, 48_000.0, 2_000_000_000);
2326            }
2327            capture.event(
2328                Track::SystemAudio,
2329                MREC_TRACK_INTERRUPTED,
2330                MREC_TRACK_REASON_APP_EXITED,
2331                "",
2332                "target exited",
2333            );
2334        });
2335        capture.session.control.stop_with(|| {
2336            native_stops.fetch_add(1, Ordering::Relaxed);
2337        });
2338        capture.session.pause();
2339        capture.session.resume();
2340        assert_eq!(native_stops.load(Ordering::Relaxed), 1);
2341        assert_eq!(capture.session.state(), CaptureState::Stopped);
2342        for track in [
2343            &capture.session.system_audio().queue,
2344            &capture.session.microphone().unwrap().queue,
2345        ] {
2346            assert_eq!(track.recv().unwrap().frames, [0.25]);
2347            assert_eq!(track.recv().unwrap().frames, [0.5]);
2348            assert!(track.recv().is_none());
2349        }
2350        assert!(capture.session.recv_event().is_some());
2351        assert!(capture.session.recv_event().is_none());
2352    }
2353
2354    #[test]
2355    fn unknown_events_do_not_change_track_status_or_enter_the_queue() {
2356        use super::{sys::*, InterruptionReason, Track, TrackAvailability, TrackEvent};
2357        let capture = CaptureHarness::new(1);
2358        capture.event(Track::Microphone, 99, 0, "unused", "unused");
2359        let invalid_track = super::sys::TrackEvent {
2360            track: 99,
2361            kind: MREC_TRACK_INTERRUPTED,
2362            reason: MREC_TRACK_REASON_DEVICE_REMOVED,
2363            host_time_ns: 0,
2364            device_name: [0; 256],
2365            message: [0; 512],
2366            capture_info: unsafe { std::mem::zeroed() },
2367        };
2368        unsafe {
2369            super::track_event_trampoline(
2370                &invalid_track,
2371                (&capture.events as *const super::EventContext)
2372                    .cast_mut()
2373                    .cast(),
2374            );
2375        }
2376        assert_eq!(
2377            capture.session.system_audio().availability(),
2378            TrackAvailability::Live
2379        );
2380        assert_eq!(
2381            capture.session.microphone().unwrap().availability(),
2382            TrackAvailability::Live
2383        );
2384        assert_eq!(
2385            capture
2386                .session
2387                .microphone()
2388                .unwrap()
2389                .device_name()
2390                .as_deref(),
2391            Some("Initial microphone")
2392        );
2393        assert!(capture.session.try_recv_event().is_none());
2394        capture.event(
2395            Track::Microphone,
2396            MREC_TRACK_INTERRUPTED,
2397            99,
2398            "",
2399            "unknown reason",
2400        );
2401        assert_eq!(
2402            capture.session.try_recv_event(),
2403            Some(TrackEvent::Interrupted {
2404                track: Track::Microphone,
2405                reason: InterruptionReason::Unknown,
2406                message: "unknown reason".into(),
2407            })
2408        );
2409        capture.stop();
2410    }
2411
2412    #[test]
2413    fn track_queue_drains_final_packets_while_producer_closes() {
2414        use std::{sync::Arc, thread};
2415
2416        for _ in 0..32 {
2417            let queue = Arc::new(TrackQueue::new());
2418            let producer = Arc::clone(&queue);
2419            let writer = thread::spawn(move || {
2420                let state = AtomicUsize::new(STATE_RECORDING);
2421                for index in 0..128 {
2422                    write(&producer, &[0.25], 1, 1, 48_000.0, index * 20_833, &state);
2423                    thread::yield_now();
2424                }
2425                producer.close();
2426                write(&producer, &[1.0], 1, 1, 48_000.0, 3_000_000, &state);
2427            });
2428            let mut frames = Vec::new();
2429            while let Some(chunk) = queue.recv() {
2430                frames.extend(chunk.frames);
2431            }
2432            writer.join().unwrap();
2433            assert_eq!(frames, vec![0.25; 128]);
2434            assert!(queue.recv().is_none());
2435        }
2436    }
2437
2438    #[test]
2439    fn track_queue_never_coalesces_across_format_changes() {
2440        let queue = TrackQueue::new();
2441        let state = AtomicUsize::new(STATE_RECORDING);
2442        write(&queue, &[1.0], 1, 1, 48_000.0, 1, &state);
2443        write(&queue, &[2.0, 3.0], 1, 2, 44_100.0, 2, &state);
2444
2445        let first = queue.recv().unwrap();
2446        assert_eq!(first.frames, [1.0]);
2447        assert_eq!(first.sample_rate, 48_000.0);
2448        assert_eq!(first.channels, 1);
2449
2450        let second = queue.recv().unwrap();
2451        assert_eq!(second.frames, [2.0, 3.0]);
2452        assert_eq!(second.frame_count, 1);
2453        assert_eq!(second.sample_rate, 44_100.0);
2454        assert_eq!(second.channels, 2);
2455        queue.close();
2456    }
2457
2458    #[test]
2459    fn track_queue_never_coalesces_across_timestamp_gaps() {
2460        let queue = TrackQueue::new();
2461        let state = AtomicUsize::new(STATE_RECORDING);
2462        write(&queue, &[1.0], 1, 1, 48_000.0, 1_000_000, &state);
2463        write(&queue, &[2.0], 1, 1, 48_000.0, 20_000_000, &state);
2464
2465        assert_eq!(queue.recv().unwrap().frames, [1.0]);
2466        assert_eq!(queue.recv().unwrap().frames, [2.0]);
2467        queue.close();
2468    }
2469
2470    #[test]
2471    fn track_queue_reports_a_drop_on_the_first_packet_after_the_gap() {
2472        let queue = TrackQueue::new();
2473        let state = AtomicUsize::new(STATE_RECORDING);
2474        write(&queue, &[1.0], 1, 1, 48_000.0, 1_000_000, &state);
2475        let oversized = vec![0.0; super::TRACK_CAPACITY + 1];
2476        write(
2477            &queue,
2478            &oversized,
2479            oversized.len() as u32,
2480            1,
2481            48_000.0,
2482            2_000_000,
2483            &state,
2484        );
2485        write(&queue, &[2.0], 1, 1, 48_000.0, 3_000_000, &state);
2486
2487        let before_gap = queue.recv().unwrap();
2488        assert_eq!(before_gap.frames, [1.0]);
2489        assert_eq!(before_gap.dropped_samples, 0);
2490        let after_gap = queue.recv().unwrap();
2491        assert_eq!(after_gap.frames, [2.0]);
2492        assert_eq!(after_gap.dropped_samples, oversized.len());
2493        assert_eq!(
2494            queue.dropped.load(std::sync::atomic::Ordering::Relaxed),
2495            oversized.len()
2496        );
2497        queue.close();
2498    }
2499
2500    #[test]
2501    fn packets_keep_pause_boundaries_and_reject_stale_callbacks() {
2502        let queue = TrackQueue::new();
2503        let state = AtomicUsize::new(STATE_RECORDING);
2504        write(&queue, &[2.0], 1, 1, 48_000.0, 0, &state);
2505        queue.clear();
2506        write(&queue, &[0.25], 1, 1, 48_000.0, 1, &state);
2507        state.store(STATE_PAUSED, std::sync::atomic::Ordering::Release);
2508        write(&queue, &[1.0], 1, 1, 48_000.0, 2, &state);
2509        state.store(4, std::sync::atomic::Ordering::Release);
2510        write(&queue, &[0.5], 1, 1, 48_000.0, 3, &state);
2511        queue.write(
2512            &[1.0],
2513            PacketMeta {
2514                frame_count: 1,
2515                channels: 1,
2516                sample_rate: 48_000.0,
2517                host_time_ns: 4,
2518                segment: 0,
2519                ..PacketMeta::default()
2520            },
2521            &state,
2522        );
2523        queue.close();
2524        let first = queue.try_recv().unwrap();
2525        let second = queue.try_recv().unwrap();
2526        assert_eq!((first.segment, first.audio.frames), (0, vec![0.25]));
2527        assert_eq!((second.segment, second.audio.frames), (1, vec![0.5]));
2528        assert!(queue.try_recv().is_none());
2529    }
2530
2531    #[test]
2532    fn native_callback_fans_out_independent_raw_and_mix_queues() {
2533        use super::{audio_trampoline, TrackCallbackContext};
2534        use std::sync::Arc;
2535        let state = Arc::new(AtomicUsize::new(STATE_RECORDING));
2536        let raw = Arc::new(TrackQueue::new());
2537        let mixed = Arc::new(TrackQueue::new());
2538        let context = TrackCallbackContext {
2539            queue: Arc::clone(&raw),
2540            mix_queue: Some(Arc::clone(&mixed)),
2541            state,
2542        };
2543        let samples = [0.25, -0.5];
2544        unsafe {
2545            audio_trampoline(
2546                samples.as_ptr(),
2547                2,
2548                1,
2549                48_000.0,
2550                42,
2551                (&context as *const TrackCallbackContext).cast_mut().cast(),
2552            );
2553        }
2554        assert_eq!(raw.try_recv().unwrap().audio.frames, samples);
2555        assert_eq!(mixed.try_recv().unwrap().audio.frames, samples);
2556        assert!(raw.try_recv().is_none());
2557        assert!(mixed.try_recv().is_none());
2558    }
2559
2560    #[test]
2561    fn stopping_retains_native_flush_callbacks_but_paused_capture_does_not() {
2562        use super::{audio_trampoline, CaptureControl, EventQueue, TrackCallbackContext};
2563        use std::sync::{Arc, Mutex};
2564        for phase in [STATE_RECORDING, STATE_PAUSED] {
2565            let state = Arc::new(AtomicUsize::new(phase));
2566            let queue = Arc::new(TrackQueue::new());
2567            let mixed = Arc::new(TrackQueue::new());
2568            let context = TrackCallbackContext {
2569                queue: queue.clone(),
2570                mix_queue: Some(mixed.clone()),
2571                state: state.clone(),
2572            };
2573            let control = CaptureControl {
2574                state,
2575                queues: vec![queue.clone(), mixed.clone()],
2576                raw_queues: vec![queue.clone()],
2577                events: Arc::new(EventQueue::default()),
2578                lifecycle: Mutex::new(()),
2579            };
2580            control.stop_with(|| unsafe {
2581                audio_trampoline(
2582                    [0.25f32, -0.5].as_ptr(),
2583                    2,
2584                    1,
2585                    48000.0,
2586                    42,
2587                    (&context as *const TrackCallbackContext).cast_mut().cast(),
2588                );
2589            });
2590            for output in [queue, mixed] {
2591                let packet = output.recv();
2592                if phase == STATE_RECORDING {
2593                    assert_eq!(packet.unwrap().frames, [0.25, -0.5]);
2594                } else {
2595                    assert!(packet.is_none());
2596                }
2597                assert!(output.recv().is_none());
2598            }
2599        }
2600    }
2601
2602    #[test]
2603    fn track_events_update_availability_and_skip_unknown_types() {
2604        use super::{
2605            sys, track_event_trampoline, EventContext, EventQueue, InterruptionReason,
2606            MicrophoneStatus, SystemAudioStatus, Track, TrackEvent,
2607        };
2608        use std::{
2609            mem,
2610            sync::{atomic::Ordering, Arc},
2611        };
2612        let context = EventContext {
2613            target: super::CaptureTarget::System,
2614            queue: Arc::new(EventQueue::default()),
2615            system_audio: Arc::new(SystemAudioStatus::default()),
2616            microphone: Arc::new(MicrophoneStatus::default()),
2617        };
2618        let publish = |kind| {
2619            let mut event: sys::TrackEvent = unsafe { mem::zeroed() };
2620            event.kind = kind;
2621            event.reason = sys::MREC_TRACK_REASON_DEVICE_REMOVED;
2622            unsafe {
2623                track_event_trampoline(&event, (&context as *const EventContext).cast_mut().cast())
2624            };
2625        };
2626        let availability = || context.system_audio.availability.load(Ordering::Acquire);
2627
2628        publish(sys::MREC_TRACK_DEGRADED);
2629        // A newer native event type leaves the track as it was.
2630        publish(99);
2631        assert_eq!(availability(), 1);
2632        assert!(matches!(
2633            context.queue.try_recv(),
2634            Some(TrackEvent::Degraded {
2635                track: Track::SystemAudio,
2636                reason: InterruptionReason::DeviceRemoved,
2637                ..
2638            })
2639        ));
2640        assert!(context.queue.try_recv().is_none());
2641
2642        publish(sys::MREC_TRACK_RESUMED);
2643        assert_eq!(availability(), 0);
2644        assert!(matches!(
2645            context.queue.try_recv(),
2646            Some(TrackEvent::Resumed {
2647                track: Track::SystemAudio
2648            })
2649        ));
2650    }
2651
2652    #[test]
2653    fn capture_path_events_update_state_without_changing_source_availability() {
2654        let capture = CaptureHarness::new(1);
2655        let mut event: super::sys::TrackEvent = unsafe { std::mem::zeroed() };
2656        event.kind = super::sys::MREC_TRACK_CAPTURE_CHANGED;
2657        event.capture_info.actual_scope = 1;
2658        event.capture_info.reason = 1;
2659        event.capture_info.volume_dependent = 1;
2660        event.capture_info.includes_recorder = 1;
2661        for (out, byte) in event
2662            .capture_info
2663            .app_id
2664            .iter_mut()
2665            .zip(b"com.microsoft.teams2")
2666        {
2667            *out = *byte as _;
2668        }
2669        unsafe {
2670            super::track_event_trampoline(
2671                &event,
2672                (&capture.events as *const super::EventContext)
2673                    .cast_mut()
2674                    .cast(),
2675            );
2676        }
2677        let info = capture.session.system_audio().capture_info();
2678        assert_eq!(info.actual_target, super::CaptureTarget::System);
2679        assert_eq!(
2680            info.requested_target,
2681            super::CaptureTarget::Process { pid: 123 }
2682        );
2683        assert!(matches!(info.fallback.as_ref(),
2684            Some(super::CaptureFallback::ProcessCaptureIncompatible { app_id })
2685            if app_id.as_deref() == Some("com.microsoft.teams2")));
2686        assert!(info.volume_dependent && info.includes_recorder_audio);
2687        assert_eq!(
2688            capture.session.try_recv_event(),
2689            Some(super::TrackEvent::CaptureChanged(info))
2690        );
2691        assert_eq!(
2692            capture.session.system_audio().availability(),
2693            super::TrackAvailability::Live
2694        );
2695    }
2696
2697    #[test]
2698    fn cancelled_requests_do_not_start_native_work() {
2699        use super::{
2700            capture, permissions, CancellationToken, CaptureOptions, CaptureTarget, Error,
2701            Permission,
2702        };
2703        use std::time::Duration;
2704        let token = CancellationToken::new();
2705        token.cancel();
2706        assert!(matches!(
2707            capture::start(
2708                CaptureTarget::System,
2709                CaptureOptions {
2710                    cancellation: Some(token.clone()),
2711                    ..CaptureOptions::default()
2712                }
2713            ),
2714            Err(Error::Cancelled)
2715        ));
2716        assert_eq!(
2717            permissions::request_and_wait(
2718                Permission::Microphone,
2719                Duration::from_secs(10),
2720                Some(&token)
2721            ),
2722            Err(Error::Cancelled)
2723        );
2724    }
2725
2726    #[test]
2727    fn zero_mix_rate_is_rejected_before_capture_starts() {
2728        use super::{capture, CaptureOptions, CaptureTarget, Error, MixedAudioOptions};
2729        assert!(matches!(
2730            capture::start(
2731                CaptureTarget::System,
2732                CaptureOptions {
2733                    mix: Some(MixedAudioOptions { sample_rate: 0 }),
2734                    ..CaptureOptions::default()
2735                }
2736            ),
2737            Err(Error::Capture(_))
2738        ));
2739    }
2740
2741    #[test]
2742    fn microphone_effects_are_independent_and_require_a_microphone() {
2743        use super::{capture, CaptureOptions, CaptureTarget, Error, MicrophoneProcessing};
2744        for mask in 0..8 {
2745            let settings = MicrophoneProcessing {
2746                echo_cancellation: mask & 1 != 0,
2747                noise_suppression: mask & 2 != 0,
2748                auto_gain_control: mask & 4 != 0,
2749            };
2750            assert_eq!(settings.flags(), mask << 8);
2751        }
2752        assert!(matches!(
2753            capture::start(
2754                CaptureTarget::System,
2755                CaptureOptions {
2756                    microphone_processing: MicrophoneProcessing {
2757                        echo_cancellation: true,
2758                        ..Default::default()
2759                    },
2760                    ..Default::default()
2761                }
2762            ),
2763            Err(Error::Capture(_))
2764        ));
2765    }
2766
2767    #[test]
2768    fn cancellation_wakes_permission_wait_without_polling_delay() {
2769        use super::{CancellationToken, Error};
2770        use std::{sync::mpsc, thread, time::Duration};
2771        let token = CancellationToken::new();
2772        let waiting = token.clone();
2773        let (send, recv) = mpsc::channel();
2774        let worker = thread::spawn(move || {
2775            send.send(waiting.wait(Duration::from_secs(60))).unwrap();
2776        });
2777        token.cancel();
2778        assert_eq!(
2779            recv.recv_timeout(Duration::from_secs(1)).unwrap(),
2780            Err(Error::Cancelled)
2781        );
2782        worker.join().unwrap();
2783    }
2784
2785    #[test]
2786    fn cancellation_stops_registered_capture_and_preserves_tail() {
2787        use super::{CancellationToken, CaptureState, Track};
2788        use std::sync::atomic::Ordering;
2789        let capture = CaptureHarness::new(1);
2790        for track in [Track::SystemAudio, Track::Microphone] {
2791            capture.audio(track, &[0.25], 1, 48_000.0, 42);
2792        }
2793        let token = CancellationToken::new();
2794        token.register(&capture.session.control).unwrap();
2795        token.cancel();
2796        token.cancel();
2797        assert_eq!(capture.session.state(), CaptureState::Stopped);
2798        for track in [
2799            &capture.session.system_audio().queue,
2800            &capture.session.microphone().unwrap().queue,
2801        ] {
2802            assert!(track.closed.load(Ordering::Acquire));
2803            assert_eq!(track.recv().unwrap().frames, [0.25]);
2804            assert!(track.recv().is_none());
2805        }
2806        capture.stop();
2807    }
2808}