Skip to main content

kessel_audio/
config.rs

1//! Engine configuration.
2
3use crate::apm::ProcessingConfig;
4use crate::device::NullDevice;
5use crate::error::{AudioError, ErrorCode};
6#[cfg(feature = "cpal")]
7use crate::events::DeviceChoice;
8use crate::frame::EncoderCfg;
9use crate::jitter::JitterConfig;
10use std::time::Duration;
11
12/// Where audio comes from and goes to.
13#[derive(Debug)]
14#[non_exhaustive]
15pub enum Backend {
16    /// The system's audio devices (cpal: CoreAudio, WASAPI or ALSA).
17    #[cfg(feature = "cpal")]
18    System {
19        /// The capture device to start with.
20        input: DeviceChoice,
21        /// The playback device to start with.
22        output: DeviceChoice,
23    },
24    /// No hardware: see [`NullDevice`].
25    Null(NullDevice),
26    /// The phone's own voice processing (echo cancellation, noise
27    /// suppression and gain control tuned for the device). iOS: the
28    /// VoiceProcessingIO audio unit. Android: AAudio with the
29    /// voice-communication input preset and usage (API 28 or later).
30    ///
31    /// The app owns the OS's audio session; the engine never configures or
32    /// activates it. With CallKit, start with
33    /// [`crate::AudioEngine::start_when_session_active`] and report
34    /// `didActivate` / `didDeactivate` to
35    /// [`crate::AudioEngine::session_activated`] /
36    /// [`crate::AudioEngine::session_deactivated`], and route changes to
37    /// [`crate::AudioEngine::route_changed`]. sonora runs only what
38    /// [`crate::OsEffects`] says the OS doesn't do.
39    ///
40    /// [`crate::PhoneMode::Raw`] (from the start with
41    /// [`EngineConfig::with_phone_mode`], or mid-call with
42    /// [`crate::AudioEngine::set_phone_mode`]) turns the OS's processing off
43    /// for the full microphone signal: sonora cancels echo and controls
44    /// gain, and nothing suppresses noise.
45    #[cfg(all(feature = "os-voice", any(target_os = "ios", target_os = "android")))]
46    OsVoiceProcessing(crate::OsVoiceConfig),
47    /// The phone backend's state machine on a fake device (tests).
48    #[cfg(test)]
49    #[allow(private_interfaces)]
50    TestPhone(crate::phone::tests::FakeIo),
51}
52
53impl Default for Backend {
54    /// The system default devices when built with the `cpal` feature, else
55    /// a real-time null device.
56    fn default() -> Self {
57        #[cfg(feature = "cpal")]
58        {
59            Backend::System {
60                input: DeviceChoice::Default,
61                output: DeviceChoice::Default,
62            }
63        }
64        #[cfg(not(feature = "cpal"))]
65        {
66            Backend::Null(NullDevice::default())
67        }
68    }
69}
70
71impl Backend {
72    fn null_device(&self) -> Option<&NullDevice> {
73        // With only the null backend compiled in, the last arm can't match.
74        #[allow(unreachable_patterns)]
75        match self {
76            Backend::Null(d) => Some(d),
77            _ => None,
78        }
79    }
80
81    /// A phone backend (the only kind with a deferred start).
82    #[cfg(any(
83        test,
84        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
85    ))]
86    pub(crate) fn is_phone(&self) -> bool {
87        self.os_effects().is_some()
88    }
89
90    /// What the OS's voice processing covers, for a phone backend.
91    #[cfg(any(
92        test,
93        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
94    ))]
95    pub(crate) fn os_effects(&self) -> Option<crate::phone::OsEffects> {
96        match self {
97            #[cfg(all(feature = "os-voice", any(target_os = "ios", target_os = "android")))]
98            Backend::OsVoiceProcessing(c) => Some(c.os_effects),
99            #[cfg(test)]
100            Backend::TestPhone(f) => Some(f.1),
101            _ => None,
102        }
103    }
104}
105
106/// Everything [`crate::AudioEngine::start`] needs.
107///
108/// `#[non_exhaustive]`: start from [`EngineConfig::default`] (the system
109/// devices) or [`EngineConfig::null`] and chain the `with_` methods, or set
110/// fields on a `let mut`.
111#[derive(Debug)]
112#[non_exhaustive]
113pub struct EngineConfig {
114    /// Devices.
115    pub backend: Backend,
116    /// Capture processing (echo cancellation, noise suppression, gain).
117    pub processing: ProcessingConfig,
118    /// Initial encoder settings.
119    pub encoder: EncoderCfg,
120    /// Jitter-buffer settings for every participant.
121    pub jitter: JitterConfig,
122    /// The first capture timestamp ([`crate::EncodedFrame::ts48k`]). RTP
123    /// recommends a random start.
124    pub initial_ts48k: u32,
125    /// Playback queued ahead of the output device, milliseconds (10..=200).
126    /// Lower is less latency; higher survives scheduling hiccups.
127    pub playout_buffer_ms: u32,
128    /// Capacity of the encoded-frame queue, in frames (20 ms each).
129    pub capture_queue_frames: usize,
130    /// Capacity of the receive queue, in frames.
131    pub recv_queue_frames: usize,
132    /// The most participants at once.
133    pub max_participants: usize,
134    /// Level reading interval, milliseconds (multiple of 10).
135    pub levels_interval_ms: u32,
136    /// Level at or above which a stream counts as speaking, dBov.
137    pub speaking_threshold_dbov: f32,
138    /// How often to look for added or removed devices (hot-plug). Zero
139    /// turns polling off; device errors are still handled.
140    pub device_poll_interval: Duration,
141    /// How often the processing thread wakes to move audio. Must be well
142    /// under 10 ms.
143    pub processing_poll: Duration,
144    /// How the processing thread asks the OS to schedule it (macOS and iOS;
145    /// elsewhere it is reported as [`crate::DspSchedMode::Unsupported`]).
146    /// The default, [`crate::DspSchedMode::Workgroup`], is 0.2.4's
147    /// behaviour. Read once, as the thread starts; what it got is in
148    /// [`crate::Stats::dsp_sched`] and [`crate::Stats::dsp_scheduling`].
149    /// [`crate::DspSchedConfig::from_env`] and
150    /// [`crate::DspSchedConfig::from_lookup`] read one from the environment
151    /// or an app's settings.
152    pub dsp_sched: crate::DspSchedConfig,
153    /// The phone backend's starting mode: the OS's voice processing (the
154    /// default) or raw capture with no noise suppression. Change it during
155    /// a call with [`crate::AudioEngine::set_phone_mode`]. Other backends
156    /// ignore it.
157    #[cfg(any(
158        test,
159        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
160    ))]
161    pub phone_mode: crate::phone::PhoneMode,
162}
163
164impl Default for EngineConfig {
165    fn default() -> Self {
166        EngineConfig {
167            backend: Backend::default(),
168            processing: ProcessingConfig::default(),
169            encoder: EncoderCfg::default(),
170            jitter: JitterConfig::default(),
171            initial_ts48k: 0,
172            playout_buffer_ms: 30,
173            capture_queue_frames: 50,
174            recv_queue_frames: 1024,
175            max_participants: 32,
176            levels_interval_ms: 50,
177            speaking_threshold_dbov: -45.0,
178            device_poll_interval: Duration::from_secs(1),
179            processing_poll: Duration::from_millis(2),
180            dsp_sched: crate::DspSchedConfig::default(),
181            #[cfg(any(
182                test,
183                all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
184            ))]
185            phone_mode: crate::phone::PhoneMode::Os,
186        }
187    }
188}
189
190impl EngineConfig {
191    /// A config for the null device, everything else default.
192    pub fn null(device: NullDevice) -> Self {
193        EngineConfig {
194            backend: Backend::Null(device),
195            ..EngineConfig::default()
196        }
197    }
198
199    /// Set [`backend`](Self::backend).
200    pub fn with_backend(mut self, backend: Backend) -> Self {
201        self.backend = backend;
202        self
203    }
204
205    /// Set [`processing`](Self::processing).
206    pub fn with_processing(mut self, processing: ProcessingConfig) -> Self {
207        self.processing = processing;
208        self
209    }
210
211    /// Set the capture stage ([`ProcessingConfig::capture_stage`]), keeping
212    /// the rest of [`processing`](Self::processing).
213    pub fn with_capture_stage(mut self, stage: Box<dyn crate::CaptureStage>) -> Self {
214        self.processing.capture_stage = Some(stage);
215        self
216    }
217
218    /// Set [`encoder`](Self::encoder).
219    pub fn with_encoder(mut self, encoder: EncoderCfg) -> Self {
220        self.encoder = encoder;
221        self
222    }
223
224    /// Set [`jitter`](Self::jitter).
225    pub fn with_jitter(mut self, jitter: JitterConfig) -> Self {
226        self.jitter = jitter;
227        self
228    }
229
230    /// Set [`initial_ts48k`](Self::initial_ts48k).
231    pub fn with_initial_ts48k(mut self, ts48k: u32) -> Self {
232        self.initial_ts48k = ts48k;
233        self
234    }
235
236    /// Set [`playout_buffer_ms`](Self::playout_buffer_ms).
237    pub fn with_playout_buffer_ms(mut self, ms: u32) -> Self {
238        self.playout_buffer_ms = ms;
239        self
240    }
241
242    /// Set [`capture_queue_frames`](Self::capture_queue_frames).
243    pub fn with_capture_queue_frames(mut self, frames: usize) -> Self {
244        self.capture_queue_frames = frames;
245        self
246    }
247
248    /// Set [`recv_queue_frames`](Self::recv_queue_frames).
249    pub fn with_recv_queue_frames(mut self, frames: usize) -> Self {
250        self.recv_queue_frames = frames;
251        self
252    }
253
254    /// Set [`max_participants`](Self::max_participants).
255    pub fn with_max_participants(mut self, n: usize) -> Self {
256        self.max_participants = n;
257        self
258    }
259
260    /// Set [`levels_interval_ms`](Self::levels_interval_ms).
261    pub fn with_levels_interval_ms(mut self, ms: u32) -> Self {
262        self.levels_interval_ms = ms;
263        self
264    }
265
266    /// Set [`speaking_threshold_dbov`](Self::speaking_threshold_dbov).
267    pub fn with_speaking_threshold_dbov(mut self, dbov: f32) -> Self {
268        self.speaking_threshold_dbov = dbov;
269        self
270    }
271
272    /// Set [`device_poll_interval`](Self::device_poll_interval).
273    pub fn with_device_poll_interval(mut self, every: Duration) -> Self {
274        self.device_poll_interval = every;
275        self
276    }
277
278    /// Set [`processing_poll`](Self::processing_poll).
279    pub fn with_processing_poll(mut self, every: Duration) -> Self {
280        self.processing_poll = every;
281        self
282    }
283
284    /// Set [`dsp_sched`](Self::dsp_sched).
285    pub fn with_dsp_sched(mut self, sched: crate::DspSchedConfig) -> Self {
286        self.dsp_sched = sched;
287        self
288    }
289
290    /// Set [`phone_mode`](Self::phone_mode).
291    #[cfg(any(
292        test,
293        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
294    ))]
295    pub fn with_phone_mode(mut self, mode: crate::phone::PhoneMode) -> Self {
296        self.phone_mode = mode;
297        self
298    }
299
300    /// With a phone backend: what the caller asked sonora for, the stage's
301    /// latency and what the OS does, kept for mode changes.
302    #[cfg(any(
303        test,
304        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
305    ))]
306    pub(crate) fn phone_processing(&self) -> Option<crate::phone::Processing> {
307        Some(crate::phone::Processing {
308            fx: self.backend.os_effects()?,
309            asked: self.processing.settings(),
310            stage_latency: self
311                .processing
312                .capture_stage
313                .as_ref()
314                .map(|s| s.latency_samples()),
315        })
316    }
317
318    /// With a phone backend, sonora runs only what the OS doesn't (in
319    /// [`crate::phone::PhoneMode::Raw`], echo cancellation and gain control
320    /// and no noise suppression). A capture stage stays: it is the caller's,
321    /// not one of the OS's effects.
322    #[cfg(any(
323        test,
324        all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
325    ))]
326    pub(crate) fn with_os_effects(mut self) -> Self {
327        if let Some(pp) = self.phone_processing() {
328            let left = pp.settings(self.phone_mode);
329            let p = &mut self.processing;
330            p.echo_cancellation = left.echo_cancellation;
331            p.noise_suppression = left.noise_suppression;
332            p.gain_control = left.gain_control;
333            p.high_pass = left.high_pass;
334            p.stage_fallback_noise_suppression = left.stage_fallback_ns;
335        }
336        self
337    }
338
339    pub(crate) fn validate(&self) -> Result<(), AudioError> {
340        let bad = |what: &str| Err(AudioError::new(ErrorCode::InvalidConfig, what.to_string()));
341        if !(10..=200).contains(&self.playout_buffer_ms) {
342            return bad("playout_buffer_ms must be 10..=200");
343        }
344        if self.capture_queue_frames == 0 || self.recv_queue_frames == 0 {
345            return bad("queue sizes must be at least 1");
346        }
347        if self.max_participants == 0 {
348            return bad("max_participants must be at least 1");
349        }
350        if self.levels_interval_ms < 10 || !self.levels_interval_ms.is_multiple_of(10) {
351            return bad("levels_interval_ms must be a multiple of 10");
352        }
353        if self.jitter.min_delay_ms > self.jitter.max_delay_ms {
354            return bad("jitter min_delay_ms is above max_delay_ms");
355        }
356        if self.processing_poll.is_zero() || self.processing_poll >= Duration::from_millis(10) {
357            return bad("processing_poll must be between 0 and 10 ms");
358        }
359        self.dsp_sched.validate()?;
360        if self.processing.stage_grace > crate::stage::MAX_STAGE_GRACE {
361            return bad("processing.stage_grace must be at most 10 s");
362        }
363        if self.processing.stage_starvation_cutoff < crate::stage::HARD_BUDGET {
364            return bad("processing.stage_starvation_cutoff must be at least 9 ms");
365        }
366        #[cfg(all(feature = "os-voice", any(target_os = "ios", target_os = "android")))]
367        if let Backend::OsVoiceProcessing(c) = &self.backend {
368            c.validate(self.phone_mode)?;
369        }
370        if let Some(d) = self.backend.null_device() {
371            if d.sample_rate < 8_000
372                || d.sample_rate > 384_000
373                || !d.sample_rate.is_multiple_of(100)
374            {
375                return bad("null device sample_rate must be 8000..=384000 and a multiple of 100");
376            }
377            if d.block_period.is_zero() {
378                return bad("null device block_period must be above 0");
379            }
380        }
381        Ok(())
382    }
383}