Files
chanora/crates/chanora_audio/src/lib.rs
T
EdisonJwa 7188a5a69d feat(perf,benchmark-infra): criterion bench harness + advisory CI workflows (SDD-120)
Implementation of SDD-120 §1-§8:

Bench harness (crates/chanora_audio/benches/):
- common.rs: deterministic synthetic audio (440 Hz sine, no RNG).
- realtime_capture.rs: bench_capture_alloc_count (dhat) +
  bench_capture_callback_wall_clock (criterion).
- opus_codec.rs: bench_opus_encode_latency + bench_opus_decode_latency
  (direct audiopus, not AudioHandler — SDD-120 §3 item 4).
- resampler.rs: bench_resampler_throughput across 44.1->48 /
  16->48 / 48->48 passthrough.

CI tooling (crates/chanora_audio/examples/):
- emit_baseline.rs: aggregates criterion estimates.json outputs
  into the SRS-217 baseline schema.
- compare_baseline.rs: applies SRS-219 tolerance, renders markdown
  table with 🟢/🟡/🔴 markers + yellow simpler-form realization per
  SDD-120 §8.

  Deviation from SDD-120 §2 / §5 / §7 placement: these tools live
  under examples/, not benches/ or src/bin/. Rationale: they must
  consume serde_json (a dev-only dep — production builds must not
  pull it). Cargo only resolves dev-dependencies for [[test]],
  [[bench]], and [[example]] targets; [[bin]] targets under
  src/bin/ see only regular [dependencies]. examples/ keeps the
  binaries out of the production dep tree while still giving them
  cargo run --example invocation. An SDD-120 amendment should
  reflect this.

Workflows (.github/workflows/):
- bench-advisory.yml: PR + push triggers; runs benches; posts a
  sticky PR comment via actions/github-script@v7; job status is
  always success (SRS-218 clause 4 — non-blocking).
- bench-baseline-update.yml: workflow_dispatch only; runs benches;
  opens PR via peter-evans/create-pull-request@v6 (sole writer of
  the SAD-089 baseline JSON).

Cargo.toml additions ([dev-dependencies] only — verified excluded
from --release builds): criterion 0.5, dhat 0.3, serde_json 1.

Source-code seam: minimal pub-but-#[doc(hidden)] bench_seam module
in chanora_audio (engine.rs + lib.rs re-export) so the criterion
bench harness can construct a CaptureState and drive
CaptureState::ingest without re-implementing the engine (SDD-120
§3). Non-iOS targets only — CaptureState itself is iOS-gated.

Initial baseline seed: crates/chanora_audio/benches/baselines/
x86_64-unknown-linux-gnu.json = {}. compare_baseline handles the
missing-baseline case gracefully and emits a 'no red markers'
report; the first manual dispatch of bench-baseline-update.yml
after merge establishes the real values.

Out of scope per SDD-120 §10: production telemetry export,
build-failing hard CI gate, multi-host benchmarking, IDE
integration, Dart-side bridge round-trip bench.

Verification:
- cargo check --workspace --all-targets: PASS.
- cargo bench --bench realtime_capture --no-run: PASS.
- cargo bench --bench opus_codec --no-run: PASS.
- cargo bench --bench resampler --no-run: PASS.
- cargo build --example emit_baseline --example compare_baseline
  -p chanora_audio: PASS.
- cargo test --workspace: 106 passed, 0 failed, 3 ignored — no
  regression from prior count.
2026-05-18 13:52:15 +08:00

128 lines
4.1 KiB
Rust

