Skip to main content

sew_call_client/
audio.rs

1//! The kessel-audio bridge (feature `audio-core`; `audio` adds the system devices): the
2//! capture path's `EncodedFrame`s go to the call's send queue (the engine encrypts them), and
3//! the call's decrypted, verified frames go to kessel-audio's `push` / `lost`, with
4//! `add_participant` first, `remove_participant` when a track ends, and the call's mute and
5//! deafen as `set_capture` / `set_deafened`.
6//!
7//! kessel-audio never sees a key or a ciphertext; the engine never touches PCM.
8//!
9//! **Phones** (iOS and Android with feature `mobile`): [`platform_audio_config`] picks
10//! kessel-audio's OS voice processing (iOS's VoiceProcessingIO unit; Android's AAudio with the
11//! voice-communication preset), with the OS's echo cancellation and noise suppression on. The
12//! phone's audio session ([`SessionEvent`]: CallKit's `didActivate` / `didDeactivate`, an
13//! interruption, a route change) reaches kessel-audio through an [`AudioSession`]. On iOS the
14//! engine starts deferred (kessel-audio's `start_when_session_active`): the microphone and the
15//! speaker open only once the session is active. The engine never configures or activates the
16//! OS's audio session (`AVAudioSession`, the Android audio mode): that is the app's job.
17//! Desktop keeps cpal, and there the session events change nothing.
18
19use std::collections::HashMap;
20use std::sync::{Arc, Mutex, MutexGuard, Weak};
21use std::time::Duration;
22
23#[cfg(feature = "audio")]
24use kessel_audio::DeviceChoice;
25use kessel_audio::{AudioEngine, EngineConfig, Level, RecvFrame};
26use tokio::task::JoinHandle;
27
28use crate::call::{Call, FrameSender, FrameStream, OpusFrame, RecvItem};
29use crate::noise::{NoiseRemoval, NoiseRemovalControl, NoiseRemovalState, PhoneAudioMode};
30use crate::stats::{PlayoutStats, PlayoutTotals};
31
32/// How often the bridge moves frames (well under one 20 ms frame).
33const TICK: Duration = Duration::from_millis(5);
34/// The noise removal state is checked every this many ticks (100 ms).
35const NOISE_TICKS: u32 = 20;
36
37/// Why the bridge could not start.
38#[derive(Debug, thiserror::Error)]
39#[non_exhaustive]
40pub enum AudioBridgeError {
41    /// The call's frame stream was already taken.
42    #[error("the call's frames are already taken")]
43    FramesTaken,
44    /// kessel-audio did not start.
45    #[error("audio: {0}")]
46    Audio(#[from] kessel_audio::AudioError),
47}
48
49/// The audio backend [`platform_audio_config`] picks in this build: `"os-voice"` (iOS and
50/// Android with feature `mobile`: the OS's own voice processing) or `"system"` (cpal).
51pub const AUDIO_BACKEND: &str = if PHONE_AUDIO { "os-voice" } else { "system" };
52
53/// This build drives kessel-audio's phone backend (iOS or Android, feature `mobile`).
54pub(crate) const PHONE_AUDIO: bool = cfg!(all(
55    feature = "mobile",
56    any(target_os = "ios", target_os = "android")
57));
58
59/// The kessel-audio config for a call on this platform's audio.
60///
61/// - **iOS and Android** (feature `mobile`): `Backend::OsVoiceProcessing`, with the OS's echo
62///   cancellation, noise suppression and gain control on (kessel-audio's own processing then
63///   runs none of them). A call whose audio starts in [`NoiseRemoval::Off`]
64///   ([`AudioBridge::start_with_noise`]) captures raw instead ([`crate::PhoneAudioMode::Raw`]:
65///   no OS processing; kessel-audio cancels echo and controls gain, with no noise
66///   suppression), and a change of the setting during the call switches between the two.
67///   `input` and `output` are ignored: the OS owns the route. Start it with
68///   [`AudioBridge::start_with_session`] and report the phone's audio session to the
69///   [`AudioSession`]; on iOS nothing opens until [`SessionEvent::Activated`].
70/// - **Desktop:** the system's devices through cpal (`Backend::System { input, output }`).
71///
72/// - **Noise removal** (desktop): Standard, a `sew-noise` stage in kessel-audio's capture hook
73///   between echo cancellation and gain control, with kessel-audio's own noise suppression off.
74///   To change it or read its state, start the call's audio with
75///   [`AudioBridge::start_with_noise`] (which builds its own stage from the
76///   [`NoiseRemovalControl`]). While kessel-audio bypasses the stage (over its time budget, or
77///   a fault) its own noise suppression stands in. A frame's `ts48k` does not include the
78///   stage's 10 ms: its audio is 480 samples older than its stamp.
79///
80/// Everything else is kessel-audio's default.
81#[cfg(feature = "audio")]
82pub fn platform_audio_config(input: DeviceChoice, output: DeviceChoice) -> EngineConfig {
83    let cfg = platform_devices(input, output);
84    NoiseRemovalControl::default().configure(cfg).0
85}
86
87#[cfg(feature = "audio")]
88pub(crate) fn platform_devices(input: DeviceChoice, output: DeviceChoice) -> EngineConfig {
89    #[cfg(all(feature = "mobile", any(target_os = "ios", target_os = "android")))]
90    {
91        let _ = (input, output);
92        EngineConfig::default().with_backend(kessel_audio::Backend::OsVoiceProcessing(
93            kessel_audio::OsVoiceConfig {
94                os_effects: kessel_audio::OsEffects {
95                    echo_cancellation: true,
96                    noise_suppression: true,
97                    gain_control: true,
98                },
99            },
100        ))
101    }
102    #[cfg(not(all(feature = "mobile", any(target_os = "ios", target_os = "android"))))]
103    {
104        EngineConfig::default().with_backend(kessel_audio::Backend::System { input, output })
105    }
106}
107
108/// Which phone OS the phone backend runs on ([`phone_start`]).
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub(crate) enum PhoneOs {
111    Ios,
112    Android,
113}
114
115/// The phone OS of this build: `None` off phones (and without feature `mobile`).
116pub(crate) const PHONE_OS: Option<PhoneOs> = if !PHONE_AUDIO {
117    None
118} else if cfg!(target_os = "android") {
119    Some(PhoneOs::Android)
120} else {
121    Some(PhoneOs::Ios)
122};
123
124/// How a phone's microphone is to be captured: the capture, and for raw on Android whether
125/// the device's unprocessed source may be used (else its voice recognition source).
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub(crate) struct PhoneStart {
128    pub(crate) mode: PhoneAudioMode,
129    pub(crate) unprocessed: bool,
130}
131
132/// The capture for `mode` on `os`: raw for Off (with the unprocessed source on Android when
133/// the app says the device supports it), the OS's voice processing for Standard. The OS
134/// effects stay all on in the config: raw capture ignores them.
135pub(crate) fn phone_start(
136    os: PhoneOs,
137    mode: NoiseRemoval,
138    unprocessed_supported: bool,
139) -> PhoneStart {
140    let mode = PhoneAudioMode::for_mode(mode);
141    PhoneStart {
142        mode,
143        unprocessed: mode == PhoneAudioMode::Raw && os == PhoneOs::Android && unprocessed_supported,
144    }
145}
146
147/// kessel-audio's phone mode for `start`.
148#[cfg(all(feature = "mobile", any(target_os = "ios", target_os = "android")))]
149pub(crate) fn kessel_phone_mode(start: PhoneStart) -> kessel_audio::PhoneMode {
150    match start.mode {
151        PhoneAudioMode::Raw => kessel_audio::PhoneMode::Raw(
152            kessel_audio::RawCapture::default().with_unprocessed_supported(start.unprocessed),
153        ),
154        PhoneAudioMode::Os => kessel_audio::PhoneMode::Os,
155    }
156}
157
158/// Sew's name for kessel-audio's phone mode.
159#[cfg(all(feature = "mobile", any(target_os = "ios", target_os = "android")))]
160pub(crate) fn phone_audio_mode(mode: kessel_audio::PhoneMode) -> PhoneAudioMode {
161    if mode.is_raw() {
162        PhoneAudioMode::Raw
163    } else {
164        PhoneAudioMode::Os
165    }
166}
167
168/// A call's audio is about to start in `mode`: on a phone backend its starting capture follows
169/// the setting ([`phone_start`]), so a call that starts in Off opens raw with no restart.
170/// Answers the capture set, or `None` (desktop, or a config without the phone backend: nothing
171/// changes).
172pub(crate) fn apply_phone_mode(
173    cfg: &mut EngineConfig,
174    mode: NoiseRemoval,
175    unprocessed_supported: bool,
176) -> Option<PhoneAudioMode> {
177    #[cfg(all(feature = "mobile", any(target_os = "ios", target_os = "android")))]
178    if let Some(os) = PHONE_OS
179        && matches!(cfg.backend, kessel_audio::Backend::OsVoiceProcessing(_))
180    {
181        let start = phone_start(os, mode, unprocessed_supported);
182        cfg.phone_mode = kessel_phone_mode(start);
183        return Some(start.mode);
184    }
185    let _ = (cfg, mode, unprocessed_supported);
186    None
187}
188
189/// The phone's audio session, as the app reports it (CallKit on iOS, Telecom or the app's own
190/// audio focus on Android), for [`AudioSession::event`].
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
192#[non_exhaustive]
193pub enum SessionEvent {
194    /// The OS's audio session is active (CallKit's `provider(_:didActivate:)`): kessel-audio
195    /// opens the microphone and the speaker.
196    Activated,
197    /// The session is no longer active (`didDeactivate`): I/O stops; the call goes on.
198    Deactivated,
199    /// An interruption began (a cellular call, hold, lost audio focus): I/O pauses; the call
200    /// goes on and the far end hears a pause, not loss.
201    Suspend,
202    /// The interruption ended: I/O restarts.
203    Resume,
204    /// The OS audio route changed (speaker, earpiece, Bluetooth): kessel-audio re-reads the
205    /// device and reopens it if its rate changed (always on Android).
206    RouteChanged,
207}
208
209/// The phone's audio session state, shared between the app's reports and the call's audio
210/// (one per app; clones share it). It keeps what the app said before a call's audio started
211/// (CallKit may activate the session before the join has a call) and hands it to the next
212/// [`AudioBridge::start_with_session`]:
213///
214/// - **Activated / Deactivated** are kept across calls (they are the OS's state). On iOS a
215///   bridge starts deferred and opens its device when the session is (or becomes) active; on
216///   Android it opens at once, and a later `Deactivated` closes it.
217/// - **Suspend / Resume** are kept until the call's audio ends: a `Suspend` before the audio
218///   starts pauses it from the start; a bridge that ends clears it.
219/// - **RouteChanged** goes to the live bridge only (a new bridge reads the route anyway).
220/// - A repeated event (a second `Activated`, `Resume` without `Suspend`) is passed on once.
221///
222/// On desktop the events change nothing (the system backend has no session); the state is
223/// still kept.
224#[derive(Clone, Default)]
225pub struct AudioSession {
226    inner: Arc<Mutex<SessionState>>,
227}
228
229impl std::fmt::Debug for AudioSession {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        let st = self.lock();
232        f.debug_struct("AudioSession")
233            .field("active", &st.active)
234            .field("suspended", &st.suspended)
235            .field("attached", &st.attached.is_some())
236            .finish()
237    }
238}
239
240#[derive(Default)]
241struct SessionState {
242    /// `None` until the app first says.
243    active: Option<bool>,
244    suspended: bool,
245    next_id: u64,
246    attached: Option<Attached>,
247}
248
249struct Attached {
250    id: u64,
251    sink: Weak<dyn SessionSink>,
252}
253
254/// Where the session events go: kessel-audio's engine (the phone backend's calls), or a test's
255/// recorder.
256pub(crate) trait SessionSink: Send + Sync {
257    fn apply(&self, event: SessionEvent);
258}
259
260impl SessionSink for AudioEngine {
261    fn apply(&self, event: SessionEvent) {
262        #[cfg(all(feature = "mobile", any(target_os = "ios", target_os = "android")))]
263        match event {
264            SessionEvent::Activated => self.session_activated(),
265            SessionEvent::Deactivated => self.session_deactivated(),
266            SessionEvent::Suspend => self.suspend(),
267            SessionEvent::Resume => self.resume(),
268            SessionEvent::RouteChanged => self.route_changed(),
269        }
270        // Desktop: the system backend has no session; nothing changes.
271        #[cfg(not(all(feature = "mobile", any(target_os = "ios", target_os = "android"))))]
272        let _ = event;
273    }
274}
275
276/// A bridge's session sink: the call's noise removal hears an event first (an activation, a
277/// resume or a route change opens its stage's grace window before the device reopens), then
278/// kessel-audio's engine.
279pub(crate) struct BridgeSink {
280    pub(crate) engine: Weak<AudioEngine>,
281    pub(crate) noise: Option<(NoiseRemovalControl, u64)>,
282}
283
284impl SessionSink for BridgeSink {
285    fn apply(&self, event: SessionEvent) {
286        if let Some((noise, id)) = &self.noise {
287            noise.session_event(*id, event);
288        }
289        if let Some(engine) = self.engine.upgrade() {
290            engine.apply(event);
291        }
292    }
293}
294
295impl AudioSession {
296    /// A new session state (nothing reported yet).
297    pub fn new() -> AudioSession {
298        AudioSession::default()
299    }
300
301    fn lock(&self) -> MutexGuard<'_, SessionState> {
302        self.inner.lock().unwrap_or_else(|p| p.into_inner())
303    }
304
305    /// The app's report. Never blocks (kessel-audio acts on its control thread).
306    pub fn event(&self, event: SessionEvent) {
307        let mut guard = self.lock();
308        let st = &mut *guard;
309        let changed = match event {
310            SessionEvent::Activated => st.active.replace(true) != Some(true),
311            SessionEvent::Deactivated => st.active.replace(false) != Some(false),
312            SessionEvent::Suspend => !std::mem::replace(&mut st.suspended, true),
313            SessionEvent::Resume => std::mem::replace(&mut st.suspended, false),
314            SessionEvent::RouteChanged => true,
315        };
316        if !changed {
317            return;
318        }
319        if let Some(sink) = st.attached.as_ref().and_then(|a| a.sink.upgrade()) {
320            sink.apply(event);
321        }
322    }
323
324    /// What the app last said: active (`Some(true)`), not active, or `None` if it never said.
325    pub fn is_active(&self) -> Option<bool> {
326        self.lock().active
327    }
328
329    /// An interruption is going on ([`SessionEvent::Suspend`] without a `Resume` yet).
330    pub fn is_suspended(&self) -> bool {
331        self.lock().suspended
332    }
333
334    /// A call's audio starts: it takes the events from now on (replacing any earlier one).
335    /// `deferred`: its device waits for the session (iOS), so an active session is replayed.
336    pub(crate) fn attach(&self, sink: Weak<dyn SessionSink>, deferred: bool) -> u64 {
337        let mut guard = self.lock();
338        let st = &mut *guard;
339        st.next_id += 1;
340        let id = st.next_id;
341        if let Some(s) = sink.upgrade() {
342            if deferred && st.active == Some(true) {
343                s.apply(SessionEvent::Activated);
344            }
345            if st.suspended {
346                s.apply(SessionEvent::Suspend);
347            }
348        }
349        st.attached = Some(Attached { id, sink });
350        id
351    }
352
353    /// The call's audio `id` ended: the events stop reaching it, and its interruption is over.
354    pub(crate) fn detach(&self, id: u64) {
355        let mut guard = self.lock();
356        let st = &mut *guard;
357        if st.attached.as_ref().is_some_and(|a| a.id == id) {
358            st.attached = None;
359            st.suspended = false;
360        }
361    }
362}
363
364/// A running bridge between one call and a kessel-audio engine.
365pub struct AudioBridge {
366    engine: Arc<AudioEngine>,
367    identities: Identities,
368    task: JoinHandle<()>,
369    session: AudioSession,
370    session_id: u64,
371    /// The noise removal this call's audio started with, and the call's id there.
372    noise: Option<(NoiseRemovalControl, u64)>,
373    /// The session's sink for this call (the session holds it weakly).
374    _sink: Arc<BridgeSink>,
375}
376
377/// kessel-audio's participant ids → the publishers' engine identities.
378type Identities = Arc<Mutex<HashMap<u64, String>>>;
379
380/// kessel-audio's latest levels (about every 50 ms) by engine identity
381/// ([`AudioBridge::levels`]).
382#[derive(Clone, Debug, Default, PartialEq)]
383#[non_exhaustive]
384pub struct BridgeLevels {
385    /// This device's processed capture (silent while muted).
386    pub local: Level,
387    /// Each remote track's decoded audio, by its publisher's engine identity.
388    pub remotes: Vec<(String, Level)>,
389}
390
391impl std::fmt::Debug for AudioBridge {
392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393        f.debug_struct("AudioBridge").finish_non_exhaustive()
394    }
395}
396
397impl Drop for AudioBridge {
398    fn drop(&mut self) {
399        self.session.detach(self.session_id);
400        self.task.abort();
401        self.engine.shutdown();
402        if let Some((noise, id)) = &self.noise {
403            noise.detach(*id);
404        }
405    }
406}
407
408impl AudioBridge {
409    /// Starts kessel-audio with `cfg` and bridges it to `call` (on the current tokio runtime),
410    /// with a session state of its own ([`AudioBridge::session`]). A phone host keeps one
411    /// [`AudioSession`] for the app instead: [`AudioBridge::start_with_session`].
412    pub fn start(call: &Call, cfg: EngineConfig) -> Result<AudioBridge, AudioBridgeError> {
413        AudioBridge::start_with_session(call, cfg, &AudioSession::new())
414    }
415
416    /// As [`AudioBridge::start`], with the app's [`AudioSession`]: what the app reported before
417    /// this call (an active session, an interruption) applies from the start, and its reports
418    /// reach this call's kessel-audio until the bridge is dropped. On iOS with the phone
419    /// backend the engine starts deferred (`start_when_session_active`): nothing opens until the
420    /// session is active.
421    pub fn start_with_session(
422        call: &Call,
423        cfg: EngineConfig,
424        session: &AudioSession,
425    ) -> Result<AudioBridge, AudioBridgeError> {
426        AudioBridge::start_inner(call, cfg, session, None)
427    }
428
429    /// As [`AudioBridge::start_with_session`], with noise removal from `noise` (the app's
430    /// setting; keep one [`NoiseRemovalControl`] for the app): the call's capture stage is built
431    /// in its mode and handed to kessel-audio (whose own noise suppression is then off), in
432    /// place of any stage `cfg` carries. While the bridge runs, [`NoiseRemovalControl::set`]
433    /// changes the mode from the next 10 ms block without a click, its state follows the
434    /// pipeline (a bypass for time or a fault steps it down), and the call's stats windows
435    /// carry it ([`crate::stats::StatsWindow::noise_removal`]).
436    pub fn start_with_noise(
437        call: &Call,
438        cfg: EngineConfig,
439        session: &AudioSession,
440        noise: &NoiseRemovalControl,
441    ) -> Result<AudioBridge, AudioBridgeError> {
442        let (cfg, id) = noise.configure(cfg);
443        AudioBridge::start_inner(call, cfg, session, Some((noise.clone(), id))).inspect_err(|_| {
444            noise.detach(id);
445        })
446    }
447
448    fn start_inner(
449        call: &Call,
450        cfg: EngineConfig,
451        session: &AudioSession,
452        noise: Option<(NoiseRemovalControl, u64)>,
453    ) -> Result<AudioBridge, AudioBridgeError> {
454        let frames = call.frames().ok_or(AudioBridgeError::FramesTaken)?;
455        let (engine, deferred) = start_call_engine(cfg)?;
456        let engine = Arc::new(engine);
457        // The noise removal first: a change of the setting since `configure` reaches the
458        // phone's capture before the session's replayed `Activated` opens the device (iOS), so
459        // the device opens once, in the mode asked.
460        if let Some((control, id)) = &noise {
461            let weak: Weak<_> = Arc::downgrade(&engine);
462            let source: Weak<dyn crate::noise::LiveAudio> = weak;
463            control.attach(*id, source);
464            call.set_noise_source(control.source(*id));
465        }
466        let bridge_sink = Arc::new(BridgeSink {
467            engine: Arc::downgrade(&engine),
468            noise: noise.clone(),
469        });
470        let weak: Weak<BridgeSink> = Arc::downgrade(&bridge_sink);
471        let sink: Weak<dyn SessionSink> = weak;
472        let session_id = session.attach(sink, deferred);
473        // The beacon's played and concealed audio are kessel-audio's own counters.
474        call.set_playout_stats(Arc::new(KesselPlayout(Arc::downgrade(&engine))));
475        let identities = Identities::default();
476        let task = tokio::spawn(bridge(
477            engine.clone(),
478            identities.clone(),
479            call.frame_sender(),
480            frames,
481            noise.as_ref().map(|(c, _)| c.clone()),
482        ));
483        Ok(AudioBridge {
484            engine,
485            identities,
486            task,
487            session: session.clone(),
488            session_id,
489            noise,
490            _sink: bridge_sink,
491        })
492    }
493
494    /// The noise removal state of this call's audio ([`AudioBridge::start_with_noise`]);
495    /// `None` for a bridge started without it.
496    pub fn noise_removal(&self) -> Option<NoiseRemovalState> {
497        self.noise.as_ref().map(|(c, _)| c.state())
498    }
499
500    /// kessel-audio's events since the last read: the engine's queue
501    /// (`engine().events()`), drained. Read them here rather than from the engine: the
502    /// bridge looks at each on the way (an error while the phone's capture is switching means
503    /// the switch failed: [`NoiseRemovalState::phone_mode_reason`]; a change of the devices
504    /// in use opens the noise removal stage's grace window,
505    /// [`NoiseRemovalState::in_grace`]) and hands every one on.
506    pub fn events(&self) -> Vec<kessel_audio::Event> {
507        let rx = self.engine.events();
508        let mut out = Vec::new();
509        while let Some(e) = rx.try_recv() {
510            match (&e, &self.noise) {
511                (kessel_audio::Event::Error(_), Some((noise, id))) => noise.audio_error(*id),
512                // The streams reopened on other devices: the stage's grace window.
513                (kessel_audio::Event::DevicesInUse(_), Some((noise, id))) => {
514                    noise.devices_changed(*id);
515                }
516                _ => {}
517            }
518            out.push(e);
519        }
520        out
521    }
522
523    /// The session state this bridge takes its events from.
524    pub fn session(&self) -> &AudioSession {
525        &self.session
526    }
527
528    /// The kessel-audio engine (levels, stats, devices).
529    pub fn engine(&self) -> &AudioEngine {
530        &self.engine
531    }
532
533    /// kessel-audio's latest levels, the remote ones by engine identity (a track whose
534    /// identity the bridge has not seen yet is left out).
535    pub fn levels(&self) -> BridgeLevels {
536        let levels = self.engine.levels();
537        let ids = self
538            .identities
539            .lock()
540            .map(|m| m.clone())
541            .unwrap_or_default();
542        BridgeLevels {
543            local: levels.local,
544            remotes: levels
545                .participants
546                .iter()
547                .filter_map(|(p, l)| ids.get(p).map(|i| (i.clone(), *l)))
548                .collect(),
549        }
550    }
551}
552
553/// Starts kessel-audio; `true` when it waits for the session (iOS's phone backend).
554pub(crate) fn start_engine(
555    cfg: EngineConfig,
556) -> Result<(AudioEngine, bool), kessel_audio::AudioError> {
557    #[cfg(all(feature = "mobile", target_os = "ios"))]
558    if matches!(cfg.backend, kessel_audio::Backend::OsVoiceProcessing(_)) {
559        return Ok((AudioEngine::start_when_session_active(cfg)?, true));
560    }
561    Ok((AudioEngine::start(cfg)?, false))
562}
563
564/// [`start_engine`] for a call's capture (a join or a rejoin): the device is busy for a
565/// moment, so the pipeline also holds its timing rule for the noise removal stage back
566/// (kessel-audio's `TransientEvent::CallStart`; nothing without a stage).
567pub(crate) fn start_call_engine(
568    cfg: EngineConfig,
569) -> Result<(AudioEngine, bool), kessel_audio::AudioError> {
570    let (engine, deferred) = start_engine(cfg)?;
571    engine.transient_event(kessel_audio::TransientEvent::CallStart);
572    Ok((engine, deferred))
573}
574
575/// kessel-audio's per-participant playout counters for the stats windows (none once the
576/// bridge is gone).
577struct KesselPlayout(Weak<AudioEngine>);
578
579impl PlayoutStats for KesselPlayout {
580    fn playout_totals(&self) -> Vec<(u64, PlayoutTotals)> {
581        let Some(engine) = self.0.upgrade() else {
582            return Vec::new();
583        };
584        engine
585            .stats()
586            .participants
587            .iter()
588            .map(|(id, p)| {
589                (
590                    *id,
591                    PlayoutTotals::new(p.frames_decoded, p.frames_fec, p.frames_concealed),
592                )
593            })
594            .collect()
595    }
596}
597
598async fn bridge(
599    engine: Arc<AudioEngine>,
600    identities: Identities,
601    send: FrameSender,
602    mut frames: FrameStream,
603    noise: Option<NoiseRemovalControl>,
604) {
605    let capture = engine.capture_frames();
606    let mut tick = tokio::time::interval(TICK);
607    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
608    let mut ticks = 0u32;
609    loop {
610        tick.tick().await;
611        ticks = ticks.wrapping_add(1);
612        if let Some(n) = &noise
613            && ticks.is_multiple_of(NOISE_TICKS)
614        {
615            // Sends a `NoiseRemovalControl::subscribe` event when the state changed.
616            n.publish();
617        }
618        while let Some(f) = capture.try_recv() {
619            send.push_opus(OpusFrame {
620                payload: f.payload,
621                ts48k: f.ts48k,
622                vad: f.vad,
623                level_dbov: f.level_dbov,
624            });
625        }
626        loop {
627            match frames.0.try_recv() {
628                Ok(item) => apply(&engine, &identities, item),
629                Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break,
630                Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => return,
631            }
632        }
633    }
634}
635
636fn apply(engine: &AudioEngine, identities: &Identities, item: RecvItem) {
637    match item {
638        RecvItem::Added {
639            participant,
640            identity,
641        } => {
642            if let Ok(mut m) = identities.lock() {
643                m.insert(participant, identity);
644            }
645            engine.add_participant(participant);
646        }
647        RecvItem::Removed { participant } => {
648            if let Ok(mut m) = identities.lock() {
649                m.remove(&participant);
650            }
651            engine.remove_participant(participant);
652        }
653        RecvItem::Frame(f) => engine.push(RecvFrame {
654            participant: f.participant,
655            payload: f.payload,
656            seq: f.seq,
657            ts48k: f.ts48k,
658            arrival: f.arrival,
659        }),
660        RecvItem::Lost { participant, seq } => engine.lost(participant, seq),
661        RecvItem::Capture(on) => engine.set_capture(on),
662        RecvItem::Deafened(on) => engine.set_deafened(on),
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    #![allow(clippy::unwrap_used, clippy::expect_used)]
669    use super::*;
670
671    use SessionEvent::{Activated, Deactivated, Resume, RouteChanged, Suspend};
672    use kessel_audio::{CaptureSource, NullDevice, ProcessingConfig};
673
674    /// A call's starting capture per mode and phone OS: Off is raw (on Android with the
675    /// unprocessed source only when the app says the device has it; iOS ignores the flag),
676    /// Standard the OS's voice processing.
677    #[test]
678    fn the_starting_capture_follows_the_mode() {
679        let raw = |unprocessed| PhoneStart {
680            mode: PhoneAudioMode::Raw,
681            unprocessed,
682        };
683        let os = PhoneStart {
684            mode: PhoneAudioMode::Os,
685            unprocessed: false,
686        };
687        for (phone, mode, supported, want) in [
688            (PhoneOs::Android, NoiseRemoval::Off, true, raw(true)),
689            (PhoneOs::Android, NoiseRemoval::Off, false, raw(false)),
690            (PhoneOs::Ios, NoiseRemoval::Off, true, raw(false)),
691            (PhoneOs::Ios, NoiseRemoval::Off, false, raw(false)),
692            (PhoneOs::Android, NoiseRemoval::Standard, true, os),
693            (PhoneOs::Android, NoiseRemoval::Standard, false, os),
694            (PhoneOs::Ios, NoiseRemoval::Standard, true, os),
695            (PhoneOs::Ios, NoiseRemoval::Standard, false, os),
696        ] {
697            assert_eq!(
698                phone_start(phone, mode, supported),
699                want,
700                "{phone:?} {mode:?} unprocessed={supported}"
701            );
702        }
703    }
704
705    /// Desktop (and any config without the phone backend): the config is untouched in every
706    /// mode, kessel-audio's own processing included.
707    #[test]
708    fn desktop_config_is_untouched_by_the_mode() {
709        assert_eq!(PHONE_OS, None);
710        for mode in NoiseRemoval::ALL {
711            let mut cfg = EngineConfig::default();
712            let (ns, fallback) = (
713                cfg.processing.noise_suppression,
714                cfg.processing.stage_fallback_noise_suppression,
715            );
716            assert_eq!(apply_phone_mode(&mut cfg, mode, true), None);
717            assert_eq!(cfg.processing.noise_suppression, ns, "{mode:?}");
718            assert_eq!(
719                cfg.processing.stage_fallback_noise_suppression, fallback,
720                "{mode:?}"
721            );
722        }
723    }
724
725    /// Records what reaches "kessel-audio", in order.
726    #[derive(Default)]
727    struct Recorder(Mutex<Vec<SessionEvent>>);
728
729    impl SessionSink for Recorder {
730        fn apply(&self, event: SessionEvent) {
731            self.0.lock().unwrap().push(event);
732        }
733    }
734
735    impl Recorder {
736        fn take(&self) -> Vec<SessionEvent> {
737            std::mem::take(&mut *self.0.lock().unwrap())
738        }
739    }
740
741    fn attach(session: &AudioSession, deferred: bool) -> (Arc<Recorder>, u64) {
742        let rec = Arc::new(Recorder::default());
743        let weak: Weak<_> = Arc::downgrade(&rec);
744        let sink: Weak<dyn SessionSink> = weak;
745        let id = session.attach(sink, deferred);
746        (rec, id)
747    }
748
749    #[test]
750    fn events_before_the_call_are_replayed_on_a_deferred_start() {
751        let s = AudioSession::new();
752        // CallKit activates the session before the join has a call; a route change then is
753        // the new bridge's to read.
754        s.event(Activated);
755        s.event(RouteChanged);
756        assert_eq!(s.is_active(), Some(true));
757        let (rec, _id) = attach(&s, true);
758        assert_eq!(rec.take(), vec![Activated]);
759        // Live from now on.
760        s.event(RouteChanged);
761        s.event(Deactivated);
762        assert_eq!(rec.take(), vec![RouteChanged, Deactivated]);
763    }
764
765    #[test]
766    fn a_deferred_start_waits_for_the_session() {
767        let s = AudioSession::new();
768        let (rec, _id) = attach(&s, true);
769        // Never said: nothing opens.
770        assert_eq!(rec.take(), vec![]);
771        assert_eq!(s.is_active(), None);
772        s.event(Activated);
773        assert_eq!(rec.take(), vec![Activated]);
774    }
775
776    #[test]
777    fn a_deactivated_session_is_not_replayed_as_active() {
778        let s = AudioSession::new();
779        s.event(Activated);
780        s.event(Deactivated);
781        let (rec, _id) = attach(&s, true);
782        assert_eq!(rec.take(), vec![]);
783        s.event(Activated);
784        assert_eq!(rec.take(), vec![Activated]);
785    }
786
787    #[test]
788    fn an_immediate_start_is_not_told_activated_again() {
789        // Android: the engine opens at once; an earlier Activated is not replayed.
790        let s = AudioSession::new();
791        s.event(Activated);
792        let (rec, _id) = attach(&s, false);
793        assert_eq!(rec.take(), vec![]);
794        s.event(Deactivated);
795        s.event(Activated);
796        assert_eq!(rec.take(), vec![Deactivated, Activated]);
797    }
798
799    #[test]
800    fn a_double_activated_is_passed_on_once() {
801        let s = AudioSession::new();
802        let (rec, _id) = attach(&s, true);
803        s.event(Activated);
804        s.event(Activated);
805        s.event(Deactivated);
806        s.event(Deactivated);
807        s.event(Activated);
808        assert_eq!(rec.take(), vec![Activated, Deactivated, Activated]);
809    }
810
811    #[test]
812    fn suspend_then_resume_in_order_and_once_each() {
813        let s = AudioSession::new();
814        let (rec, _id) = attach(&s, true);
815        s.event(Activated);
816        s.event(Suspend);
817        s.event(Suspend);
818        assert!(s.is_suspended());
819        s.event(Resume);
820        s.event(Resume);
821        assert!(!s.is_suspended());
822        assert_eq!(rec.take(), vec![Activated, Suspend, Resume]);
823    }
824
825    #[test]
826    fn a_suspend_before_the_call_pauses_it_from_the_start() {
827        let s = AudioSession::new();
828        s.event(Activated);
829        s.event(Suspend);
830        let (rec, _id) = attach(&s, true);
831        assert_eq!(rec.take(), vec![Activated, Suspend]);
832        s.event(Resume);
833        assert_eq!(rec.take(), vec![Resume]);
834    }
835
836    #[test]
837    fn an_ended_call_gets_nothing_and_its_interruption_ends() {
838        let s = AudioSession::new();
839        let (first, id) = attach(&s, true);
840        s.event(Activated);
841        s.event(Suspend);
842        assert_eq!(first.take(), vec![Activated, Suspend]);
843        s.detach(id);
844        assert!(!s.is_suspended());
845        s.event(RouteChanged);
846        s.event(Deactivated);
847        assert_eq!(first.take(), vec![]);
848        // The next call: the session is not active, nothing is suspended.
849        let (second, _id) = attach(&s, true);
850        assert_eq!(second.take(), vec![]);
851        s.event(Activated);
852        assert_eq!(second.take(), vec![Activated]);
853        assert_eq!(first.take(), vec![]);
854    }
855
856    #[test]
857    fn a_stale_detach_leaves_the_new_call_attached() {
858        let s = AudioSession::new();
859        let (_first, old) = attach(&s, true);
860        let (second, _new) = attach(&s, true);
861        s.detach(old);
862        s.event(Activated);
863        assert_eq!(second.take(), vec![Activated]);
864    }
865
866    #[test]
867    fn a_dropped_engine_is_skipped() {
868        let s = AudioSession::new();
869        let (rec, _id) = attach(&s, true);
870        drop(rec);
871        // No panic, and the state is still kept.
872        s.event(Activated);
873        s.event(Suspend);
874        assert_eq!(s.is_active(), Some(true));
875        assert!(s.is_suspended());
876    }
877
878    /// A 440 Hz tone at 48 kHz (never DTX), for the null device.
879    fn tone() -> CaptureSource {
880        let mut n = 0u64;
881        Box::new(move |buf: &mut [f32]| {
882            for x in buf.iter_mut() {
883                *x = 0.3 * (n as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin();
884                n += 1;
885            }
886        })
887    }
888
889    #[test]
890    #[cfg(not(any(target_os = "ios", target_os = "android")))]
891    fn this_build_picks_the_system_backend_on_desktop() {
892        assert_eq!(AUDIO_BACKEND, "system");
893    }
894
895    #[test]
896    #[cfg(not(any(target_os = "ios", target_os = "android")))]
897    fn desktop_audio_is_unchanged_by_session_events() {
898        // A real kessel-audio engine on the null device: on desktop the session events reach
899        // it and change nothing (no suspend, no closed device).
900        let mut cfg = EngineConfig::null(NullDevice {
901            input: Some(tone()),
902            ..NullDevice::default()
903        });
904        cfg.processing = ProcessingConfig::off();
905        let (engine, deferred) = start_engine(cfg).unwrap();
906        assert!(!deferred);
907        let engine = Arc::new(engine);
908        let session = AudioSession::new();
909        session.event(Suspend);
910        let weak: Weak<_> = Arc::downgrade(&engine);
911        let sink: Weak<dyn SessionSink> = weak;
912        let id = session.attach(sink, deferred);
913        let frames = engine.capture_frames();
914        session.event(Deactivated);
915        session.event(RouteChanged);
916        // Drain what came before, then frames must keep coming while "suspended" and
917        // "deactivated".
918        while frames.try_recv().is_some() {}
919        let mut got = 0;
920        let deadline = std::time::Instant::now() + Duration::from_secs(5);
921        while got < 10 && std::time::Instant::now() < deadline {
922            if frames.recv_timeout(Duration::from_millis(200)).is_some() {
923                got += 1;
924            }
925        }
926        assert_eq!(got, 10, "the desktop engine stopped producing frames");
927        session.detach(id);
928        engine.shutdown();
929    }
930
931    /// A call's capture reports its start to the pipeline: the noise removal stage's grace
932    /// window opens with `CallStart` as its reason.
933    #[test]
934    #[cfg(not(any(target_os = "ios", target_os = "android")))]
935    fn a_calls_capture_reports_its_start() {
936        let noise = NoiseRemovalControl::new(NoiseRemoval::Standard);
937        let (cfg, id) = noise.configure(EngineConfig::null(NullDevice {
938            input: Some(tone()),
939            ..NullDevice::default()
940        }));
941        let (engine, deferred) = start_call_engine(cfg).unwrap();
942        assert!(!deferred);
943        let deadline = std::time::Instant::now() + Duration::from_secs(20);
944        loop {
945            let st = engine.stats().capture_stage;
946            if let Some(s) = st
947                && s.last_transient == Some(kessel_audio::TransientEvent::CallStart)
948                && s.grace_blocks > 0
949            {
950                break;
951            }
952            assert!(
953                std::time::Instant::now() < deadline,
954                "the call's start never reached the pipeline: {st:?}"
955            );
956            std::thread::sleep(Duration::from_millis(20));
957        }
958        engine.shutdown();
959        noise.detach(id);
960    }
961}