Skip to content

About

A lock-free, zero-allocation audio processing chain for Kotlin Multiplatform.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

audio-processing-chain

A lock-free, zero-allocation audio processing chain for Kotlin Multiplatform.

Real-time audio comes in the size the capture device produces it in, and every processor wants its own: WebRTC's echo canceller, noise suppressor and AGC2 and RNNoise's denoiser take 10 ms blocks, at a rate each of them supports. The chain sits between them — frames of any size go in, each stage is handed exactly the block size its processor is defined for, and what the last stage produced comes out of a queue of its own.

val chain = AudioProcessingChain()
chain.addStage(160) { block -> aec3.process(block) }        // 10 ms in place
chain.addStage(160) { block -> suppressor.process(block) }  // 10 ms in place
chain.addStage(160) { block -> agc2.process(block) }        // 10 ms in place

Steady state neither locks nor allocates: the queues are single-producer / single-consumer rings, the frames a stage produces come from a fixed-size pool and are recycled, and a stage's processor is called with the same array every time — no copies beyond the samples that change hands. A producer allocates the one frame it hands over per callback; the chain owns it from then on and reuses its array further down.

Get it

The library is on Maven Central as cn.enaium:audio-processing-chain (the Kotlin Multiplatform root, every target and the Android AAR) and on npm as @enaium/audio-processing-chain (the JavaScript build with its numbers-based facade):

dependencies {
    implementation("cn.enaium:audio-processing-chain:1.0.0")
}
npm install @enaium/audio-processing-chain

Supported Platforms

The library is pure Kotlin with no platform code of its own, so it builds for every target Kotlin Multiplatform offers, JavaScript and WebAssembly included:

Family Targets
JVM jvm
Android android, androidNativeArm64, androidNativeArm32, androidNativeX64, androidNativeX86
Apple iosArm64, iosX64, iosSimulatorArm64, macosArm64, macosX64, tvosArm64, tvosSimulatorArm64, watchosArm64, watchosSimulatorArm64, watchosDeviceArm64
Linux linuxX64, linuxArm64
Windows mingwX64
Web js, wasmJs

./gradlew build compiles the library and its tests for all of them, and runs the tests on the targets the machine can run them on: the JVM, Android's JVM (testAndroidHostTest), the native host (macosArm64Test on macOS) and Node (jsTest, wasmJsTest). There is nothing to publish — the chain is one Gradle project, and project(":") is what the examples depend on.

The JavaScript build also ships as the npm package @enaium/audio-processing-chain (see npm below), the way the other Kotlin Multiplatform libraries of this family ship what a web consumer needs.

Layout

Path What it is
src/commonMain The library: the chain and its parts (AudioProcessingChain, ProcessingStage, AudioRingBuffer, AudioFrame, AudioFramePool), the stage contract (BlockProcessor), the rate boundary and resampler contract (RateBoundary, BlockResampler), the block stager, the PCM conversions (Pcm), and the measurement utilities (LevelMeter, SampleHistory)
src/commonTest Its tests, shared by every target
examples/common The processors of the chain (AEC3, WebRTC NS or RNNoise, AGC2) and ProcessingChain, the chain they are assembled on, plus signal generation and the number formatting both examples print with
examples/waveform Live input/output waveform viewer, drawn with imgui-kmp/ImPlot
examples/benchmark What the chain and its processors cost, fed as fast as they take blocks
examples/waveform/android The Android application that hosts the waveform example

Usage

import cn.enaium.apc.AudioFrame
import cn.enaium.apc.AudioProcessingChain

val chain = AudioProcessingChain()

// A stage accumulates whatever it is given into blocks of its own size and
// calls the processor with one block at a time, in place.
chain.addStage(160) { block -> echo.process(block) }
chain.addStage(160) { block -> gain.process(block) }

// Producer side - a capture callback, say. The chain owns the samples of the
// frame it is handed, so this is the last time the caller touches them.
chain.inputQueue.offer(AudioFrame(captured))

