Skip to main content

sew_call_client/noise/
mod.rs

1//! Noise removal on the capture path: the setting ([`NoiseRemoval`]) and what runs
2//! ([`NoiseRemovalState`]).
3//!
4//! kessel-audio runs a capture stage between echo cancellation and gain control (its capture
5//! hook); with feature `audio-core` this crate builds that stage over `sew-noise` and hands it
6//! over ([`NoiseRemovalControl`], [`crate::AudioBridge::start_with_noise`]). With a stage set,
7//! kessel-audio's own noise suppression is off.
8//!
9//! [`NoiseRemoval::Standard`] runs:
10//! - with feature `dfn3` and the DeepFilterNet3 weights given to the control
11//!   (`NoiseRemovalControl::set_dfn3_weights`), DeepFilterNet3's low-latency model, with
12//!   RNNoise kept warm beside it and stepped down to when the device can't keep up
13//!   ([`NoiseRemovalState::model`] says which runs);
14//! - otherwise RNNoise.
15//!
16//! On phones the OS's voice processing does its own noise suppression first. Without the
17//! DeepFilterNet3 weights no stage runs there (the state says `unavailable`); with them the
18//! stage runs after the OS's processing, as on desktop. [`NoiseRemoval::Off`] turns the OS's
19//! processing off too: the phone's audio goes raw ([`PhoneAudioMode::Raw`]), at the start of a
20//! call and when the setting changes during one.
21
22use serde::{Deserialize, Serialize};
23
24#[cfg(feature = "noise-bench")]
25pub mod bench;
26#[cfg(feature = "audio-core")]
27mod control;
28#[cfg(feature = "audio-core")]
29mod hook;
30#[cfg(any(feature = "dfn3", feature = "noise-bench"))]
31mod mem;
32#[cfg(feature = "noise-probe")]
33pub mod probe;
34
35#[cfg(feature = "dfn3")]
36pub use control::{DFN3_IDLE_UNLOAD, Dfn3LoadInfo};
37#[cfg(any(feature = "dfn3", feature = "noise-bench"))]
38pub(crate) use mem::rss_kib;
39#[cfg(feature = "noise-bench")]
40pub(crate) use mem::rss_peak_kib;
41
42#[cfg(feature = "audio-core")]
43pub(crate) use control::LiveAudio;
44#[cfg(feature = "audio-core")]
45pub use control::NoiseRemovalControl;
46
47/// Where a call reads its noise removal state (its stats windows, [`crate::Call::noise_removal`]):
48/// the [`NoiseRemovalControl`] its audio started with. `None` once that audio ended.
49pub(crate) trait NoiseSource: Send + Sync {
50    fn noise_state(&self) -> Option<NoiseRemovalState>;
51    /// The device is busy with something else for a moment (a camera starting): the call's
52    /// stage holds its timing rules back for a grace window.
53    fn grace(&self) {}
54}
55
56/// How much noise this device's microphone has removed. The default is
57/// [`NoiseRemoval::Standard`].
58///
59/// Its JSON is `"off"` or `"standard"`. More modes may come in a later version.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62#[non_exhaustive]
63pub enum NoiseRemoval {
64    /// No noise removal: the full audio, with echo cancellation and gain control kept. For
65    /// music or a studio microphone.
66    ///
67    /// On iOS and Android the OS's voice processing is off as well ([`PhoneAudioMode::Raw`]):
68    /// iOS opens the plain RemoteIO unit; Android opens the microphone with its unprocessed
69    /// source where the device supports it
70    /// (`NoiseRemovalControl::set_android_unprocessed_supported`), else its voice recognition
71    /// source, with no effects attached. kessel-audio then cancels echo and controls gain
72    /// itself, with no noise suppression. A call that starts in Off opens that way; a change
73    /// during a call switches the phone's audio at once, with a short pause of the microphone
74    /// while it reopens ([`NoiseRemovalState::phone_mode_gap_ms`]).
75    Off,
76    /// Noise removal between echo cancellation and gain control: DeepFilterNet3 where it is
77    /// built in and its weights are loaded, with RNNoise as its automatic step-down; RNNoise
78    /// otherwise.
79    #[default]
80    Standard,
81}
82
83impl NoiseRemoval {
84    /// Every mode this version has, weakest first.
85    pub const ALL: [NoiseRemoval; 2] = [NoiseRemoval::Off, NoiseRemoval::Standard];
86
87    /// The mode's name: `off` or `standard`.
88    pub fn as_str(self) -> &'static str {
89        match self {
90            NoiseRemoval::Off => "off",
91            NoiseRemoval::Standard => "standard",
92        }
93    }
94
95    /// The mode of a name [`NoiseRemoval::as_str`] gives; `None` for any other (`strong`
96    /// included: this version has no stronger mode).
97    pub fn from_name(name: &str) -> Option<NoiseRemoval> {
98        NoiseRemoval::ALL.into_iter().find(|m| m.as_str() == name)
99    }
100}
101
102impl std::fmt::Display for NoiseRemoval {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.write_str(self.as_str())
105    }
106}
107
108/// Why the noise removal that runs ([`NoiseRemovalState::active`]) is less than what was asked
109/// ([`NoiseRemovalState::mode`]).
110///
111/// Its JSON is `"budget"`, `"fault"`, `"unavailable"`, `"switch_failed"` or `"loading"`.
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case")]
114#[non_exhaustive]
115pub enum NoiseRemovalReason {
116    /// The audio pipeline stopped the stage because it took too long (two blocks in a row of
117    /// 9 ms or more, or over 6 ms at the 99th percentile): the microphone goes on with
118    /// kessel-audio's own noise suppression instead, until a retry 10 s later brings the stage
119    /// back (after 3 such stops within 60 s, for the rest of the call).
120    Budget,
121    /// The audio pipeline stopped the stage after a fault (a panic, or samples that were not
122    /// finite), for the rest of the call; kessel-audio's own noise suppression runs instead.
123    Fault,
124    /// This platform or build can't run the mode (phones; an audio pipeline without the
125    /// capture hook).
126    Unavailable,
127    /// The phone's audio could not switch to the capture the setting asks for (the microphone
128    /// would not open that way): it went back to the capture it had, and kessel-audio reported
129    /// the error. In [`NoiseRemovalState::phone_mode_reason`] only.
130    SwitchFailed,
131    /// DeepFilterNet3's model is being loaded (it is loaded when a call first needs it): RNNoise
132    /// runs meanwhile (on phones, the OS's processing alone), and the call steps up to
133    /// DeepFilterNet3 once it is ready.
134    Loading,
135}
136
137impl NoiseRemovalReason {
138    /// The reason's name: `budget`, `fault`, `unavailable`, `switch_failed` or `loading`.
139    pub fn as_str(self) -> &'static str {
140        match self {
141            NoiseRemovalReason::Budget => "budget",
142            NoiseRemovalReason::Fault => "fault",
143            NoiseRemovalReason::Unavailable => "unavailable",
144            NoiseRemovalReason::SwitchFailed => "switch_failed",
145            NoiseRemovalReason::Loading => "loading",
146        }
147    }
148}
149
150/// How a phone's microphone is captured (iOS and Android with feature `mobile`): through the
151/// OS's voice processing, or raw, with the OS's processing off ([`NoiseRemoval::Off`]).
152///
153/// Its JSON is `"os"` or `"raw"`.
154#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case")]
156#[non_exhaustive]
157pub enum PhoneAudioMode {
158    /// The OS's voice processing: its echo cancellation, noise suppression and gain control
159    /// ([`NoiseRemoval::Standard`]).
160    Os,
161    /// No OS processing: the full microphone signal. kessel-audio cancels echo and controls
162    /// gain, with no noise suppression ([`NoiseRemoval::Off`]).
163    Raw,
164}
165
166impl PhoneAudioMode {
167    /// The capture a setting asks for: raw for Off, the OS's processing otherwise.
168    pub fn for_mode(mode: NoiseRemoval) -> PhoneAudioMode {
169        match mode {
170            NoiseRemoval::Off => PhoneAudioMode::Raw,
171            NoiseRemoval::Standard => PhoneAudioMode::Os,
172        }
173    }
174
175    /// The mode's name: `os` or `raw`.
176    pub fn as_str(self) -> &'static str {
177        match self {
178            PhoneAudioMode::Os => "os",
179            PhoneAudioMode::Raw => "raw",
180        }
181    }
182}
183
184impl std::fmt::Display for PhoneAudioMode {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.write_str(self.as_str())
187    }
188}
189
190/// The model that removes the noise when [`NoiseRemoval::Standard`] runs.
191///
192/// Its JSON is `"dfn3"` or `"rnnoise"`. More models may come in a later version.
193#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
194#[serde(rename_all = "snake_case")]
195#[non_exhaustive]
196pub enum NoiseModel {
197    /// DeepFilterNet3's low-latency model (feature `dfn3`, its weights loaded).
198    Dfn3,
199    /// RNNoise.
200    Rnnoise,
201}
202
203impl NoiseModel {
204    /// The model's name: `dfn3` or `rnnoise`.
205    pub fn as_str(self) -> &'static str {
206        match self {
207            NoiseModel::Dfn3 => "dfn3",
208            NoiseModel::Rnnoise => "rnnoise",
209        }
210    }
211}
212
213impl std::fmt::Display for NoiseModel {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        f.write_str(self.as_str())
216    }
217}
218
219/// Why the call's stage last stepped down from DeepFilterNet3 to RNNoise
220/// ([`NoiseRemovalState::step_down_reason`]): the stage's own rule names.
221///
222/// Its JSON is `"slow_block"`, `"slow_window"`, `"heavy"`, `"fault"`, `"forced"` or
223/// `"starved"`. More may come in a later version.
224#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
225#[serde(rename_all = "snake_case")]
226#[non_exhaustive]
227pub enum NoiseStepDownReason {
228    /// One block took too long on its own.
229    SlowBlock,
230    /// Too many recent blocks were slow (the 99th percentile; in a grace window, the second
231    /// block over the audio pipeline's own line).
232    SlowWindow,
233    /// Recent blocks were steadily close to the budget (the median).
234    Heavy,
235    /// The model gave a sample that was not finite: final for the call.
236    Fault,
237    /// Asked for by a measurement.
238    Forced,
239    /// The audio thread fell behind real time for several blocks in a row by the wall clock,
240    /// whatever the cause.
241    Starved,
242}
243
244impl NoiseStepDownReason {
245    /// The reason's name: `slow_block`, `slow_window`, `heavy`, `fault`, `forced` or
246    /// `starved`.
247    pub fn as_str(self) -> &'static str {
248        match self {
249            NoiseStepDownReason::SlowBlock => "slow_block",
250            NoiseStepDownReason::SlowWindow => "slow_window",
251            NoiseStepDownReason::Heavy => "heavy",
252            NoiseStepDownReason::Fault => "fault",
253            NoiseStepDownReason::Forced => "forced",
254            NoiseStepDownReason::Starved => "starved",
255        }
256    }
257}
258
259/// Where the call's stage is with DeepFilterNet3 ([`NoiseRemovalState::dfn3_state`]).
260///
261/// Its JSON is `"idle"`, `"warming"`, `"running"`, `"stepped_down"` or `"retired"`. More may
262/// come in a later version.
263#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
264#[serde(rename_all = "snake_case")]
265#[non_exhaustive]
266pub enum NoiseDfn3State {
267    /// Not asked for (the setting is Off), or not started yet.
268    Idle,
269    /// The model runs on the microphone while RNNoise's output goes on: the call's start, or
270    /// a retry after a step-down.
271    Warming,
272    /// The model's output goes on.
273    Running,
274    /// Stepped down to RNNoise; retried later (`retry_in_ms`).
275    SteppedDown,
276    /// Stepped down for the rest of the call.
277    Retired,
278}
279
280impl NoiseDfn3State {
281    /// The state's name: `idle`, `warming`, `running`, `stepped_down` or `retired`.
282    pub fn as_str(self) -> &'static str {
283        match self {
284            NoiseDfn3State::Idle => "idle",
285            NoiseDfn3State::Warming => "warming",
286            NoiseDfn3State::Running => "running",
287            NoiseDfn3State::SteppedDown => "stepped_down",
288            NoiseDfn3State::Retired => "retired",
289        }
290    }
291}
292
293impl std::fmt::Display for NoiseDfn3State {
294    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295        f.write_str(self.as_str())
296    }
297}
298
299impl std::fmt::Display for NoiseStepDownReason {
300    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301        f.write_str(self.as_str())
302    }
303}
304
305/// A busy moment of the device reported to the audio pipeline, which opens its grace window
306/// for the stage ([`NoiseRemovalState::capture_stage_last_transient`]).
307///
308/// Its JSON is `"call_start"`, `"audio_session_activated"`, `"route_change"`,
309/// `"camera_start"`, `"app_scene_change"` or `"other"`. More may come in a later version.
310#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
311#[serde(rename_all = "snake_case")]
312#[non_exhaustive]
313pub enum CaptureTransient {
314    /// The call's audio started (a join or a rejoin).
315    CallStart,
316    /// The phone's audio session became active.
317    AudioSessionActivated,
318    /// The audio route changed.
319    RouteChange,
320    /// A camera started or restarted.
321    CameraStart,
322    /// The app changed scene (foreground, background, focus).
323    AppSceneChange,
324    /// Anything else.
325    Other,
326}
327
328impl CaptureTransient {
329    /// The moment's name: `call_start`, `audio_session_activated`, `route_change`,
330    /// `camera_start`, `app_scene_change` or `other`.
331    pub fn as_str(self) -> &'static str {
332        match self {
333            CaptureTransient::CallStart => "call_start",
334            CaptureTransient::AudioSessionActivated => "audio_session_activated",
335            CaptureTransient::RouteChange => "route_change",
336            CaptureTransient::CameraStart => "camera_start",
337            CaptureTransient::AppSceneChange => "app_scene_change",
338            CaptureTransient::Other => "other",
339        }
340    }
341}
342
343impl std::fmt::Display for CaptureTransient {
344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345        f.write_str(self.as_str())
346    }
347}
348
349/// The clock the audio pipeline times the noise removal stage by
350/// ([`NoiseRemovalState::capture_stage_clock`]).
351///
352/// Its JSON is `"thread_cpu"` or `"wall"`. More may come in a later version.
353#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
354#[serde(rename_all = "snake_case")]
355#[non_exhaustive]
356pub enum CaptureStageClock {
357    /// The processing thread's own CPU time: time the device spends on other threads while the
358    /// stage waits does not count.
359    ThreadCpu,
360    /// The wall clock: everything between a block's start and end counts.
361    Wall,
362}
363
364impl CaptureStageClock {
365    /// The clock's name: `thread_cpu` or `wall`.
366    pub fn as_str(self) -> &'static str {
367        match self {
368            CaptureStageClock::ThreadCpu => "thread_cpu",
369            CaptureStageClock::Wall => "wall",
370        }
371    }
372}
373
374impl std::fmt::Display for CaptureStageClock {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        f.write_str(self.as_str())
377    }
378}
379
380/// Which scheduling the audio pipeline's processing thread asks the OS for
381/// ([`CaptureDspSched::mode`], `NoiseRemovalControl::set_dsp_sched`). Only macOS and iOS act
382/// on it.
383///
384/// Its JSON is `"workgroup"`, `"time_constraint_only"`, `"none"`, `"own_workgroup"` or
385/// `"unsupported"`. More may come in a later version.
386#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
387#[serde(rename_all = "snake_case")]
388#[non_exhaustive]
389pub enum CaptureDspSchedMode {
390    /// Asks for real-time scheduling by the time-constraint policy, and on iOS joins the audio
391    /// unit's own I/O workgroup while the phone's audio unit runs: what a call does when nothing
392    /// is set.
393    #[default]
394    Workgroup,
395    /// Asks for real-time scheduling by the time-constraint policy with the given figures, in
396    /// no workgroup.
397    TimeConstraintOnly,
398    /// No request: the OS's default scheduling.
399    None,
400    /// Asks for real-time scheduling by the time-constraint policy, and in a work interval of
401    /// the thread's own: each block is due [`CaptureDspSched::interval_deadline_us`] after it
402    /// starts.
403    OwnWorkgroup,
404    /// Only reported, as the mode in effect: this platform has none of these calls (Linux,
405    /// Android, Windows). Asking for it is refused.
406    Unsupported,
407}
408
409impl CaptureDspSchedMode {
410    /// The mode's name: `workgroup`, `time_constraint_only`, `none`, `own_workgroup` or
411    /// `unsupported`.
412    pub const fn as_str(self) -> &'static str {
413        match self {
414            CaptureDspSchedMode::Workgroup => "workgroup",
415            CaptureDspSchedMode::TimeConstraintOnly => "time_constraint_only",
416            CaptureDspSchedMode::None => "none",
417            CaptureDspSchedMode::OwnWorkgroup => "own_workgroup",
418            CaptureDspSchedMode::Unsupported => "unsupported",
419        }
420    }
421}
422
423/// Why the processing thread runs in [`CaptureDspSchedMode::Workgroup`] and not in the mode
424/// asked for ([`NoiseRemovalState::capture_stage_dsp_sched_fallback`]).
425///
426/// Its JSON is `"time_constraint_refused"`, `"own_workgroup_unavailable"`,
427/// `"own_workgroup_join_refused"`, `"interval_refused"` or `"other"`.
428#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
429#[serde(rename_all = "snake_case")]
430#[non_exhaustive]
431pub enum CaptureDspSchedFallback {
432    /// The OS refused the time-constraint policy.
433    TimeConstraintRefused,
434    /// The system has no work intervals for an app's audio threads, or making one failed.
435    OwnWorkgroupUnavailable,
436    /// The OS refused the thread joining its own work interval.
437    OwnWorkgroupJoinRefused,
438    /// The OS refused an interval during the call; the thread left its own work interval.
439    IntervalRefused,
440    /// A reason this version does not know.
441    Other,
442}
443
444/// Why [`CaptureDspSched::validate`] (and `NoiseRemovalControl::set_dsp_sched`) refused.
445#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
446#[non_exhaustive]
447pub enum CaptureDspSchedError {
448    /// [`CaptureDspSchedMode::Unsupported`] is only reported, never asked for.
449    #[error("the mode `unsupported` is only reported, never asked for")]
450    ModeNotAskable,
451    /// The figures must satisfy 0 < computation <= constraint <= period <= 1 s.
452    #[error("the time constraint needs 0 < computation <= constraint <= period <= 1 s")]
453    TimeConstraint,
454    /// The interval deadline must be above zero and at most the period.
455    #[error("the interval deadline must be above 0 and at most the period")]
456    IntervalDeadline,
457}
458
459/// What the audio pipeline's processing thread asks the OS for in the calls that start after
460/// it is set (`NoiseRemovalControl::set_dsp_sched`): the mode, the time-constraint policy's
461/// figures and, for [`CaptureDspSchedMode::OwnWorkgroup`], each block's deadline. The
462/// pipeline reads it once, as a call's audio starts; a change reaches the next call.
463///
464/// Its JSON is `{mode, period_us, computation_us, constraint_us, interval_deadline_us}`.
465#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
466#[non_exhaustive]
467pub struct CaptureDspSched {
468    /// Which set-up to ask for.
469    pub mode: CaptureDspSchedMode,
470    /// How often the thread has work, microseconds (one 10 ms block by default).
471    pub period_us: u32,
472    /// The CPU time it needs per period, microseconds (6 ms by default).
473    pub computation_us: u32,
474    /// The time from the start of the period by which that work must be done, microseconds
475    /// (9 ms by default).
476    pub constraint_us: u32,
477    /// [`CaptureDspSchedMode::OwnWorkgroup`] only: how long after a block starts its work is
478    /// due, microseconds (3 ms by default). The other modes ignore it.
479    pub interval_deadline_us: u32,
480}
481
482impl Default for CaptureDspSched {
483    fn default() -> CaptureDspSched {
484        CaptureDspSched::new(CaptureDspSchedMode::Workgroup)
485    }
486}
487
488impl CaptureDspSched {
489    /// `mode` with the default figures: a 10 ms period, 6 ms of computation, a 9 ms
490    /// constraint and a 3 ms interval deadline.
491    pub const fn new(mode: CaptureDspSchedMode) -> CaptureDspSched {
492        CaptureDspSched {
493            mode,
494            period_us: 10_000,
495            computation_us: 6_000,
496            constraint_us: 9_000,
497            interval_deadline_us: 3_000,
498        }
499    }
500
501    /// With these time-constraint figures, microseconds.
502    pub const fn with_time_constraint_us(
503        mut self,
504        period_us: u32,
505        computation_us: u32,
506        constraint_us: u32,
507    ) -> CaptureDspSched {
508        self.period_us = period_us;
509        self.computation_us = computation_us;
510        self.constraint_us = constraint_us;
511        self
512    }
513
514    /// With this interval deadline, microseconds.
515    pub const fn with_interval_deadline_us(mut self, deadline_us: u32) -> CaptureDspSched {
516        self.interval_deadline_us = deadline_us;
517        self
518    }
519
520    /// Whether the audio pipeline would take these figures: a mode that can be asked for,
521    /// 0 < computation <= constraint <= period <= 1 s, and an interval deadline above zero and
522    /// at most the period.
523    pub const fn validate(&self) -> Result<(), CaptureDspSchedError> {
524        if matches!(self.mode, CaptureDspSchedMode::Unsupported) {
525            return Err(CaptureDspSchedError::ModeNotAskable);
526        }
527        if self.computation_us == 0
528            || self.computation_us > self.constraint_us
529            || self.constraint_us > self.period_us
530            || self.period_us > 1_000_000
531        {
532            return Err(CaptureDspSchedError::TimeConstraint);
533        }
534        if self.interval_deadline_us == 0 || self.interval_deadline_us > self.period_us {
535            return Err(CaptureDspSchedError::IntervalDeadline);
536        }
537        Ok(())
538    }
539}
540
541/// How the OS schedules the audio pipeline's processing thread, the thread the noise removal
542/// stage runs on ([`NoiseRemovalState::capture_stage_dsp_scheduling`]): the best of the
543/// requests the pipeline made that the OS granted. On macOS and iOS the thread asks for
544/// real-time scheduling; elsewhere it keeps the OS's default.
545///
546/// Its JSON is `"workgroup"`, `"time_constraint"`, `"qos"`, `"none"` or `"own_workgroup"`. More
547/// may come in a later version.
548#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
549#[serde(rename_all = "snake_case")]
550#[non_exhaustive]
551pub enum CaptureDspScheduling {
552    /// Real-time, and joined to the audio unit's own I/O workgroup, so the OS schedules it with
553    /// the audio I/O thread (iOS, while the phone's audio unit runs).
554    Workgroup,
555    /// The OS's real-time time-constraint policy.
556    TimeConstraint,
557    /// Only the OS's user-interactive quality of service: the OS refused the real-time policy.
558    Qos,
559    /// The OS's default scheduling (Linux, Android and Windows, or where the OS refused every
560    /// request).
561    None,
562    /// Real-time, and joined to a work interval of the thread's own
563    /// ([`CaptureDspSchedMode::OwnWorkgroup`]): each block is an interval with its own deadline.
564    OwnWorkgroup,
565}
566
567impl CaptureDspScheduling {
568    /// The mode's name: `workgroup`, `time_constraint`, `qos`, `none` or `own_workgroup`.
569    pub fn as_str(self) -> &'static str {
570        match self {
571            CaptureDspScheduling::Workgroup => "workgroup",
572            CaptureDspScheduling::TimeConstraint => "time_constraint",
573            CaptureDspScheduling::Qos => "qos",
574            CaptureDspScheduling::None => "none",
575            CaptureDspScheduling::OwnWorkgroup => "own_workgroup",
576        }
577    }
578}
579
580impl std::fmt::Display for CaptureDspScheduling {
581    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
582        f.write_str(self.as_str())
583    }
584}
585
586/// The noise removal setting and what runs: `{mode, active, reason?, model?, model_reason?,
587/// step_downs?, phone_mode?, phone_mode_reason?, phone_mode_switches?, phone_mode_gap_ms?,
588/// step_down_reason?, last_step_down_ms_ago?, slowest_block_us?, blocks_over_budget?,
589/// in_grace?, dfn3_state?, retry_in_ms?, grace_step_downs?, slowest_block_cpu_us?,
590/// p99_block_us?, p99_block_cpu_us?, capture_stage_strikes?, capture_stage_bypassed?,
591/// capture_stage_p99_us?, capture_stage_grace?, capture_stage_grace_blocks?,
592/// capture_stage_grace_over_budget?, capture_stage_last_transient?, capture_stage_clock?,
593/// capture_stage_max_wall_us?, capture_stage_preempted_over_budget?, capture_stage_starved?,
594/// capture_stage_dsp_scheduling?}`.
595///
596/// `mode` is what was asked, `active` what the microphone's audio goes through now, and
597/// `reason` (absent when `active` is `mode`) why they differ. With no call, `active` is what a
598/// call would start with.
599///
600/// On phones (iOS and Android with feature `mobile`) `phone_mode` says how the microphone is
601/// captured ([`PhoneAudioMode`]: `raw` for Off, `os` otherwise; with no call, what a call
602/// would start with). A change of the setting during a call switches it: `phone_mode` follows
603/// once the microphone has reopened, `phone_mode_switches` counts the call's switches and
604/// `phone_mode_gap_ms` is how long the microphone paused for the last one. If a switch fails,
605/// the phone keeps the capture it had and `phone_mode_reason` is `switch_failed` until the
606/// setting and the capture agree again. These fields are absent elsewhere and while unset.
607///
608/// Where DeepFilterNet3 is in play (feature `dfn3`, once the app has given the control its
609/// weights, whether they checked out or not), `model` says which model runs while `active` is
610/// Standard, `model_reason` why it is RNNoise rather than DeepFilterNet3 (`budget`: the stage
611/// stepped down because the device could not keep up; `fault`; `loading`: the model is being
612/// loaded for this call; `unavailable`: no usable weights), and `step_downs` how many times
613/// this call's stage stepped down. They are absent otherwise, so the JSON is then
614/// `{mode, active, reason?}` as before. A UI shows, for example,
615/// "DeepFilterNet3" or "RNNoise (stepped down: budget)".
616///
617/// For a call's log, where DeepFilterNet3 is in play and a call's stage runs, the state also
618/// carries the stage's timing: `step_down_reason` (the stage's rule at the latest step-down),
619/// `last_step_down_ms_ago`, `slowest_block_us`, `blocks_over_budget` and `in_grace` (a grace
620/// window is open: the timing rules are held back while the device is busy with something
621/// else, see `NoiseRemovalControl::app_scene_changed`); where DeepFilterNet3 is
622/// (`dfn3_state`), how long until its retry while it is stepped down (`retry_in_ms`), the
623/// step-downs tied to a grace window or a reset (`grace_step_downs`: they do not count towards
624/// retiring the model), and the stage's blocks by the audio thread's CPU time beside the wall
625/// clock (`slowest_block_cpu_us`, `p99_block_us`, `p99_block_cpu_us`: the stage judges CPU
626/// time where the platform has a clock for it, so a block that waited for a core does not
627/// count against the model); and kessel-audio's view of the stage: `capture_stage_strikes`,
628/// `capture_stage_bypassed` (why the pipeline last bypassed the stage, kept after a retry
629/// brought it back) and `capture_stage_p99_us`, and the audio pipeline's own grace window for
630/// the stage: `capture_stage_grace` (open now: its slow blocks do not count toward a bypass),
631/// `capture_stage_grace_blocks`, `capture_stage_grace_over_budget` (slow blocks the window
632/// excused) and `capture_stage_last_transient` (the last busy moment reported to it,
633/// [`CaptureTransient`]), and how it times the stage: `capture_stage_clock`
634/// ([`CaptureStageClock`]), `capture_stage_max_wall_us` (the slowest block on the wall
635/// clock), `capture_stage_preempted_over_budget` (blocks over the budget on the wall clock but
636/// not in the thread's CPU time) and `capture_stage_starved` (blocks long enough on the wall
637/// clock to count as slow whatever their CPU time), and how the OS schedules the thread the
638/// stage runs on: `capture_stage_dsp_scheduling` ([`CaptureDspScheduling`]; the thread asks
639/// for real-time scheduling on macOS and iOS). Each is absent while unset or zero. The
640/// counters (`last_step_down_ms_ago`, `slowest_block_us`, `blocks_over_budget`,
641/// `retry_in_ms`, `slowest_block_cpu_us`, `p99_block_us`, `p99_block_cpu_us`,
642/// `capture_stage_p99_us`) and the pipeline's grace, clock and scheduling fields are read with
643/// the state and ride along with each change; they do not make a change by themselves.
644#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
645#[non_exhaustive]
646pub struct NoiseRemovalState {
647    /// What was asked.
648    pub mode: NoiseRemoval,
649    /// What runs.
650    pub active: NoiseRemoval,
651    /// Why `active` is less than `mode`.
652    #[serde(default, skip_serializing_if = "Option::is_none")]
653    pub reason: Option<NoiseRemovalReason>,
654    /// The model running while `active` is Standard (absent where DeepFilterNet3 is not in
655    /// play, and while nothing of ours runs).
656    #[serde(default, skip_serializing_if = "Option::is_none")]
657    pub model: Option<NoiseModel>,
658    /// Why `model` is RNNoise when DeepFilterNet3 was wanted.
659    #[serde(default, skip_serializing_if = "Option::is_none")]
660    pub model_reason: Option<NoiseRemovalReason>,
661    /// How many times the call's stage stepped down from DeepFilterNet3 to RNNoise.
662    #[serde(default, skip_serializing_if = "is_zero")]
663    pub step_downs: u32,
664    /// Phones: how the microphone is captured (absent elsewhere).
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub phone_mode: Option<PhoneAudioMode>,
667    /// Phones: why `phone_mode` is not what `mode` asks for (`switch_failed`); absent while a
668    /// switch is under way and when they agree.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub phone_mode_reason: Option<NoiseRemovalReason>,
671    /// Phones: how many times this call's microphone switched capture.
672    #[serde(default, skip_serializing_if = "is_zero")]
673    pub phone_mode_switches: u32,
674    /// Phones: how long the microphone paused for the last switch that reopened it, ms.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub phone_mode_gap_ms: Option<u32>,
677    /// The stage's rule at its latest step-down from DeepFilterNet3 (absent before any).
678    #[serde(default, skip_serializing_if = "Option::is_none")]
679    pub step_down_reason: Option<NoiseStepDownReason>,
680    /// How long ago, in the call's audio, the latest step-down was (ms; absent before any).
681    #[serde(default, skip_serializing_if = "Option::is_none")]
682    pub last_step_down_ms_ago: Option<u64>,
683    /// The call's slowest stage block so far, microseconds.
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub slowest_block_us: Option<u64>,
686    /// The call's stage blocks over the stage's budget so far.
687    #[serde(default, skip_serializing_if = "is_zero_u64")]
688    pub blocks_over_budget: u64,
689    /// A grace window is open: the stage's timing rules are held back while the device is busy
690    /// with something else (the call's start, the audio session, a route change, a camera, an
691    /// app switch).
692    #[serde(default, skip_serializing_if = "is_false")]
693    pub in_grace: bool,
694    /// Where the call's stage is with DeepFilterNet3.
695    #[serde(default, skip_serializing_if = "Option::is_none")]
696    pub dfn3_state: Option<NoiseDfn3State>,
697    /// While `dfn3_state` is `stepped_down`: how long until the retry may start, in the call's
698    /// audio (ms; 0 when it is due and waits for the device to settle).
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    pub retry_in_ms: Option<u64>,
701    /// Step-downs (of `step_downs`) tied to a grace window or to a restart of the capture
702    /// stage: they do not count towards retiring DeepFilterNet3 for the call.
703    #[serde(default, skip_serializing_if = "is_zero")]
704    pub grace_step_downs: u32,
705    /// The call's slowest stage block by the audio thread's CPU time, microseconds (absent
706    /// where the platform has no clock for it).
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub slowest_block_cpu_us: Option<u64>,
709    /// The 99th percentile of the stage's last 100 blocks by the wall clock, microseconds.
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub p99_block_us: Option<u64>,
712    /// The same by the audio thread's CPU time (absent where the platform has no clock for
713    /// it).
714    #[serde(default, skip_serializing_if = "Option::is_none")]
715    pub p99_block_cpu_us: Option<u64>,
716    /// kessel-audio's budget strikes and faults against the stage so far.
717    #[serde(default, skip_serializing_if = "is_zero")]
718    pub capture_stage_strikes: u32,
719    /// Why kessel-audio last bypassed the stage (`budget` or `fault`), kept after a retry
720    /// brought it back (`reason` says whether it is bypassed now).
721    #[serde(default, skip_serializing_if = "Option::is_none")]
722    pub capture_stage_bypassed: Option<NoiseRemovalReason>,
723    /// kessel-audio's 99th percentile of the stage's last 100 blocks, microseconds.
724    #[serde(default, skip_serializing_if = "Option::is_none")]
725    pub capture_stage_p99_us: Option<u32>,
726    /// kessel-audio's grace window for the stage is open now: its slow blocks do not count
727    /// toward a bypass.
728    #[serde(default, skip_serializing_if = "is_false")]
729    pub capture_stage_grace: bool,
730    /// kessel-audio's stage blocks inside its grace windows so far.
731    #[serde(default, skip_serializing_if = "is_zero_u64")]
732    pub capture_stage_grace_blocks: u64,
733    /// Of those, the blocks over the budget that a grace window excused.
734    #[serde(default, skip_serializing_if = "is_zero_u64")]
735    pub capture_stage_grace_over_budget: u64,
736    /// The last busy moment reported to kessel-audio (absent before any).
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub capture_stage_last_transient: Option<CaptureTransient>,
739    /// The clock kessel-audio times the stage by.
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub capture_stage_clock: Option<CaptureStageClock>,
742    /// kessel-audio's slowest stage block on the wall clock so far, microseconds, whatever
743    /// the clock.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub capture_stage_max_wall_us: Option<u32>,
746    /// With the thread's CPU time: blocks over the budget on the wall clock that were not over
747    /// it in CPU time (the thread waited; the stage was not slow).
748    #[serde(default, skip_serializing_if = "is_zero_u64")]
749    pub capture_stage_preempted_over_budget: u64,
750    /// With the thread's CPU time: blocks long enough on the wall clock to count as slow
751    /// whatever their CPU time.
752    #[serde(default, skip_serializing_if = "is_zero_u64")]
753    pub capture_stage_starved: u64,
754    /// How the OS schedules the processing thread the stage runs on (absent before the
755    /// pipeline reports it).
756    #[serde(default, skip_serializing_if = "Option::is_none")]
757    pub capture_stage_dsp_scheduling: Option<CaptureDspScheduling>,
758    /// The scheduling mode asked for (`NoiseRemovalControl::set_dsp_sched`, or the default)
759    /// and the mode the processing thread runs in. Absent before the pipeline reports them,
760    /// and on a platform without these calls unless a mode was asked for.
761    #[serde(default, skip_serializing_if = "Option::is_none")]
762    pub capture_stage_dsp_sched_requested: Option<CaptureDspSchedMode>,
763    #[serde(default, skip_serializing_if = "Option::is_none")]
764    pub capture_stage_dsp_sched_effective: Option<CaptureDspSchedMode>,
765    /// Why the mode in effect is not the mode asked for.
766    #[serde(default, skip_serializing_if = "Option::is_none")]
767    pub capture_stage_dsp_sched_fallback: Option<CaptureDspSchedFallback>,
768    /// The time-constraint figures asked for, microseconds (absent in the modes that do not
769    /// ask for the policy).
770    #[serde(default, skip_serializing_if = "Option::is_none")]
771    pub capture_stage_dsp_period_us: Option<u32>,
772    #[serde(default, skip_serializing_if = "Option::is_none")]
773    pub capture_stage_dsp_computation_us: Option<u32>,
774    #[serde(default, skip_serializing_if = "Option::is_none")]
775    pub capture_stage_dsp_constraint_us: Option<u32>,
776    /// The deadline of each block's work interval, microseconds
777    /// ([`CaptureDspSchedMode::OwnWorkgroup`] only).
778    #[serde(default, skip_serializing_if = "Option::is_none")]
779    pub capture_stage_dsp_interval_deadline_us: Option<u32>,
780    /// Work intervals finished on the thread's own workgroup so far.
781    #[serde(default, skip_serializing_if = "is_zero_u64")]
782    pub capture_stage_dsp_intervals: u64,
783}
784
785fn is_zero(v: &u32) -> bool {
786    *v == 0
787}
788
789fn is_zero_u64(v: &u64) -> bool {
790    *v == 0
791}
792
793fn is_false(v: &bool) -> bool {
794    !*v
795}
796
797impl NoiseRemovalState {
798    /// A state, as an engine reports it.
799    pub fn new(
800        mode: NoiseRemoval,
801        active: NoiseRemoval,
802        reason: Option<NoiseRemovalReason>,
803    ) -> NoiseRemovalState {
804        NoiseRemovalState {
805            mode,
806            active,
807            reason,
808            model: None,
809            model_reason: None,
810            step_downs: 0,
811            phone_mode: None,
812            phone_mode_reason: None,
813            phone_mode_switches: 0,
814            phone_mode_gap_ms: None,
815            step_down_reason: None,
816            last_step_down_ms_ago: None,
817            slowest_block_us: None,
818            blocks_over_budget: 0,
819            in_grace: false,
820            dfn3_state: None,
821            retry_in_ms: None,
822            grace_step_downs: 0,
823            slowest_block_cpu_us: None,
824            p99_block_us: None,
825            p99_block_cpu_us: None,
826            capture_stage_strikes: 0,
827            capture_stage_bypassed: None,
828            capture_stage_p99_us: None,
829            capture_stage_grace: false,
830            capture_stage_grace_blocks: 0,
831            capture_stage_grace_over_budget: 0,
832            capture_stage_last_transient: None,
833            capture_stage_clock: None,
834            capture_stage_max_wall_us: None,
835            capture_stage_preempted_over_budget: 0,
836            capture_stage_starved: 0,
837            capture_stage_dsp_scheduling: None,
838            capture_stage_dsp_sched_requested: None,
839            capture_stage_dsp_sched_effective: None,
840            capture_stage_dsp_sched_fallback: None,
841            capture_stage_dsp_period_us: None,
842            capture_stage_dsp_computation_us: None,
843            capture_stage_dsp_constraint_us: None,
844            capture_stage_dsp_interval_deadline_us: None,
845            capture_stage_dsp_intervals: 0,
846        }
847    }
848
849    /// This state without the counters that change with every block
850    /// (`last_step_down_ms_ago`, `slowest_block_us`, `blocks_over_budget`, `retry_in_ms`,
851    /// `slowest_block_cpu_us`, `p99_block_us`, `p99_block_cpu_us`, `capture_stage_p99_us`) and
852    /// the pipeline's grace, clock and scheduling fields: what a change of state is judged on.
853    #[cfg_attr(not(feature = "audio-core"), allow(dead_code))]
854    pub(crate) fn change_key(mut self) -> NoiseRemovalState {
855        self.last_step_down_ms_ago = None;
856        self.slowest_block_us = None;
857        self.blocks_over_budget = 0;
858        self.retry_in_ms = None;
859        self.slowest_block_cpu_us = None;
860        self.p99_block_us = None;
861        self.p99_block_cpu_us = None;
862        self.capture_stage_p99_us = None;
863        self.capture_stage_grace = false;
864        self.capture_stage_grace_blocks = 0;
865        self.capture_stage_grace_over_budget = 0;
866        self.capture_stage_last_transient = None;
867        self.capture_stage_clock = None;
868        self.capture_stage_max_wall_us = None;
869        self.capture_stage_preempted_over_budget = 0;
870        self.capture_stage_starved = 0;
871        self.capture_stage_dsp_scheduling = None;
872        self.capture_stage_dsp_sched_requested = None;
873        self.capture_stage_dsp_sched_effective = None;
874        self.capture_stage_dsp_sched_fallback = None;
875        self.capture_stage_dsp_period_us = None;
876        self.capture_stage_dsp_computation_us = None;
877        self.capture_stage_dsp_constraint_us = None;
878        self.capture_stage_dsp_interval_deadline_us = None;
879        self.capture_stage_dsp_intervals = 0;
880        self
881    }
882
883    /// This state with the phone's capture, why it is not what the setting asks for
884    /// (`switch_failed`), the call's switches and the last switch's pause (ms).
885    pub fn with_phone_mode(
886        mut self,
887        phone_mode: Option<PhoneAudioMode>,
888        phone_mode_reason: Option<NoiseRemovalReason>,
889        switches: u32,
890        gap_ms: Option<u32>,
891    ) -> NoiseRemovalState {
892        self.phone_mode = phone_mode;
893        self.phone_mode_reason = phone_mode_reason;
894        self.phone_mode_switches = switches;
895        self.phone_mode_gap_ms = gap_ms;
896        self
897    }
898
899    /// This state with the model that runs, why it is not DeepFilterNet3 when that was wanted,
900    /// and the step-downs so far.
901    pub fn with_model(
902        mut self,
903        model: Option<NoiseModel>,
904        model_reason: Option<NoiseRemovalReason>,
905        step_downs: u32,
906    ) -> NoiseRemovalState {
907        self.model = model;
908        self.model_reason = model_reason;
909        self.step_downs = step_downs;
910        self
911    }
912
913    /// `mode` running as asked.
914    pub fn running(mode: NoiseRemoval) -> NoiseRemovalState {
915        NoiseRemovalState::new(mode, mode, None)
916    }
917
918    /// `mode` asked, nothing of ours running, for `reason` (`Off` asked: nothing is missing,
919    /// so no reason).
920    pub fn stepped_down(mode: NoiseRemoval, reason: NoiseRemovalReason) -> NoiseRemovalState {
921        if mode == NoiseRemoval::Off {
922            NoiseRemovalState::running(NoiseRemoval::Off)
923        } else {
924            NoiseRemovalState::new(mode, NoiseRemoval::Off, Some(reason))
925        }
926    }
927}
928
929#[cfg(test)]
930mod tests {
931    #![allow(clippy::unwrap_used)]
932    use super::*;
933
934    #[test]
935    fn names_and_json() {
936        assert_eq!(NoiseRemoval::default(), NoiseRemoval::Standard);
937        for m in NoiseRemoval::ALL {
938            assert_eq!(NoiseRemoval::from_name(m.as_str()), Some(m));
939            assert_eq!(
940                serde_json::to_value(m).unwrap(),
941                serde_json::json!(m.as_str())
942            );
943        }
944        assert_eq!(NoiseRemoval::from_name("strong"), None);
945        assert_eq!(NoiseRemoval::from_name("Standard"), None);
946        let s = NoiseRemovalState::running(NoiseRemoval::Standard);
947        assert_eq!(
948            serde_json::to_value(s).unwrap(),
949            serde_json::json!({"mode": "standard", "active": "standard"})
950        );
951        let s = NoiseRemovalState::stepped_down(NoiseRemoval::Standard, NoiseRemovalReason::Budget);
952        assert_eq!(
953            serde_json::to_value(s).unwrap(),
954            serde_json::json!({"mode": "standard", "active": "off", "reason": "budget"})
955        );
956        for (r, n) in [
957            (NoiseRemovalReason::Budget, "budget"),
958            (NoiseRemovalReason::Fault, "fault"),
959            (NoiseRemovalReason::Unavailable, "unavailable"),
960            (NoiseRemovalReason::SwitchFailed, "switch_failed"),
961            (NoiseRemovalReason::Loading, "loading"),
962        ] {
963            assert_eq!(r.as_str(), n);
964            assert_eq!(serde_json::to_value(r).unwrap(), serde_json::json!(n));
965        }
966        assert_eq!(
967            NoiseRemovalState::stepped_down(NoiseRemoval::Off, NoiseRemovalReason::Fault),
968            NoiseRemovalState::running(NoiseRemoval::Off)
969        );
970        let back: NoiseRemovalState =
971            serde_json::from_value(serde_json::json!({"mode": "off", "active": "off"})).unwrap();
972        assert_eq!(back, NoiseRemovalState::running(NoiseRemoval::Off));
973    }
974
975    #[test]
976    fn model_fields_json() {
977        let s = NoiseRemovalState::running(NoiseRemoval::Standard).with_model(
978            Some(NoiseModel::Dfn3),
979            None,
980            0,
981        );
982        assert_eq!(
983            serde_json::to_value(s).unwrap(),
984            serde_json::json!({"mode": "standard", "active": "standard", "model": "dfn3"})
985        );
986        let s = NoiseRemovalState::running(NoiseRemoval::Standard).with_model(
987            Some(NoiseModel::Rnnoise),
988            Some(NoiseRemovalReason::Budget),
989            2,
990        );
991        let v = serde_json::to_value(s).unwrap();
992        assert_eq!(
993            v,
994            serde_json::json!({"mode": "standard", "active": "standard", "model": "rnnoise",
995                "model_reason": "budget", "step_downs": 2})
996        );
997        let back: NoiseRemovalState = serde_json::from_value(v).unwrap();
998        assert_eq!(back, s);
999        for (m, n) in [(NoiseModel::Dfn3, "dfn3"), (NoiseModel::Rnnoise, "rnnoise")] {
1000            assert_eq!(m.as_str(), n);
1001            assert_eq!(serde_json::to_value(m).unwrap(), serde_json::json!(n));
1002        }
1003    }
1004
1005    /// The timing fields: absent when unset (the JSON is as before), their names when set, read
1006    /// back; the counters do not make a change by themselves, the reason and the grace do.
1007    #[test]
1008    fn timing_fields_json() {
1009        let base = NoiseRemovalState::running(NoiseRemoval::Standard);
1010        assert_eq!(
1011            serde_json::to_value(base).unwrap(),
1012            serde_json::json!({"mode": "standard", "active": "standard"})
1013        );
1014        let mut s = base;
1015        s.step_down_reason = Some(NoiseStepDownReason::SlowWindow);
1016        s.last_step_down_ms_ago = Some(1_234);
1017        s.slowest_block_us = Some(7_100);
1018        s.blocks_over_budget = 3;
1019        s.in_grace = true;
1020        s.dfn3_state = Some(NoiseDfn3State::SteppedDown);
1021        s.retry_in_ms = Some(4_200);
1022        s.grace_step_downs = 1;
1023        s.slowest_block_cpu_us = Some(1_300);
1024        s.p99_block_us = Some(6_900);
1025        s.p99_block_cpu_us = Some(900);
1026        s.capture_stage_strikes = 1;
1027        s.capture_stage_bypassed = Some(NoiseRemovalReason::Budget);
1028        s.capture_stage_p99_us = Some(6_200);
1029        s.capture_stage_grace = true;
1030        s.capture_stage_grace_blocks = 150;
1031        s.capture_stage_grace_over_budget = 4;
1032        s.capture_stage_last_transient = Some(CaptureTransient::CameraStart);
1033        s.capture_stage_clock = Some(CaptureStageClock::ThreadCpu);
1034        s.capture_stage_max_wall_us = Some(21_000);
1035        s.capture_stage_preempted_over_budget = 5;
1036        s.capture_stage_starved = 1;
1037        s.capture_stage_dsp_scheduling = Some(CaptureDspScheduling::TimeConstraint);
1038        let v = serde_json::to_value(s).unwrap();
1039        assert_eq!(
1040            v,
1041            serde_json::json!({"mode": "standard", "active": "standard",
1042                "step_down_reason": "slow_window", "last_step_down_ms_ago": 1234,
1043                "slowest_block_us": 7100, "blocks_over_budget": 3, "in_grace": true,
1044                "dfn3_state": "stepped_down", "retry_in_ms": 4200, "grace_step_downs": 1,
1045                "slowest_block_cpu_us": 1300, "p99_block_us": 6900, "p99_block_cpu_us": 900,
1046                "capture_stage_strikes": 1, "capture_stage_bypassed": "budget",
1047                "capture_stage_p99_us": 6200, "capture_stage_grace": true,
1048                "capture_stage_grace_blocks": 150, "capture_stage_grace_over_budget": 4,
1049                "capture_stage_last_transient": "camera_start",
1050                "capture_stage_clock": "thread_cpu", "capture_stage_max_wall_us": 21000,
1051                "capture_stage_preempted_over_budget": 5, "capture_stage_starved": 1,
1052                "capture_stage_dsp_scheduling": "time_constraint"})
1053        );
1054        let back: NoiseRemovalState = serde_json::from_value(v).unwrap();
1055        assert_eq!(back, s);
1056        for (r, n) in [
1057            (NoiseStepDownReason::SlowBlock, "slow_block"),
1058            (NoiseStepDownReason::SlowWindow, "slow_window"),
1059            (NoiseStepDownReason::Heavy, "heavy"),
1060            (NoiseStepDownReason::Fault, "fault"),
1061            (NoiseStepDownReason::Forced, "forced"),
1062            (NoiseStepDownReason::Starved, "starved"),
1063        ] {
1064            assert_eq!(r.as_str(), n);
1065            assert_eq!(r.to_string(), n);
1066            assert_eq!(serde_json::to_value(r).unwrap(), serde_json::json!(n));
1067        }
1068        for (d, n) in [
1069            (NoiseDfn3State::Idle, "idle"),
1070            (NoiseDfn3State::Warming, "warming"),
1071            (NoiseDfn3State::Running, "running"),
1072            (NoiseDfn3State::SteppedDown, "stepped_down"),
1073            (NoiseDfn3State::Retired, "retired"),
1074        ] {
1075            assert_eq!(d.as_str(), n);
1076            assert_eq!(d.to_string(), n);
1077            assert_eq!(serde_json::to_value(d).unwrap(), serde_json::json!(n));
1078        }
1079        // An older reader's JSON (none of the new fields) reads with them unset.
1080        let old: NoiseRemovalState = serde_json::from_value(serde_json::json!({
1081            "mode": "standard", "active": "standard", "slowest_block_us": 7100}))
1082        .unwrap();
1083        assert_eq!(
1084            (old.dfn3_state, old.retry_in_ms, old.grace_step_downs),
1085            (None, None, 0)
1086        );
1087        // The counters ride along; the reason, the grace and the strikes make a change.
1088        let mut counters = base;
1089        counters.last_step_down_ms_ago = Some(10);
1090        counters.slowest_block_us = Some(1);
1091        counters.blocks_over_budget = 9;
1092        counters.capture_stage_p99_us = Some(5);
1093        counters.retry_in_ms = Some(3_000);
1094        counters.slowest_block_cpu_us = Some(2);
1095        counters.p99_block_us = Some(3);
1096        counters.p99_block_cpu_us = Some(4);
1097        counters.capture_stage_grace = true;
1098        counters.capture_stage_grace_blocks = 7;
1099        counters.capture_stage_grace_over_budget = 2;
1100        counters.capture_stage_last_transient = Some(CaptureTransient::AppSceneChange);
1101        counters.capture_stage_clock = Some(CaptureStageClock::Wall);
1102        counters.capture_stage_max_wall_us = Some(9);
1103        counters.capture_stage_preempted_over_budget = 3;
1104        counters.capture_stage_starved = 1;
1105        counters.capture_stage_dsp_scheduling = Some(CaptureDspScheduling::Workgroup);
1106        assert_eq!(counters.change_key(), base.change_key());
1107        for (d, n) in [
1108            (CaptureDspScheduling::Workgroup, "workgroup"),
1109            (CaptureDspScheduling::TimeConstraint, "time_constraint"),
1110            (CaptureDspScheduling::Qos, "qos"),
1111            (CaptureDspScheduling::None, "none"),
1112        ] {
1113            assert_eq!(d.as_str(), n);
1114            assert_eq!(d.to_string(), n);
1115            assert_eq!(serde_json::to_value(d).unwrap(), serde_json::json!(n));
1116            let back: CaptureDspScheduling = serde_json::from_value(serde_json::json!(n)).unwrap();
1117            assert_eq!(back, d);
1118        }
1119        for (c, n) in [
1120            (CaptureStageClock::ThreadCpu, "thread_cpu"),
1121            (CaptureStageClock::Wall, "wall"),
1122        ] {
1123            assert_eq!(c.as_str(), n);
1124            assert_eq!(c.to_string(), n);
1125            assert_eq!(serde_json::to_value(c).unwrap(), serde_json::json!(n));
1126        }
1127        for (t, n) in [
1128            (CaptureTransient::CallStart, "call_start"),
1129            (
1130                CaptureTransient::AudioSessionActivated,
1131                "audio_session_activated",
1132            ),
1133            (CaptureTransient::RouteChange, "route_change"),
1134            (CaptureTransient::CameraStart, "camera_start"),
1135            (CaptureTransient::AppSceneChange, "app_scene_change"),
1136            (CaptureTransient::Other, "other"),
1137        ] {
1138            assert_eq!(t.as_str(), n);
1139            assert_eq!(t.to_string(), n);
1140            assert_eq!(serde_json::to_value(t).unwrap(), serde_json::json!(n));
1141        }
1142        // Where DeepFilterNet3 is, and the step-downs tied to grace, make a change.
1143        let mut state = base;
1144        state.dfn3_state = Some(NoiseDfn3State::Warming);
1145        assert_ne!(state.change_key(), base.change_key());
1146        let mut tied = base;
1147        tied.grace_step_downs = 1;
1148        assert_ne!(tied.change_key(), base.change_key());
1149        let mut grace = base;
1150        grace.in_grace = true;
1151        assert_ne!(grace.change_key(), base.change_key());
1152        let mut reason = base;
1153        reason.step_down_reason = Some(NoiseStepDownReason::Heavy);
1154        assert_ne!(reason.change_key(), base.change_key());
1155        let mut strikes = base;
1156        strikes.capture_stage_strikes = 1;
1157        assert_ne!(strikes.change_key(), base.change_key());
1158    }
1159
1160    /// The phone fields: absent when unset (the JSON is as before), present when set, and
1161    /// read back.
1162    #[test]
1163    fn phone_fields_json() {
1164        let s = NoiseRemovalState::running(NoiseRemoval::Off).with_phone_mode(
1165            Some(PhoneAudioMode::Raw),
1166            None,
1167            0,
1168            None,
1169        );
1170        assert_eq!(
1171            serde_json::to_value(s).unwrap(),
1172            serde_json::json!({"mode": "off", "active": "off", "phone_mode": "raw"})
1173        );
1174        let s = NoiseRemovalState::running(NoiseRemoval::Off).with_phone_mode(
1175            Some(PhoneAudioMode::Os),
1176            Some(NoiseRemovalReason::SwitchFailed),
1177            3,
1178            Some(42),
1179        );
1180        let v = serde_json::to_value(s).unwrap();
1181        assert_eq!(
1182            v,
1183            serde_json::json!({"mode": "off", "active": "off", "phone_mode": "os",
1184                "phone_mode_reason": "switch_failed", "phone_mode_switches": 3,
1185                "phone_mode_gap_ms": 42})
1186        );
1187        let back: NoiseRemovalState = serde_json::from_value(v).unwrap();
1188        assert_eq!(back, s);
1189        for (m, n) in [(PhoneAudioMode::Os, "os"), (PhoneAudioMode::Raw, "raw")] {
1190            assert_eq!(m.as_str(), n);
1191            assert_eq!(m.to_string(), n);
1192            assert_eq!(serde_json::to_value(m).unwrap(), serde_json::json!(n));
1193        }
1194        assert_eq!(
1195            PhoneAudioMode::for_mode(NoiseRemoval::Off),
1196            PhoneAudioMode::Raw
1197        );
1198        assert_eq!(
1199            PhoneAudioMode::for_mode(NoiseRemoval::Standard),
1200            PhoneAudioMode::Os
1201        );
1202    }
1203}