use crate::error::{AudioError, ErrorCode};
use crate::frame::BLOCK_SAMPLES;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::time::{Duration, Instant};
pub trait CaptureStage: Send + 'static {
fn process(&mut self, block: &mut [f32; BLOCK_SAMPLES]);
fn latency_samples(&self) -> usize;
fn reset(&mut self);
}
pub const MAX_STAGE_LATENCY_SAMPLES: usize = 48_000;
pub(crate) const HARD_BUDGET: Duration = Duration::from_millis(9);
pub(crate) const HARD_RUN: u32 = 2;
pub(crate) const P99_BUDGET: Duration = Duration::from_millis(6);
pub(crate) const WINDOW: usize = 100;
pub(crate) const RETRY_BLOCKS: u64 = 1_000;
pub(crate) const MAX_STRIKES: usize = 3;
pub(crate) const STRIKE_SPAN_BLOCKS: u64 = 6_000;
pub const DEFAULT_STAGE_GRACE: Duration = Duration::from_millis(1_500);
pub const MAX_STAGE_GRACE: Duration = Duration::from_secs(10);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TransientEvent {
CallStart,
AudioSessionActivated,
RouteChange,
CameraStart,
AppSceneChange,
Other,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StageBypassReason {
Budget,
Fault,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CaptureStageStats {
pub active: bool,
pub bypassed: Option<StageBypassReason>,
pub permanent: bool,
pub fallback_noise_suppression: bool,
pub strikes: u32,
pub latency_samples: u32,
pub blocks_processed: u64,
pub blocks_bypassed: u64,
pub max_block_us: u32,
pub p99_block_us: u32,
pub grace: bool,
pub grace_blocks: u64,
pub grace_over_budget: u64,
pub last_transient: Option<TransientEvent>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Active,
Warming(u32),
Bypassed(Option<u64>),
}
#[derive(Clone, Debug)]
pub(crate) enum StageClock {
Wall,
#[cfg(test)]
Manual(std::sync::Arc<std::sync::atomic::AtomicU64>),
}
impl StageClock {
fn now(&self, base: Instant) -> Duration {
match self {
StageClock::Wall => base.elapsed(),
#[cfg(test)]
StageClock::Manual(ns) => {
Duration::from_nanos(ns.load(std::sync::atomic::Ordering::Relaxed))
}
}
}
}
pub(crate) struct StageRunner {
clock: StageClock,
epoch: Instant,
slow_run: u32,
strike_blocks: [u64; MAX_STRIKES],
budget_strikes: usize,
stage: Box<dyn CaptureStage>,
latency: usize,
delay: Box<[f32]>,
pos: usize,
work: [f32; BLOCK_SAMPLES],
window: [u32; WINDOW],
graced: [bool; WINDOW],
sorted: [u32; WINDOW],
win_len: usize,
win_pos: usize,
over_p99: usize,
mode: Mode,
blocks: u64,
stats: CaptureStageStats,
changed: bool,
dirty: bool,
used_stage: bool,
grace_len: u64,
grace_until: u64,
grace_mark: u64,
}
impl StageRunner {
pub(crate) fn new(
stage: Box<dyn CaptureStage>,
grace: Duration,
) -> Result<StageRunner, AudioError> {
Self::with_clock(stage, StageClock::Wall, grace)
}
pub(crate) fn with_clock(
stage: Box<dyn CaptureStage>,
clock: StageClock,
grace: Duration,
) -> Result<StageRunner, AudioError> {
let latency = stage.latency_samples();
if latency > MAX_STAGE_LATENCY_SAMPLES {
return Err(AudioError::new(
ErrorCode::InvalidConfig,
format!(
"capture stage latency {latency} samples is over {MAX_STAGE_LATENCY_SAMPLES}"
),
));
}
let mut runner = StageRunner {
clock,
epoch: Instant::now(),
slow_run: 0,
strike_blocks: [0; MAX_STRIKES],
budget_strikes: 0,
stage,
latency,
delay: vec![0.0; latency].into_boxed_slice(),
pos: 0,
work: [0.0; BLOCK_SAMPLES],
window: [0; WINDOW],
graced: [false; WINDOW],
sorted: [0; WINDOW],
win_len: 0,
win_pos: 0,
over_p99: 0,
mode: Mode::Active,
blocks: 0,
stats: CaptureStageStats {
active: true,
latency_samples: latency as u32,
..CaptureStageStats::default()
},
changed: false,
dirty: false,
used_stage: false,
grace_len: grace_blocks(grace),
grace_until: 0,
grace_mark: 0,
};
runner.reset_stage();
runner.open_grace(None);
Ok(runner)
}
pub(crate) fn latency(&self) -> usize {
self.latency
}
pub(crate) fn used_stage(&self) -> bool {
self.used_stage
}
pub(crate) fn set_fallback(&mut self, on: bool) {
self.stats.fallback_noise_suppression = on;
}
pub(crate) fn open_grace(&mut self, event: Option<TransientEvent>) {
if event.is_some() {
self.stats.last_transient = event;
}
if self.grace_len == 0 {
return;
}
if !self.stats.grace {
self.stats.grace = true;
self.grace_mark = self.stats.grace_over_budget;
}
self.grace_until = self
.grace_until
.max(self.blocks.saturating_add(self.grace_len));
}
pub(crate) fn process(&mut self, block: &mut [f32; BLOCK_SAMPLES]) {
self.blocks += 1;
self.used_stage = false;
let grace = self.blocks <= self.grace_until;
if self.stats.grace && !grace {
self.stats.grace = false;
if self.stats.grace_over_budget > self.grace_mark {
self.changed = true;
}
}
self.work.copy_from_slice(block);
self.delay_in_place(block);
if let Mode::Bypassed(retry) = self.mode {
match retry {
Some(at) if self.blocks >= at => {
if !self.reset_stage() {
self.stats.blocks_bypassed += 1;
return;
}
self.clear_window();
self.mode = match self.warm_blocks() {
0 => Mode::Active,
n => Mode::Warming(n),
};
self.stats.active = self.mode == Mode::Active;
self.changed = true;
}
_ => {
self.stats.blocks_bypassed += 1;
return;
}
}
}
let t = self.clock.now(self.epoch);
let r = catch_unwind(AssertUnwindSafe(|| self.stage.process(&mut self.work)));
let took = self.clock.now(self.epoch).saturating_sub(t);
self.dirty = true;
self.stats.blocks_processed += 1;
let us = took.as_micros().min(u32::MAX as u128) as u32;
self.stats.max_block_us = self.stats.max_block_us.max(us);
if grace {
self.stats.grace_blocks += 1;
if took > P99_BUDGET {
self.stats.grace_over_budget += 1;
}
}
if r.is_err() || !self.work.iter().all(|v| v.is_finite()) {
self.strike(StageBypassReason::Fault);
self.stats.blocks_bypassed += 1;
return;
}
self.push_time(us, grace);
self.slow_run = if took >= HARD_BUDGET && !grace {
self.slow_run + 1
} else {
0
};
if self.slow_run >= HARD_RUN || (self.win_len == WINDOW && self.over_p99 >= 2) {
self.strike(StageBypassReason::Budget);
self.stats.blocks_bypassed += 1;
return;
}
match self.mode {
Mode::Active => {
block.copy_from_slice(&self.work);
self.used_stage = true;
}
Mode::Warming(n) => {
self.stats.blocks_bypassed += 1;
if n <= 1 {
self.mode = Mode::Active;
self.stats.active = true;
self.changed = true;
} else {
self.mode = Mode::Warming(n - 1);
}
}
Mode::Bypassed(_) => unreachable!("handled above"),
}
}
pub(crate) fn reset(&mut self) {
self.open_grace(None);
self.delay.fill(0.0);
self.pos = 0;
match self.mode {
Mode::Active | Mode::Warming(_) if self.dirty => {
if self.reset_stage() {
self.clear_window();
if self.mode != Mode::Active {
self.mode = Mode::Active;
self.stats.active = true;
self.changed = true;
}
}
}
Mode::Active | Mode::Warming(_) | Mode::Bypassed(_) => {}
}
}
pub(crate) fn stats(&mut self) -> CaptureStageStats {
let mut s = self.stats;
s.p99_block_us = self.p99_us();
s
}
pub(crate) fn take_changed(&mut self) -> bool {
std::mem::take(&mut self.changed)
}
fn warm_blocks(&self) -> u32 {
self.latency.div_ceil(BLOCK_SAMPLES) as u32
}
fn reset_stage(&mut self) -> bool {
if catch_unwind(AssertUnwindSafe(|| self.stage.reset())).is_err() {
self.strike(StageBypassReason::Fault);
false
} else {
self.dirty = false;
true
}
}
fn strike(&mut self, why: StageBypassReason) {
self.stats.strikes += 1;
self.stats.bypassed = Some(why);
self.stats.active = false;
let mut permanent = why == StageBypassReason::Fault;
if why == StageBypassReason::Budget {
self.strike_blocks[self.budget_strikes % MAX_STRIKES] = self.blocks;
self.budget_strikes += 1;
if self.budget_strikes >= MAX_STRIKES {
let oldest = self.strike_blocks[self.budget_strikes % MAX_STRIKES];
permanent = self.blocks - oldest <= STRIKE_SPAN_BLOCKS;
}
}
self.stats.permanent = permanent;
self.mode = Mode::Bypassed((!permanent).then_some(self.blocks + RETRY_BLOCKS));
self.clear_window();
self.changed = true;
}
fn delay_in_place(&mut self, block: &mut [f32; BLOCK_SAMPLES]) {
let l = self.latency;
if l == 0 {
return;
}
for v in block.iter_mut() {
std::mem::swap(&mut self.delay[self.pos], v);
self.pos += 1;
if self.pos == l {
self.pos = 0;
}
}
}
fn push_time(&mut self, us: u32, graced: bool) {
let limit = P99_BUDGET.as_micros() as u32;
if self.win_len == WINDOW {
if self.window[self.win_pos] > limit && !self.graced[self.win_pos] {
self.over_p99 -= 1;
}
} else {
self.win_len += 1;
}
self.window[self.win_pos] = us;
self.graced[self.win_pos] = graced;
if us > limit && !graced {
self.over_p99 += 1;
}
self.win_pos = (self.win_pos + 1) % WINDOW;
}
fn clear_window(&mut self) {
self.win_len = 0;
self.win_pos = 0;
self.over_p99 = 0;
self.slow_run = 0;
}
fn p99_us(&mut self) -> u32 {
let n = self.win_len;
if n == 0 {
return 0;
}
let s = &mut self.sorted[..n];
s.copy_from_slice(&self.window[..n]);
let rank = (n * 99).div_ceil(100).max(1) - 1;
*s.select_nth_unstable(rank).1
}
}
fn grace_blocks(grace: Duration) -> u64 {
let block = Duration::from_millis(10).as_nanos();
grace.as_nanos().div_ceil(block).min(u64::MAX as u128) as u64
}