// Consumer side. process() runs the stages until nothing is left to process,
// however much audio accumulated since the last call.
chain.process()
while (true) {
    val frame = chain.outputQueue.poll() ?: break
    output.write(frame.data)
}

Design Notes

Framing. A stage buffers what it is given until it holds batchSize samples, calls its processor with exactly those, and offers the result to the next stage. Frames may be any size: one smaller than a batch is buffered, one larger is split across as many batches as it covers, and a stage whose batch does not divide the next stage's (160 into 480, as RNNoise's conversion has it) simply buffers the remainder. No stage has to know what the others run with.

Ownership. Frames flow one way. Once a frame is offered, the chain owns it: it is recycled through the pool and its array is reused for a batch further down the chain. A producer therefore hands over a frame it does not touch again, and a consumer reads a frame only until it pulls the next one.

Threads. The queues are SPSC rings, so a producer may offer on inputQueue from its own thread while a consumer polls outputQueue from another. The chain itself is single-threaded: one thread calls process(), and the stage processors and the frame pool are not shared with anyone (@Volatile indexes apart, nothing in a stage is atomic, and a frame is never touched by two threads at once).

Latency. Each stage adds up to one batch: audio waits there until the block is full. At the example's 16 kHz, the chain's three 160-sample stages buffer 3 × 10 ms at worst, and on average half of that, so process() hands out what whole blocks it was given rather than what was just captured.

Plumbing. What a program around the chain would otherwise write itself ships with it: BlockProcessor pins a processor to the block size it is defined for, BlockStager turns a device's counts into those blocks, RateBoundary converts between the rate a device runs at and the one the chain does - one block either way, the way out restaged when a stage's batch does not fill one - LevelMeter and SampleHistory are what a level display and a waveform read from, and FloatArray.toInt16 / ShortArray.toUnitFloats are the two conversions between the int16 samples of the API and the -1..1 floats of the DSP. Each of them works on buffers it is handed, so the audio path keeps its allocations to the one frame a producer hands over.

Cost. The framework is not what costs: measured with examples/benchmark, a chain of five identity stages is under 1 µs per 10 ms block on the JVM and ~4.5 µs on Kotlin/Native, well under 2% of what the processors in it cost. See examples/benchmark for the whole table.

Examples

examples/waveform

A live view of what enters and what leaves the chain: the two traces share one amplitude axis, so the gain AGC2 applies and the noise the suppressors remove are what the difference between them looks like. The example takes audio in and puts it out at 8 kHz — the telephone rate — while the chain itself runs at the 16 kHz its processors prefer, so the boundary converts on the way in and out. The chain it draws is the one examples/common builds, in the order WebRTC's own audio pipeline runs them - echo cancelled, then noise suppressed, then gain applied - out of five published libraries:

Part Library What it runs on
Echo cancellation stage webrtc-aec3-kmp 160 samples (10 ms @ 16 kHz); the far end is whatever the example plays through the speaker
Noise suppression stage, one of the two webrtc-ns-kmp 160 samples (10 ms @ 16 kHz)
rnnoise-kmp 160 samples @ 16 kHz, converted in the stage to the 480 @ 48 kHz RNNoise is defined for
Gain control stage webrtc-agc2-kmp 160 samples (10 ms @ 16 kHz)
Rate conversion webrtc-resampler-kmp The 8 kHz ↔ 16 kHz boundary around the chain, and a capture device that runs at neither

The window is drawn by imgui-kmp (ImPlot over an SDL3 window), the devices are opened with audio-io-kmp.

./gradlew :examples:waveform:jvmRun                                   # microphone
./gradlew :examples:waveform:jvmRun --args="--frames 300 --source tone"
./gradlew :examples:waveform:runDebugExecutableMacosArm64             # native
./gradlew :examples:waveform:android:installDebug                     # device/emulator

The suppressor is a choice, not two switches: the combo lists the ones this target has a variant for - RNNoise's and WebRTC's on the JVM, Android and WebAssembly, RNNoise's alone on native, neither on js - and the chain runs the chosen one between the echo canceller and the gain controller. RNNoise is the default, so the chain is AEC3 → RNNoise → AGC2 until the combo says otherwise. On native AGC2 is off too (see the notes below), so the chain there is AEC3 and RNNoise.

