kessel-audio 0.2.3

A real-time voice audio pipeline in pure Rust: devices, echo cancellation, noise suppression and gain control, Opus, jitter buffers with loss concealment, mixing and levels.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
//! The running engine: its threads, queues and the public handle.
//!
//! Threads:
//! - **device threads** (the OS's audio callbacks, or the null device's
//!   clock thread) move samples between the device and two lock-free rings;
//! - **the processing thread** (`kessel-audio-dsp`) owns [`Core`]: it
//!   resamples, runs echo cancellation, encodes, runs the jitter buffers,
//!   decodes and mixes. It never takes a lock it could wait on (snapshots
//!   are published with `try_lock`) and never blocks;
//! - **the control thread** (`kessel-audio-ctl`) opens and closes devices,
//!   watches for hot-plug, turns snapshots into events, and frees memory the
//!   processing thread hands back.

use crate::apm::Chain;
use crate::device::{CaptureIo, IoCounters, PlayIo};
use crate::error::{AudioError, ErrorCode};
use crate::events::{
    DeviceChoice, DeviceList, DeviceSelection, DevicesInUse, Event, EventRx, Levels,
};
use crate::frame::{EncodedFrame, EncoderCfg, FrameRx, RecvFrame, BLOCK_SAMPLES};
use crate::pipeline::{Core, CoreConfig, Participant, Pause};
use crate::stage::TransientEvent;
use crate::stats::Stats;
use crate::{Backend, EngineConfig};
use crossbeam_queue::ArrayQueue;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{sync_channel, SyncSender};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

pub(crate) enum Ctrl {
    Capture(bool),
    Deafen(bool),
    Encoder(EncoderCfg),
    Add(Box<Participant>),
    Remove(u64),
    CaptureIo(Option<Box<CaptureIo>>),
    PlayIo(Option<Box<PlayIo>>),
    Pause {
        why: Pause,
        on: bool,
    },
    /// Open (or extend) the capture stage's grace window.
    StageGrace(TransientEvent),
    /// Swap sonora's chain (a phone mode change); built off the processing
    /// thread.
    #[cfg_attr(
        not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )),
        allow(dead_code)
    )]
    Processing(Box<Chain>),
}

/// From the caller to the phone backend (on the control thread). Other
/// backends ignore them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PhoneCmd {
    /// The OS's audio session became active (`true`) or inactive.
    #[cfg_attr(
        not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )),
        allow(dead_code)
    )]
    Session(bool),
    /// The call was suspended (`true`) or resumed.
    #[cfg_attr(
        not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )),
        allow(dead_code)
    )]
    Suspend(bool),
    /// The OS's audio route changed.
    #[cfg_attr(
        not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )),
        allow(dead_code)
    )]
    RouteChanged,
    /// Switch between the OS's voice processing and raw capture.
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    Mode(crate::phone::PhoneMode),
}

pub(crate) enum RecvItem {
    Frame(RecvFrame),
    Lost { participant: u64, seq: u16 },
}