//! # `chanora_audio`
//!
//! Audio subsystem promoted from `poc/audio-capture-playback-spike`
//! and wired against `chanora_protocol`'s voice channels.
//!
//! ## What's wired in this Beta
//!
//! * Default-input capture via `cpal` (DEC-011.1)
//! * Frame-aligned 20 ms / 48 kHz mono Opus encoding via `audiopus`
//! * Forward encoded frames to the protocol crate as `OutPacket`s
//! * Inbound voice packets fed to `tsclientlib::audio::AudioHandler`
//! which owns Opus decode + per-client jitter buffer + mix
//! * Mixed f32 PCM pulled by the cpal output callback at 48 kHz stereo
//! * Push-to-talk: capture stream is permanently open; encoding is
//! gated by an atomic `ptt_active` flag
//!
//! ## What's NOT wired in this Beta
//!
//! * AEC / AGC / NS / HPF DSP chain (DEC-007/008/009/010 — Beta+
//! work; the toggles in `AudioEffects` are honoured by *naming*
//! but the filters are no-ops)
//! * Mobile audio paths (DEC-011.1 desktop + Android proven; this
//! integration is desktop-only for v0.2.0-beta.1)
//! * Hot-plug device-change handling
//! * Sample-rate adaptation if the device cannot do 48 kHz / mono in
//! the format we request (returns `AudioError::StreamConfig`)
//! * Multi-channel speaker layouts beyond stereo
#![warn(missing_docs)]
mod engine;
pub mod mobile_voice_backend;
pub mod mode_stack;
pub mod ptt;
pub mod ptt_backends;
pub mod release_tail;
pub mod transmit_mode;
pub mod transmit_selector;
#[cfg(target_os = "linux")]
mod sdl_output;
#[cfg(target_os = "ios")]
mod ios_voice_unit;
#[cfg(target_os = "android")]
pub mod android_voice_unit;
pub use engine::{AudioEngine, AudioEngineConfig};
// SDD-120 §3 bench seam — `#[doc(hidden)]` re-export so the criterion
// bench harness under `crates/chanora_audio/benches/` can construct a
// CaptureState and drive `ingest` without re-implementing the engine.
// Not part of the supported public API.
#[cfg(not(target_os = "ios"))]
#[doc(hidden)]
pub use engine::bench_seam;
pub use ptt::{AudioTransmitGate, MissedKeyUpWatchdog, PttBackendDescriptor, PttCapabilityLevel};
pub use ptt_backends::{
select as select_ptt_backend, DesktopPttBackend, FocusedPttBackend, PttBackendError,
PttBinding, PttInputClass,
};
pub use release_tail::{ReleaseTailTimer, DEFAULT_TAIL_MS, MAX_TAIL_MS};
pub use transmit_mode::TransmitMode;
pub use transmit_selector::{PermissionGate, TransmitModeSelector};
use thiserror::Error;
/// Errors raised by the audio subsystem.
#[derive(Debug, Error)]
pub enum AudioError {
/// Platform did not expose a usable default input device.
#[error("no default input device")]
NoInputDevice,
/// Platform did not expose a usable default output device.
#[error("no default output device")]
NoOutputDevice,
/// The audio backend rejected a stream configuration.
#[error("stream config rejected: {0}")]
StreamConfig(String),
/// Opus codec init/encode/decode failure.
#[error("opus: {0}")]
Opus(String),
/// A backend-specific failure surfaced without a typed mapping.
#[error("audio backend: {0}")]
Backend(String),
}
/// Audio-effect toggles. Defaults match DEC-007 (AEC),
/// DEC-008 (AGC), DEC-009 (NS), DEC-010 (HPF) — all enabled.
///
/// Note: in Beta v0.2.0-beta.1 the actual DSP filters are not yet
/// implemented; the struct is kept here as the public API surface so
/// later work can flip an internal flag without breaking callers.
#[derive(Debug, Clone, Copy)]
pub struct AudioEffects {
/// Acoustic echo cancellation (DEC-007).
pub aec: bool,
/// Automatic gain control (DEC-008).
pub agc: bool,
/// Noise suppression (DEC-009).
pub noise_suppression: bool,
/// High-pass filter (DEC-010).
pub high_pass: bool,
}
impl Default for AudioEffects {
fn default() -> Self {
Self {
aec: true,
agc: true,
noise_suppression: true,
high_pass: true,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_match_decisions() {
let e = AudioEffects::default();
assert!(e.aec && e.agc && e.noise_suppression && e.high_pass);
}
}