Option (JVM) Environment (native) Meaning
--source NAME APC_WAVEFORM_SOURCE microphone (default), tone, noise or sweep
--frames N APC_WAVEFORM_FRAMES Stop after N frames, for automated runs
--window N APC_WAVEFORM_WINDOW Plotted window in milliseconds, 100…10000

The microphone is the default source; the generated ones are for runs that have no device, and for a signal whose level and spectrum are known. A run prints one line per device it opens and a summary of what the chain did with the audio.

examples/benchmark

Feeds the chain as fast as it takes the blocks — no window, no device — over a fixed amount of generated audio, and prints what each configuration cost. Rows are the framework on its own (identity stages), each processor on the block size its stage runs with, and the chain the waveform example builds.

./gradlew :examples:benchmark:jvmRun                                    # ~20 s
./gradlew :examples:benchmark:jvmRun --args="--seconds 120 --source noise"
./gradlew :examples:benchmark:runReleaseExecutableMacosArm64
./gradlew :examples:benchmark:wasmBenchmarkRun                         # Node, glues first
./gradlew :examples:benchmark:jsBenchmarkRun                           # Node, js build

The web runs load the npm glue packages of the chain's web stages before the Kotlin module - the web targets of these libraries are Emscripten modules whose C API has to be published as globals first, which the plain wasmJsNodeProductionRun cannot do. The wasmJs run covers the noise suppressor, AGC2 and RNNoise; the js one, where only AGC2 has a variant, measures that stage alone.

Measured on an Apple M5 (macOS 27, JDK 26, Kotlin/Native release build), 60 s of audio per run, three runs per row, the fastest reported. On the JVM every stage runs; natively AGC2 and WebRTC's suppressor cannot (see the notes below), and on the web targets AEC3 has no variant, so each platform measures the stages it has. The two suppressors are measured both alone and in the chain, since which one runs is the example's choice:

Row JVM µs/block JVM % of a core Native µs/block Native % of a core wasmJs µs/block wasmJs % of a core
generate only (baseline) 0.9 0.01 1.2 0.01 4.0 0.04
chain only (5 × 160) (framework) 0.8 0.01 1.4 0.01 4.4 0.04
8 kHz boundary (in + out) 2.2 0.02 3.2 0.03 10.5 0.11
aec3 alone 86.0 0.86 90.5 0.90 — —
webrtc ns alone 3.7 0.04 — — 10.1 0.10
agc2 alone 9.9 0.10 — — 24.3 0.24
rnnoise alone 177.4 1.77 183.2 1.83 245.3 2.45
the chain, WebRTC's suppressor 101.1 1.01 — — 30.8 0.31
the chain, RNNoise (the default) 279.2 2.79 274.9 2.75 266.6 2.67
the example's pipeline (boundary + chain + metres) 281.1 2.81 278.9 2.79 276.2 2.76

% of a core is the share of one core a second of audio costs: the chain with RNNoise comes out at ~36× real time (so a 60 fps view of it has room to spare) and the one with WebRTC's suppressor at ~99×, and the chain's own framing is 0.3% (JVM) / 0.5% (native) / 1.7% (wasmJs) of the heavier one. RNNoise and AEC3 dominate; WebRTC's suppressor is nearly free next to either. What the waveform example adds around the chain - the boundary both ways, a level meter and the plots' history per block - is 2 µs (JVM) / 4 µs (native) / 10 µs (wasmJs), i.e. the pipeline row is the chain row plus less than 1%. On js, where only AGC2 has a variant, the whole chain measures 22 µs per block - the stage alone. The numbers move by a few percent between runs on a busy machine, and --seconds trades accuracy for time (the framework rows are microseconds per block and need the long runs to be meaningful).

