kessel_audio/lib.rs
1//! # kessel-audio
2//!
3//! A real-time voice audio pipeline in pure Rust, for apps that carry live
4//! calls over their own transport. It owns everything between the
5//! microphone and speaker and the encoded frames on the wire:
6//!
7//! - **devices:** capture and playback through cpal (CoreAudio, WASAPI,
8//! ALSA), device lists, hot-plug, switching, and a null device for
9//! headless use; on iOS and Android, the OS's own voice processing
10//! (`Backend::OsVoiceProcessing`), or raw capture with sonora's echo
11//! cancellation and no noise suppression (`PhoneMode::Raw`), switchable
12//! mid-call;
13//! - **resampling** between the device rate and 48 kHz (rubato);
14//! - **echo cancellation, noise suppression and gain control** (sonora, a
15//! port of WebRTC's audio processing), with the playback mix as the echo
16//! reference;
17//! - **a capture stage** of your own (a noise-removal model, say) between
18//! echo cancellation and gain control, held to a time budget (on the
19//! processing thread's CPU time where the platform has it, [`StageClock`])
20//! with a bypass that never shifts the timing, and a grace window for the
21//! host's transient events ([`CaptureStage`],
22//! [`AudioEngine::transient_event`]);
23//! - **Opus** encode and decode (ropus), 48 kHz mono, 20 ms frames, with
24//! the caller's bitrate, FEC, DTX and complexity;
25//! - **a jitter buffer per participant** with loss concealment and FEC
26//! recovery;
27//! - **mixing**, **levels** (about every 50 ms) and **statistics**.
28//!
29//! The transport (RTP, encryption, signalling) stays outside: kessel-audio
30//! produces plaintext [`EncodedFrame`]s and consumes [`RecvFrame`]s that the
31//! transport has already decrypted and verified.
32//!
33//! ## Example
34//!
35//! ```no_run
36//! use kessel_audio::{AudioEngine, EngineConfig, RecvFrame};
37//!
38//! let engine = AudioEngine::start(EngineConfig::default())?;
39//! let frames = engine.capture_frames();
40//! engine.add_participant(7);
41//! loop {
42//! // Send path: encrypt and send each encoded frame.
43//! while let Some(f) = frames.try_recv() {
44//! let _ = (f.payload, f.ts48k);
45//! }
46//! // Receive path: hand over each decrypted, verified packet.
47//! # let packet: Option<RecvFrame> = None;
48//! if let Some(p) = packet {
49//! engine.push(p);
50//! }
51//! # break;
52//! }
53//! # Ok::<(), kessel_audio::AudioError>(())
54//! ```
55//!
56//! ## Threads
57//!
58//! [`AudioEngine`] is a `Send + Sync` handle; no async runtime is needed.
59//! Device callbacks only move samples through lock-free rings; one
60//! processing thread does the signal processing and codec work; a control
61//! thread handles devices and events. On macOS and iOS the processing thread
62//! runs real-time (by default the QoS class, Mach's time-constraint policy,
63//! and on iOS the audio unit's OS workgroup; [`EngineConfig::dsp_sched`]
64//! picks another [`DspSchedMode`]) and the capture callback wakes it;
65//! [`Stats::dsp_scheduling`] says which it got ([`DspScheduling`]) and
66//! [`Stats::dsp_sched`] the mode in effect. Every queue between the caller and
67//! the engine is bounded and lock-free, and the audio side never blocks on
68//! one: a full queue drops (and counts) instead.
69
70// The thread CPU clock (`stage::thread_cpu`, on macOS, iOS, Linux and
71// Android), the processing thread's scheduling and work intervals
72// (`sched::apple`, on macOS and iOS), macOS's microphone permission calls (`mic::macos`) and the phone
73// backends' OS calls (`phone::ios`, `phone::android`) are the only `unsafe`
74// outside tests.
75#![cfg_attr(
76 not(any(
77 test,
78 target_os = "linux",
79 target_os = "android",
80 target_os = "macos",
81 target_os = "ios"
82 )),
83 forbid(unsafe_code)
84)]
85#![cfg_attr(
86 any(
87 test,
88 target_os = "linux",
89 target_os = "android",
90 target_os = "macos",
91 target_os = "ios"
92 ),
93 deny(unsafe_code)
94)]
95
96mod apm;
97mod codec;
98mod config;
99mod device;
100mod engine;
101mod error;
102mod events;
103mod frame;
104mod jitter;
105mod level;
106#[cfg(feature = "cpal")]
107mod mic;
108mod null;
109#[cfg(any(
110 test,
111 all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
112))]
113mod phone;
114mod pipeline;
115mod resample;
116mod sched;
117mod stage;
118mod stats;
119#[cfg(feature = "cpal")]
120mod system;
121
122// Runs the README's examples as doctests.
123#[cfg(doctest)]
124#[doc = include_str!("../README.md")]
125struct ReadmeDoctests;
126
127#[cfg(test)]
128mod testkit;
129#[cfg(test)]
130mod tests;
131
132pub use apm::{NoiseSuppressionStrength, ProcessingConfig, AGC2_HEADROOM_DB};
133/// The `bytes` crate, re-exported so callers build payloads with the same
134/// version.
135pub use bytes;
136pub use config::{Backend, EngineConfig};
137pub use device::{CaptureSource, NullDevice, PlaybackSink};
138pub use engine::AudioEngine;
139pub use error::{AudioError, ErrorCode};
140pub use events::{
141 DeviceChoice, DeviceInfo, DeviceList, DeviceSelection, DevicesInUse, Event, EventRx, Level,
142 Levels,
143};
144pub use frame::{
145 EncodedFrame, EncoderCfg, FrameRx, RecvFrame, FEC_LOSS_HINT_PCT, FRAME_MS, FRAME_SAMPLES,
146 SAMPLE_RATE,
147};
148pub use jitter::JitterConfig;
149#[cfg(all(feature = "os-voice", any(target_os = "ios", target_os = "android")))]
150pub use phone::{OsEffects, OsVoiceConfig, PhoneMode, PhoneModeChange, RawCapture};
151pub use sched::{
152 DspSchedConfig, DspSchedFallback, DspSchedMode, DspSchedStats, DspScheduling, DspTimeConstraint,
153};
154pub use stage::{
155 CaptureStage, CaptureStageStats, StageBypassReason, StageClock, TransientEvent,
156 DEFAULT_STAGE_GRACE, DEFAULT_STAGE_STARVATION_CUTOFF, MAX_STAGE_GRACE,
157 MAX_STAGE_LATENCY_SAMPLES,
158};
159pub use stats::{CaptureStats, ParticipantStats, Stats};