/// Memory the processing thread hands to the control thread to free.
pub(crate) enum Garbage {
    Participant(#[allow(dead_code)] Box<Participant>),
    Capture(#[allow(dead_code)] Box<CaptureIo>),
    Play(#[allow(dead_code)] Box<PlayIo>),
    Chain(#[allow(dead_code)] Box<Chain>),
}

pub(crate) struct DevRequest {
    pub(crate) sel: DeviceSelection,
    pub(crate) reply: SyncSender<Result<(), AudioError>>,
}

#[derive(Default)]
pub(crate) struct Snapshot {
    pub(crate) version: u64,
    pub(crate) levels: Levels,
    pub(crate) stats: Stats,
}

pub(crate) struct Shared {
    pub(crate) ctrl: ArrayQueue<Ctrl>,
    pub(crate) recv: ArrayQueue<RecvItem>,
    pub(crate) frames: Arc<ArrayQueue<EncodedFrame>>,
    pub(crate) events: Arc<ArrayQueue<Event>>,
    pub(crate) snapshot: Mutex<Snapshot>,
    pub(crate) devices: Mutex<DeviceList>,
    pub(crate) in_use: Mutex<DevicesInUse>,
    pub(crate) garbage: ArrayQueue<Garbage>,
    pub(crate) io: IoCounters,
    pub(crate) stop: AtomicBool,
    pub(crate) recv_drops: AtomicU64,
    pub(crate) dev_req: ArrayQueue<DevRequest>,
    pub(crate) phone_cmd: ArrayQueue<PhoneCmd>,
    pub(crate) core_cfg: CoreConfig,
    pub(crate) playout_buffer_ms: u32,
    #[cfg_attr(not(feature = "cpal"), allow(dead_code))]
    pub(crate) device_poll: Duration,
    /// The phone mode in use (the control thread writes it).
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub(crate) phone_mode: Mutex<crate::phone::PhoneMode>,
    /// Phone mode changes applied ([`Stats::phone_mode_switches`]).
    pub(crate) mode_switches: AtomicU64,
    /// The last restart gap for a mode change, microseconds; `u64::MAX`
    /// for none yet.
    pub(crate) last_mode_gap_us: AtomicU64,
}

/// Lock a mutex, ignoring poisoning (the data is plain state; a panic
/// elsewhere doesn't make it unusable).
pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(PoisonError::into_inner)
}

impl Shared {
    pub(crate) fn new(cfg: &EngineConfig) -> Arc<Shared> {
        let core_cfg = CoreConfig {
            processing: cfg.processing.settings(),
            encoder: cfg.encoder,
            jitter: cfg.jitter.clone(),
            initial_ts48k: cfg.initial_ts48k,
            levels_interval_ms: cfg.levels_interval_ms,
            speaking_threshold_dbov: cfg.speaking_threshold_dbov,
            max_participants: cfg.max_participants,
            stage_timing: cfg.processing.stage_timing(),
        };
        let mut snapshot = Snapshot::default();
        snapshot.levels.participants.reserve(cfg.max_participants);
        snapshot.stats.participants.reserve(cfg.max_participants);
        Arc::new(Shared {
            ctrl: ArrayQueue::new(256),
            recv: ArrayQueue::new(cfg.recv_queue_frames),
            frames: Arc::new(ArrayQueue::new(cfg.capture_queue_frames)),
            events: Arc::new(ArrayQueue::new(256)),
            snapshot: Mutex::new(snapshot),
            devices: Mutex::new(DeviceList::default()),
            in_use: Mutex::new(DevicesInUse::default()),
            garbage: ArrayQueue::new(1024),
            io: IoCounters::default(),
            stop: AtomicBool::new(false),
            recv_drops: AtomicU64::new(0),
            dev_req: ArrayQueue::new(16),
            phone_cmd: ArrayQueue::new(64),
            core_cfg,
            playout_buffer_ms: cfg.playout_buffer_ms,
            device_poll: cfg.device_poll_interval,
            #[cfg(any(
                test,
                all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
            ))]
            phone_mode: Mutex::new(cfg.phone_mode),
            mode_switches: AtomicU64::new(0),
            last_mode_gap_us: AtomicU64::new(u64::MAX),
        })
    }

    pub(crate) fn emit(&self, e: Event) {
        self.events.force_push(e);
    }

    /// Queue a control message. The queue is large and drained every few
    /// milliseconds; if it is full, wait briefly on the caller's thread.
    pub(crate) fn send_ctrl(&self, mut c: Ctrl) -> bool {
        let deadline = Instant::now() + Duration::from_secs(1);
        loop {
            match self.ctrl.push(c) {
                Ok(()) => return true,
                Err(back) => {
                    if Instant::now() >= deadline || self.stop.load(Ordering::Acquire) {
                        return false;
                    }
                    c = back;
                    std::thread::sleep(Duration::from_millis(1));
                }
            }
        }
    }

    pub(crate) fn set_in_use(&self, f: impl FnOnce(&mut DevicesInUse)) {
        let now = {
            let mut g = lock(&self.in_use);
            f(&mut g);
            g.clone()
        };
        self.emit(Event::DevicesInUse(now));
    }
}

/// A running audio engine. `Send + Sync`: share it (for example in an
/// `Arc`) between the transport's tasks. Dropping it stops the threads and
/// closes the devices.
pub struct AudioEngine {
    shared: Arc<Shared>,
    threads: Mutex<Vec<JoinHandle<()>>>,
}

impl std::fmt::Debug for AudioEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AudioEngine").finish_non_exhaustive()
    }
}

impl AudioEngine {
    /// Start the engine: open the devices and start the threads.
    ///
    /// Errors only for an invalid configuration or if the threads can't
    /// start. Device problems (no microphone, no permission, a busy device)
    /// don't stop the engine: they arrive as [`Event::Error`] on
    /// [`AudioEngine::events`], and the engine runs with whatever devices
    /// it could open.
    ///
    /// On macOS the input device opens only once the person has allowed the
    /// microphone. If they've never been asked, this shows the OS prompt
    /// without waiting for it: playback starts at once, and the input opens
    /// when they say yes ([`Event::DevicesInUse`]) or
    /// [`crate::ErrorCode::NoPermission`] arrives when they say no. The app
    /// needs `NSMicrophoneUsageDescription` in its Info.plist; without it the
    /// OS would kill the app for asking, so the engine raises
    /// [`crate::ErrorCode::NoPermission`] instead.
    pub fn start(cfg: EngineConfig) -> Result<AudioEngine, AudioError> {
        Self::start_inner(cfg, true)
    }

    /// Like [`AudioEngine::start`], but the device opens only once
    /// [`AudioEngine::session_activated`] says the OS's audio session is live.
    /// For iOS with CallKit: start the engine when the call starts, and call
    /// `session_activated` from `provider(_:didActivate:)`.
    ///
    /// Until then the engine runs without a device: no frames, and received
    /// frames are decoded on the wall clock so the jitter buffers are current
    /// when the device opens. Only `Backend::OsVoiceProcessing` defers; any
    /// other backend is [`ErrorCode::InvalidConfig`].
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub fn start_when_session_active(cfg: EngineConfig) -> Result<AudioEngine, AudioError> {
        if !cfg.backend.is_phone() {
            return Err(AudioError::new(
                ErrorCode::InvalidConfig,
                "start_when_session_active needs Backend::OsVoiceProcessing",
            ));
        }
        Self::start_inner(cfg, false)
    }

    fn start_inner(cfg: EngineConfig, session_active: bool) -> Result<AudioEngine, AudioError> {
        cfg.validate()?;
        // The OS's voice processing replaces sonora's where it can. What the
        // caller asked for is kept for mode changes.
        #[cfg(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        ))]
        let (phone_processing, phone_mode) = (cfg.phone_processing(), cfg.phone_mode);
        #[cfg(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        ))]
        let cfg = cfg.with_os_effects();
        #[cfg(not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )))]
        let _ = session_active;
        let mut cfg = cfg;
        // The stage moves to the processing thread on its own; the rest of
        // the config is shared.
        let stage = cfg.processing.capture_stage.take();
        let shared = Shared::new(&cfg);
        let core_cfg = shared.core_cfg.clone();
        let engine = AudioEngine {
            shared: shared.clone(),
            threads: Mutex::new(Vec::new()),
        };

        // The processing thread builds the core itself and reports back.
        let (ready_tx, ready_rx) = sync_channel::<Result<(), AudioError>>(1);
        let poll = cfg.processing_poll;
        let s = shared.clone();
        let dsp = std::thread::Builder::new()
            .name("kessel-audio-dsp".into())
            .spawn(move || match Core::with_stage(core_cfg, stage) {
                Ok(core) => {
                    let _ = ready_tx.send(Ok(()));
                    dsp_main(s, core, poll);
                }
                Err(e) => {
                    let _ = ready_tx.send(Err(e));
                }
            })
            .map_err(|e| AudioError::new(ErrorCode::Backend, format!("spawn: {e}")))?;
        lock(&engine.threads).push(dsp);
        match ready_rx.recv() {
            Ok(Ok(())) => {}
            Ok(Err(e)) => return Err(e),
            Err(_) => {
                return Err(AudioError::new(
                    ErrorCode::Backend,
                    "processing thread exited during start-up",
                ))
            }
        }

        let ctl_backend = match cfg.backend {
            Backend::Null(dev) => {
                let h = crate::null::start(&shared, dev)?;
                lock(&engine.threads).push(h);
                CtlBackend::Null
            }
            #[cfg(feature = "cpal")]
            Backend::System { input, output } => CtlBackend::System { input, output },
            #[cfg(all(feature = "os-voice", any(target_os = "ios", target_os = "android")))]
            Backend::OsVoiceProcessing(c) => CtlBackend::Phone {
                io: crate::phone::system_io(&c),
                session_active,
                processing: phone_processing.ok_or_else(phone_bug)?,
                mode: phone_mode,
            },
            #[cfg(test)]
            Backend::TestPhone(f) => CtlBackend::Phone {
                io: f.0,
                session_active,
                processing: phone_processing.ok_or_else(phone_bug)?,
                mode: phone_mode,
            },
        };
        let s = shared.clone();
        let ctl = std::thread::Builder::new()
            .name("kessel-audio-ctl".into())
            .spawn(move || ctl_main(s, ctl_backend))
            .map_err(|e| AudioError::new(ErrorCode::Backend, format!("spawn: {e}")))?;
        lock(&engine.threads).push(ctl);
        Ok(engine)
    }

    /// The encoded-frame queue (clones share it). See [`EncodedFrame`] for
    /// the timestamp rules.
    pub fn capture_frames(&self) -> FrameRx {
        FrameRx {
            q: self.shared.frames.clone(),
        }
    }

    /// Mute (`false`) or unmute (`true`). Muted, no frames are produced;
    /// echo cancellation keeps running so it stays converged, and `ts48k`
    /// keeps advancing.
    pub fn set_capture(&self, enabled: bool) {
        self.shared.send_ctrl(Ctrl::Capture(enabled));
    }

    /// Change the encoder settings; applies from the next frame without
    /// resetting the codec.
    pub fn set_encoder(&self, cfg: EncoderCfg) {
        self.shared.send_ctrl(Ctrl::Encoder(cfg));
    }

    /// Hand over a received frame (already decrypted and verified). Never
    /// blocks: if the receive queue is full the frame is dropped and
    /// counted in [`Stats::recv_queue_drops`].
    pub fn push(&self, f: RecvFrame) {
        if self.shared.recv.push(RecvItem::Frame(f)).is_err() {
            self.shared.recv_drops.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// The transport knows packet `seq` from `participant` is gone (for
    /// example a NACK gave up). Lets the jitter buffer conceal it at once
    /// instead of waiting.
    pub fn lost(&self, participant: u64, seq: u16) {
        if self
            .shared
            .recv
            .push(RecvItem::Lost { participant, seq })
            .is_err()
        {
            self.shared.recv_drops.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Start receiving a participant. Frames for ids that were never added
    /// are dropped (and counted). Adding an id twice is a no-op.
    pub fn add_participant(&self, id: u64) {
        match Participant::new(id, &self.shared.core_cfg) {
            Ok(p) => {
                self.shared.send_ctrl(Ctrl::Add(p));
            }
            Err(e) => self.shared.emit(Event::Error(e)),
        }
    }

    /// Stop receiving a participant and free its state.
    pub fn remove_participant(&self, id: u64) {
        self.shared.send_ctrl(Ctrl::Remove(id));
    }

    /// Stop (`true`) or resume playout. Deafened, the output and the echo
    /// reference are silent; participants are still decoded so their
    /// levels and stats stay live.
    pub fn set_deafened(&self, on: bool) {
        self.shared.send_ctrl(Ctrl::Deafen(on));
    }

    /// The host says a transient event happened: OS work that can make the
    /// capture stage's next few calls slow for reasons that aren't the
    /// stage's (the call starting, the audio session activating, a route
    /// change, the camera starting, the app changing scene). It opens the
    /// stage's grace window, or extends the open one: for the next
    /// [`ProcessingConfig::stage_grace`](crate::ProcessingConfig::stage_grace)
    /// of capture (1.5 s by default) slow calls don't count toward a strike,
    /// so the stage isn't bypassed for 10 s over a moment of scene-change
    /// noise.
    ///
    /// Nothing is hidden: the slow calls are still timed and reported in
    /// [`Stats::capture_stage`] (`grace_over_budget`, `max_block_us`,
    /// `p99_block_us`), and when a window that excused any closes,
    /// [`Event::CaptureStage`] carries the counts. The grace covers only the
    /// time budget: a fault (a panic, a NaN) bypasses the stage at once.
    ///
    /// Call it as the event starts, or just before. Never blocks: the
    /// processing thread opens the window before its next block. (If its
    /// command queue is full, the thread has stopped taking commands and
    /// the call is dropped.) Without a capture stage it does nothing. The
    /// phone backend's `session_activated` and `route_changed` open the
    /// window by themselves, and so does every capture stream start or
    /// restart.
    pub fn transient_event(&self, event: TransientEvent) {
        let _ = self.shared.ctrl.push(Ctrl::StageGrace(event));
    }

    /// Suspend the call: for hold (a cellular call), an interruption, or
    /// lost audio focus. No frames are produced and playback is silent until
    /// [`AudioEngine::resume`]; the phone backend also stops its device.
    /// Participants are still decoded, so the jitter buffers stay current.
    ///
    /// The far end sees a pause, not loss: if you were speaking, one frame of
    /// encoded silence (marked [`crate::EncodedFrame::dtx`]) ends the
    /// talkspurt, and the first frame after `resume` has a `ts48k` advanced
    /// by the suspended time (whole frames), like the end of a DTX gap. Keep
    /// the transport's sequence numbers running as usual.
    ///
    /// Works with every backend. Suspending twice is the same as once.
    pub fn suspend(&self) {
        self.set_suspended(true);
    }

    /// End a [`AudioEngine::suspend`].
    pub fn resume(&self) {
        self.set_suspended(false);
    }

    fn set_suspended(&self, on: bool) {
        self.shared.send_ctrl(Ctrl::Pause {
            why: Pause::Caller,
            on,
        });
        self.phone(PhoneCmd::Suspend(on));
    }

    fn phone(&self, cmd: PhoneCmd) {
        // The control thread drains this every 10 ms; it only fills up if
        // that thread has stopped.
        if self.shared.phone_cmd.push(cmd).is_err() {
            self.shared.emit(Event::Error(AudioError::new(
                ErrorCode::Backend,
                "the control thread is not taking commands",
            )));
        }
    }

    /// The OS's audio session is live: open the device. Call it from
    /// CallKit's `provider(_:didActivate:)` (iOS). Never blocks; the device
    /// opens on the control thread a few milliseconds later
    /// ([`Event::DevicesInUse`]).
    ///
    /// The engine never configures or activates the session itself. Only the
    /// phone backend uses this; others ignore it.
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub fn session_activated(&self) {
        self.transient_event(TransientEvent::AudioSessionActivated);
        self.phone(PhoneCmd::Session(true));
    }

    /// The OS's audio session is no longer live: close the device. Call it
    /// from CallKit's `provider(_:didDeactivate:)`. Until the session is
    /// active again no frames are produced, and the gap shows in `ts48k` as
    /// for [`AudioEngine::suspend`].
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub fn session_deactivated(&self) {
        self.phone(PhoneCmd::Session(false));
    }

    /// The OS's audio route changed (on iOS, from
    /// `AVAudioSession.routeChangeNotification`). If the device rate changed
    /// (Bluetooth hands-free runs at 16 kHz), the device reopens at the new
    /// rate without ending the call; the pipeline stays at 48 kHz. On Android
    /// the streams are always reopened on the new route.
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub fn route_changed(&self) {
        self.transient_event(TransientEvent::RouteChange);
        self.phone(PhoneCmd::RouteChanged);
    }

    /// Switch the phone backend between the OS's voice processing
    /// ([`crate::PhoneMode::Os`]) and raw capture ([`crate::PhoneMode::Raw`]:
    /// the full microphone signal with no noise suppression, echo still
    /// cancelled). For "noise removal off" on a call: call it whenever the
    /// person flips the setting. To start in raw mode, set
    /// [`EngineConfig::with_phone_mode`] instead (no restart).
    ///
    /// Never blocks. If the device is open, the control thread stops it and
    /// opens it again in the new mode a few milliseconds later; nothing
    /// else stops: participants, the jitter buffers, the encoder and the
    /// capture stage carry on, and nothing on the audio threads allocates.
    /// The capture path treats the gap like a short
    /// [`AudioEngine::suspend`] (a frame of silence ends the talkspurt, and
    /// `ts48k` jumps by the gap). [`Event::PhoneMode`] reports the change
    /// and the gap; [`Stats::phone_mode_switches`] and
    /// [`Stats::last_phone_mode_gap`] count them. sonora's echo canceller
    /// starts afresh in raw mode and takes a second or two of far-end
    /// speech to converge.
    ///
    /// If the device won't open in the new mode, the backend goes back to
    /// the old one at once (an [`Event::Error`] says why, and no
    /// [`Event::PhoneMode`] is sent). The same mode again does nothing.
    /// Other backends ignore it.
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub fn set_phone_mode(&self, mode: crate::phone::PhoneMode) {
        self.phone(PhoneCmd::Mode(mode));
    }

    /// The phone mode in use: the last [`AudioEngine::set_phone_mode`] once
    /// the control thread has applied it, or the starting mode. Other
    /// backends say [`crate::PhoneMode::Os`].
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    pub fn phone_mode(&self) -> crate::phone::PhoneMode {
        *lock(&self.shared.phone_mode)
    }

    /// The latest levels (updated about every 50 ms). [`Event::Levels`]
    /// delivers the same readings as they happen.
    pub fn levels(&self) -> Levels {
        lock(&self.shared.snapshot).levels.clone()
    }

    /// The latest statistics (updated with the levels).
    pub fn stats(&self) -> Stats {
        let mut s = lock(&self.shared.snapshot).stats.clone();
        let io = &self.shared.io;
        s.capture.capture_overruns = io.capture_overruns.load(Ordering::Relaxed);
        s.capture.playout_underruns = io.playout_underruns.load(Ordering::Relaxed);
        s.recv_queue_drops = self.shared.recv_drops.load(Ordering::Relaxed);
        s.phone_mode_switches = self.shared.mode_switches.load(Ordering::Relaxed);
        s.last_phone_mode_gap = match self.shared.last_mode_gap_us.load(Ordering::Relaxed) {
            u64::MAX => None,
            us => Some(Duration::from_micros(us)),
        };
        s
    }

    /// The available devices (kept current by hot-plug polling).
    pub fn devices(&self) -> DeviceList {
        lock(&self.shared.devices).clone()
    }

    /// The devices in use.
    pub fn devices_in_use(&self) -> DevicesInUse {
        lock(&self.shared.in_use).clone()
    }

    /// Switch devices. Waits (up to 10 s) for the new device to open.
    ///
    /// An input switch returns [`crate::ErrorCode::NoPermission`] if the
    /// microphone is refused. While the OS prompt is still up it returns
    /// `Ok` and the chosen device opens if the person says yes; see
    /// [`AudioEngine::start`].
    pub fn set_device(&self, sel: DeviceSelection) -> Result<(), AudioError> {
        let (tx, rx) = sync_channel(1);
        if self
            .shared
            .dev_req
            .push(DevRequest { sel, reply: tx })
            .is_err()
        {
            return Err(AudioError::new(
                ErrorCode::DeviceBusy,
                "too many device requests",
            ));
        }
        match rx.recv_timeout(Duration::from_secs(10)) {
            Ok(r) => r,
            Err(_) => Err(AudioError::new(
                ErrorCode::Backend,
                "device switch timed out",
            )),
        }
    }

    /// Events: device changes, errors and levels.
    pub fn events(&self) -> EventRx {
        EventRx {
            q: self.shared.events.clone(),
        }
    }

    /// Stop the threads and close the devices. Also done on drop.
    pub fn shutdown(&self) {
        self.shared.stop.store(true, Ordering::Release);
        let threads: Vec<JoinHandle<()>> = lock(&self.threads).drain(..).collect();
        for t in threads {
            let _ = t.join();
        }
    }
}

impl Drop for AudioEngine {
    fn drop(&mut self) {
        self.shutdown();
    }
}

fn dsp_main(shared: Arc<Shared>, mut core: Core, poll: Duration) {
    let mut cap: Option<Box<CaptureIo>> = None;
    let mut play: Option<Box<PlayIo>> = None;
    let mut block = [0.0f32; BLOCK_SAMPLES];
    let mut out = [0.0f32; BLOCK_SAMPLES];
    let mut soft_clock: Option<Instant> = None;
    let mut publish = false;
    // When the last capture block went through processing (a gap of more
    // than CAPTURE_GAP resets the capture stage).
    let mut last_capture: Option<Instant> = None;
    const BLOCK: Duration = Duration::from_millis(10);
    const MAX_CAPTURE_BLOCKS_PER_PASS: usize = 8;
    const CAPTURE_GAP: Duration = Duration::from_secs(1);

    while !shared.stop.load(Ordering::Acquire) {
        while let Some(c) = shared.ctrl.pop() {
            match c {
                Ctrl::Capture(on) => core.set_capture(on),
                Ctrl::Deafen(on) => core.set_deafened(on),
                Ctrl::Encoder(cfg) => {
                    if let Err(e) = core.set_encoder(cfg) {
                        shared.emit(Event::Error(e));
                    }
                }
                Ctrl::Add(p) => {
                    if let Err(p) = core.add(p) {
                        let _ = shared.garbage.push(Garbage::Participant(p));
                    }
                }
                Ctrl::Remove(id) => {
                    if let Some(p) = core.remove(id) {
                        let _ = shared.garbage.push(Garbage::Participant(p));
                    }
                }
                Ctrl::CaptureIo(c) => {
                    // A capture stream (re)starts: the stage's state carries
                    // audio from before it.
                    if c.is_some() {
                        core.reset_capture_stage();
                        last_capture = None;
                    }
                    if let Some(old) = std::mem::replace(&mut cap, c) {
                        let _ = shared.garbage.push(Garbage::Capture(old));
                    }
                }
                Ctrl::PlayIo(p) => {
                    soft_clock = None;
                    if let Some(old) = std::mem::replace(&mut play, p) {
                        let _ = shared.garbage.push(Garbage::Play(old));
                    }
                }
                Ctrl::Pause { why, on } => {
                    if let Some(f) = core.set_paused(why, on, Instant::now()) {
                        if shared.frames.push(f).is_ok() {
                            core.capture_stats.frames_sent += 1;
                        } else {
                            core.capture_stats.frames_dropped += 1;
                        }
                    }
                }
                Ctrl::Processing(chain) => {
                    let old = core.replace_processing(chain);
                    let _ = shared.garbage.push(Garbage::Chain(old));
                }
                Ctrl::StageGrace(event) => core.open_stage_grace(event),
            }
        }
        while let Some(item) = shared.recv.pop() {
            match item {
                RecvItem::Frame(f) => core.insert(f),
                RecvItem::Lost { participant, seq } => core.lost(participant, seq),
            }
        }

        let now = Instant::now();
        // Playout: keep the output ring at its target, or with no output
        // device, render on the wall clock so receive still runs.
        match play.as_mut() {
            Some(p) => {
                while p.filled() < p.target_fill {
                    core.render_block(now, &mut out);
                    match p.rs.process(&out) {
                        Ok(samples) => {
                            for &v in samples {
                                if p.tx.push(v).is_err() {
                                    break;
                                }
                            }
                        }
                        Err(_) => break,
                    }
                }
            }
            None => {
                let clk = soft_clock.get_or_insert(now);
                if now.saturating_duration_since(*clk) > Duration::from_millis(200) {
                    *clk = now;
                }
                while *clk <= now {
                    core.render_block(now, &mut out);
                    *clk += BLOCK;
                }
            }
        }

        // Capture: process the complete blocks the device has delivered, up
        // to a limit, so a thread that has fallen behind still gets back to
        // the control queue. A mute can't wait for a backlog to clear.
        if let Some(c) = cap.as_mut() {
            for _ in 0..MAX_CAPTURE_BLOCKS_PER_PASS {
                let need = c.rs.input_needed();
                if c.rx.slots() < need {
                    break;
                }
                for slot in c.buf[..need].iter_mut() {
                    *slot = c.rx.pop().unwrap_or(0.0);
                }
                if c.rs.process(&c.buf[..need], &mut block).is_err() {
                    break;
                }
                if !core.is_paused() {
                    if last_capture.is_some_and(|t| now.saturating_duration_since(t) > CAPTURE_GAP)
                    {
                        core.reset_capture_stage();
                    }
                    last_capture = Some(now);
                }
                if let Some(f) = core.capture_block(&block) {
                    if shared.frames.push(f).is_ok() {
                        core.capture_stats.frames_sent += 1;
                    } else {
                        core.capture_stats.frames_dropped += 1;
                    }
                }
            }
        }

        // A stage bypass or retry is published at once, not with the next
        // levels.
        if core.take_levels_due() | core.take_stage_changed() {
            publish = true;
        }
        if publish {
            if let Ok(mut s) = shared.snapshot.try_lock() {
                core.fill_levels(&mut s.levels);
                core.fill_stats(&mut s.stats);
                s.version += 1;
                publish = false;
            }
        }
        std::thread::sleep(poll);
    }
}

pub(crate) enum CtlBackend {
    Null,
    #[cfg(feature = "cpal")]
    System {
        input: DeviceChoice,
        output: DeviceChoice,
    },
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    Phone {
        io: Box<dyn crate::phone::PhoneIo>,
        session_active: bool,
        processing: crate::phone::Processing,
        mode: crate::phone::PhoneMode,
    },
}

/// A phone backend always has its processing settings; this is the error
/// if that ever stops being true.
#[cfg(any(
    test,
    all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
))]
fn phone_bug() -> AudioError {
    AudioError::new(
        ErrorCode::Backend,
        "phone backend without its processing settings",
    )
}

#[cfg(feature = "cpal")]
type SystemBackend = crate::system::System;

/// Without the `cpal` feature there is no system backend.
#[cfg(not(feature = "cpal"))]
enum SystemBackend {}

#[cfg(not(feature = "cpal"))]
impl SystemBackend {
    fn tick(&mut self, _: &Arc<Shared>) {
        match *self {}
    }
    fn set_device(&mut self, _: &Arc<Shared>, _: DeviceSelection) -> Result<(), AudioError> {
        match *self {}
    }
}

fn ctl_main(shared: Arc<Shared>, backend: CtlBackend) {
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    let mut phone: Option<crate::phone::Phone> = None;
    let mut system: Option<SystemBackend> = match backend {
        CtlBackend::Null => None,
        #[cfg(feature = "cpal")]
        CtlBackend::System { input, output } => {
            Some(crate::system::System::start(&shared, input, output))
        }
        #[cfg(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        ))]
        CtlBackend::Phone {
            io,
            session_active,
            processing,
            mode,
        } => {
            phone = Some(crate::phone::Phone::start(
                &shared,
                io,
                session_active,
                processing,
                mode,
            ));
            None
        }
    };

    let mut last_version = 0u64;
    let mut last_levels_seq = 0u64;
    type StageKey = (bool, Option<crate::stage::StageBypassReason>, u32, bool);
    let mut last_stage: Option<StageKey> = None;
    // `grace_over_budget` as last reported in an event, once its window had
    // closed.
    let mut reported_excused = 0u64;
    while !shared.stop.load(Ordering::Acquire) {
        while shared.garbage.pop().is_some() {}

        while let Some(req) = shared.dev_req.pop() {
            #[cfg(any(
                test,
                all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
            ))]
            if phone.is_some() {
                let _ = req.reply.send(crate::phone::check_selection(&req.sel));
                continue;
            }
            let r = match system.as_mut() {
                Some(sys) => sys.set_device(&shared, req.sel),
                None => crate::null::check_selection(&req.sel),
            };
            let _ = req.reply.send(r);
        }

        // Other backends have nothing to do with these.
        while let Some(_cmd) = shared.phone_cmd.pop() {
            #[cfg(any(
                test,
                all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
            ))]
            if let Some(p) = phone.as_mut() {
                p.command(&shared, _cmd);
            }
        }

        if let Some(sys) = system.as_mut() {
            sys.tick(&shared);
        }
        #[cfg(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        ))]
        if let Some(p) = phone.as_mut() {
            p.tick(&shared);
        }

        let (levels, stage) = {
            let g = lock(&shared.snapshot);
            if g.version == last_version {
                (None, None)
            } else {
                last_version = g.version;
                // A snapshot published for a stage change carries the same
                // levels reading: send it once.
                let levels = (g.levels.seq != last_levels_seq).then(|| {
                    last_levels_seq = g.levels.seq;
                    g.levels.clone()
                });
                (levels, g.stats.capture_stage)
            }
        };
        if let Some(l) = levels {
            shared.emit(Event::Levels(l));
        }
        if let Some(s) = stage {
            let key = (s.active, s.bypassed, s.strikes, s.permanent);
            // A closed grace window that excused slow calls is reported too.
            let excused = !s.grace && s.grace_over_budget != reported_excused;
            if last_stage != Some(key) || excused {
                // The first reading is the starting state, not a change.
                if last_stage.is_some() || !s.active || excused {
                    shared.emit(Event::CaptureStage(s));
                }
                last_stage = Some(key);
                if !s.grace {
                    reported_excused = s.grace_over_budget;
                }
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    // Close devices before the rings go away.
    #[allow(clippy::drop_non_drop)]
    drop(system);
    #[cfg(any(
        test,
        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
    ))]
    drop(phone);
    while shared.garbage.pop().is_some() {}
}

/// The default-choice helper for backends.
pub(crate) fn is_default(c: &Option<DeviceChoice>) -> bool {
    matches!(c, None | Some(DeviceChoice::Default))
}