The example's view costs more than its pipeline: scan walks the whole window on every drawn frame, so 2 plots over the longest 10 s window (80,000 samples into 1024 min/max columns each) measure 328 µs per frame on the JVM, 342 µs on Kotlin/Native and 142 µs on wasmJs - about 2% of a core at 60 fps, and a tenth of that at the 1 s window the controls start at. It only rescans when a frame is drawn, so it never touches the audio path; the way to cut it is an incrementally maintained envelope (per-column min/max as samples arrive) rather than a full scan per frame, which is worth doing if long windows at high frame rates become the common case.

A debug Kotlin/Native build - what runDebugExecutableMacosArm64 runs - costs 334 µs per block for the same pipeline instead of 279 µs, because the time is in the C++ of the processors, which the Kotlin build mode does not touch: even the debug example keeps ~30× real time.

npm

./gradlew assembleNpm stages the package in build/npm: the compiled JavaScript module with a JsAudioProcessingChain facade whose API is plain numbers (Int32Array in and out, a JavaScript function as the stage's processor), because the chain's own types are ShortArray, which JavaScript cannot construct. The module exports its Kotlin packages by name, so the facade is reached through the one it lives in:

const { cn } = require('@enaium/audio-processing-chain')
const { JsAudioProcessingChain } = cn.enaium.apc
``` `./gradlew publishNpm` publishes it to npm; the token comes
from the `npm.publish.key` Gradle property, exactly like the other packages of
this family. The WebAssembly target is consumed from Kotlin, through the
Maven artifacts, where the full API - not only the numbers-based facade - is
available.

## Building

```bash
./gradlew build              # library + examples, every target the machine can build
./gradlew jvmTest            # the library's tests on the JVM
./gradlew macosArm64Test     # ... and on the native host
./gradlew testAndroidHostTest

./gradlew :examples:waveform:jvmRun
./gradlew :examples:benchmark:jvmRun

The examples need Android's SDK for their Android targets (sdk.dir in local.properties or ANDROID_HOME); everything else is fetched from Maven Central by the Gradle build.

Notes

  • The webrtc klibs collide on Kotlin/Native. Each of the four cn.enaium.webrtc klibs statically embeds its own copy of WebRTC's support code under the same symbol names (WebRtcSpl_AnalysisQMF, WebRtc_GetCPUInfo, rtc::LogMessage, rtc::GlobalLock, ...). Linked into one binary, Linux refuses the duplicate symbols outright, and on macOS - where ld64 quietly keeps whichever copy it saw first - the echo canceller's copies win while AGC2's and the noise suppressor's lose: the first call into either dereferences state the winning copy never initialized and the process dies with SIGSEGV (webrtc_agc2_audio_buffer_get_channel_data, webrtc_ns_suppressor_analyze). The AEC3, resampler and RNNoise stages coexist natively, which is what the example runs there. The JVM and Android targets are unaffected altogether, because each library is a shared library of its own there, and on the web each is its own Emscripten module. examples/common expresses all of this per tier: every stage is created by a factory whose actual says whether it runs on that target, and the suppressor combo only offers the ones that exist there.
  • mingwX64 and linuxX64 examples. The library builds and tests for both, but the examples do not target them. MinGW: audio-io-kmp's WASAPI binding leaves CLSID_MMDeviceEnumerator, the IID_IAudio* and PKEY_Device_FriendlyName undefined, and Kotlin/Native's MinGW sysroot has no import library that provides them. Linux: the rolling webrtc-agc2-kmp archive references the C23 __isoc23_strtoul family, which needs the glibc of a distribution from 2023 on and which the glibc 2.19 of Kotlin/Native's sysroot does not define. Both platforms are covered by the JVM target of the same libraries.
  • Apple simulator tests. The Kotlin plugin registers iosSimulatorArm64Test and friends wherever Xcode is installed, but running one needs a simulator runtime Xcode does not ship by default; they are skipped so build does not stop on a machine that has none. Everything else about those targets — klibs and test binaries — is still built.

License

MIT, see LICENSE.

About

A lock-free, zero-allocation audio processing chain for Kotlin Multiplatform.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages