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);
pub const DEFAULT_STAGE_STARVATION_CUTOFF: Duration = Duration::from_millis(20);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StageClock {
ThreadCpu,
Wall,
}
impl StageClock {
pub const fn is_supported(self) -> bool {
match self {
StageClock::ThreadCpu => thread_cpu::SUPPORTED,
StageClock::Wall => true,
}
}
}
impl Default for StageClock {
fn default() -> Self {
if thread_cpu::SUPPORTED {
StageClock::ThreadCpu
} else {
StageClock::Wall
}
}
}
#[cfg(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios"
))]
pub(crate) mod thread_cpu {
use std::mem::MaybeUninit;
use std::time::Duration;
pub(crate) const SUPPORTED: bool = true;
#[allow(unsafe_code)]
pub(crate) fn now() -> Option<Duration> {
let mut ts = MaybeUninit::<libc::timespec>::uninit();
let ts = unsafe {
if libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, ts.as_mut_ptr()) != 0 {
return None;
}
ts.assume_init()
};
Some(Duration::new(
u64::try_from(ts.tv_sec).ok()?,
u32::try_from(ts.tv_nsec).ok()?,
))
}
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios"
)))]
pub(crate) mod thread_cpu {
use std::time::Duration;
pub(crate) const SUPPORTED: bool = false;
pub(crate) fn now() -> Option<Duration> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct StageTiming {
pub(crate) grace: Duration,
pub(crate) clock: StageClock,
pub(crate) starvation_cutoff: Duration,
}
impl Default for StageTiming {
fn default() -> Self {
StageTiming {
grace: DEFAULT_STAGE_GRACE,
clock: StageClock::default(),
starvation_cutoff: DEFAULT_STAGE_STARVATION_CUTOFF,
}
}
}
#[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>,
pub clock: StageClock,
pub max_wall_us: u32,
pub preempted_over_budget: u64,
pub starved: u64,
pub dsp_scheduling: crate::DspScheduling,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Active,
Warming(u32),
Bypassed(Option<u64>),
}
#[derive(Clone, Debug)]
pub(crate) enum TimeSource {
Os,
#[cfg(test)]
Manual(std::sync::Arc<ManualTime>),
}
#[cfg(test)]
#[derive(Debug, Default)]
pub(crate) struct ManualTime {
cpu_ns: std::sync::atomic::AtomicU64,
wall_ns: std::sync::atomic::AtomicU64,
}
#[cfg(test)]
impl ManualTime {
pub(crate) fn work_us(&self, us: u64) {
use std::sync::atomic::Ordering::Relaxed;
self.cpu_ns.fetch_add(us * 1_000, Relaxed);
self.wall_ns.fetch_add(us * 1_000, Relaxed);
}
pub(crate) fn preempt_us(&self, us: u64) {
self.wall_ns
.fetch_add(us * 1_000, std::sync::atomic::Ordering::Relaxed);
}
}
#[derive(Clone, Copy)]
struct Reading {
wall: Duration,
cpu: Option<Duration>,
}
impl TimeSource {
fn read(&self, base: Instant, cpu: bool, start: bool) -> Reading {
match self {
TimeSource::Os => {
let cpu_now = || if cpu { thread_cpu::now() } else { None };
if start {
let wall = base.elapsed();
Reading {
wall,
cpu: cpu_now(),
}
} else {
let cpu = cpu_now();
Reading {
wall: base.elapsed(),
cpu,
}
}
}
#[cfg(test)]
TimeSource::Manual(t) => {
use std::sync::atomic::Ordering::Relaxed;
Reading {
wall: Duration::from_nanos(t.wall_ns.load(Relaxed)),
cpu: cpu.then(|| Duration::from_nanos(t.cpu_ns.load(Relaxed))),
}
}
}
}
fn resolve(&self, want: StageClock) -> StageClock {
match want {
StageClock::ThreadCpu if self.read(Instant::now(), true, true).cpu.is_some() => {
StageClock::ThreadCpu
}
_ => StageClock::Wall,
}
}
}
pub(crate) struct StageRunner {
time: TimeSource,
cpu_clock: bool,
starvation_cutoff: Duration,
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>,
timing: StageTiming,
) -> Result<StageRunner, AudioError> {
Self::with_source(stage, TimeSource::Os, timing)
}
pub(crate) fn with_source(
stage: Box<dyn CaptureStage>,
time: TimeSource,
timing: StageTiming,
) -> 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 clock = time.resolve(timing.clock);
let mut runner = StageRunner {
time,
cpu_clock: clock == StageClock::ThreadCpu,
starvation_cutoff: timing.starvation_cutoff,
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,
clock,
..CaptureStageStats::default()
},
changed: false,
dirty: false,
used_stage: false,
grace_len: grace_blocks(timing.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 t0 = self.time.read(self.epoch, self.cpu_clock, true);
let r = catch_unwind(AssertUnwindSafe(|| self.stage.process(&mut self.work)));
let t1 = self.time.read(self.epoch, self.cpu_clock, false);
let wall = t1.wall.saturating_sub(t0.wall);
let (took, starved) = match (t0.cpu, t1.cpu) {
(Some(a), Some(b)) => {
let cpu = b.saturating_sub(a);
if wall > P99_BUDGET && cpu <= P99_BUDGET {
self.stats.preempted_over_budget += 1;
}
let starved = wall >= self.starvation_cutoff;
if starved {
self.stats.starved += 1;
}
(cpu, starved)
}
_ => (wall, false),
};
self.dirty = true;
self.stats.blocks_processed += 1;
let us = micros(took);
self.stats.max_block_us = self.stats.max_block_us.max(us);
self.stats.max_wall_us = self.stats.max_wall_us.max(micros(wall));
if grace {
self.stats.grace_blocks += 1;
if took > P99_BUDGET || starved {
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 || starved) && !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 micros(d: Duration) -> u32 {
d.as_micros().min(u32::MAX as u128) as u32
}
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
}