Skip to content

LanguageIdiomaภาษา

Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core

Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust CoreDSP de audio de baja latencia con Rust: AAudio y Oboe desde un núcleo en RustDSP เสียงความหน่วงต่ำด้วย Rust: AAudio และ Oboe จากคอร์ Rust

Rust & NativeRust y nativoRust และเนทีฟ

ByPorโดย David Cruz Anaya, Mobile & Applied AI EngineerIngeniero sénior de móvil e IA aplicada (Android, Kotlin Multiplatform, IA de producto)วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

Updated 25 September 2026Actualizado el 25 de septiembre de 2026อัปเดตเมื่อ 25 กันยายน 20269 min read9 min de lecturaอ่าน 9 นาที
AndroidRustNDKAudioAAudioDSP
Share:Compartir:แชร์:

Rust + NDK on Android, Part 10 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Threading and Async: Tokio, Kotlin Coroutines, and Calling Back Into Kotlin from Rust. Next: Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust.

You can hold a real-time audio deadline on Android from pure Rust, with no C++ in the build. AAudio, the platform’s low latency audio API since Android 8.0, is a plain C API (Android Developers, AAudio guide), and the ndk crate wraps it in safe Rust, callback included. In this part you’ll open a low latency output stream from a Rust cdylib and render a synth through a gain and filter chain that never allocates. A Kotlin slider drives the gain and the filter cutoff while it plays, and nothing on either side takes a lock.

This is the Rust counterpart to my modern C++ audio guide. Rust’s compiler enforces more of those audio-thread rules than C++. It assumes the toolchain from Part 1, the handle pattern from Part 7, and the threading rules from Part 9.

Key Takeaways

  • A Rust cdylib can drive AAudio directly through the ndk crate’s audio module. minSdk must be 26 or higher, because the crate links libaaudio.so.
  • The callback contract is the one Google documents for Oboe: no allocation, no locks, no I/O, which rules out JNI as well. Rust checks the sharing rules at compile time; allocation stays your discipline.
  • Parameters cross to the audio thread as f32 bit patterns in an AtomicU32 with Relaxed ordering. No mutex, no torn reads, no priority inversion.
  • Oboe still earns its place below minSdk 26 or when you want its per-device workarounds. The oboe crate wraps the C++ library for Rust.

Why Rust fits low latency audio on Android

An audio callback is the hardest deadline most app code ever meets. The stream calls you every few milliseconds, you fill a buffer, and if you are late the user hears a click. Google’s rules for that callback are explicit: no memory allocation, no file or network I/O, no mutexes or other synchronization primitives, no sleeping, no closing the stream from inside it (Google’s Oboe Full Guide). JNI fails several of those at once, which is why the audio thread never touches Kotlin, a rule Part 9 established.

In C++ that list lives in code review. In Rust, a useful chunk of it moves into the type system. The ndk crate’s data callback is a boxed FnMut closure that must be Send, so state moved into it must prove it can cross threads, and anything shared with the UI thread must be Sync, which pushes you straight to atomics and lock-free queues. The stream handle is !Send, so the compiler refuses to let you stash it in a global. And the data race that corrupts one buffer a week on one device model, the bug that pushed me from C++ toward Rust, cannot be written in safe Rust.

Be honest about the other half. Vec::push in the callback compiles without a warning, and so does Mutex::lock. Rust has no garbage collector, which removes the JVM’s class of glitches, but the allocator is still non-deterministic and still forbidden. The compiler shrinks the list you enforce by discipline; it does not empty it.

Opening an AAudio stream from Rust

The crate needs jni for the boundary and ndk with its audio feature for AAudio. This is rust/audiofx/Cargo.toml in full:

[package]
name = "audiofx"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
jni = "0.21"
ndk = { version = "0.9", features = ["audio"] }

The audio feature links libaaudio.so, which exists on API 26 and later, so set minSdk = 26. Below that, skip ahead to the Oboe section.

Everything else lives in rust/audiofx/src/lib.rs, starting with imports, constants, and the stream setup:

use std::f32::consts::PI;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

use jni::objects::JClass;
use jni::sys::{jfloat, jlong};
use jni::JNIEnv;
use ndk::audio::{
    AudioCallbackResult, AudioDirection, AudioFormat, AudioPerformanceMode,
    AudioSharingMode, AudioStream, AudioStreamBuilder,
};

const SAMPLE_RATE: i32 = 48_000;
const CHANNELS: i32 = 2;
const FREQUENCY_HZ: f32 = 220.0;

/// Owns the stream and the parameters shared with the audio thread.
pub struct Engine {
    stream: AudioStream,
    params: Arc<SharedParams>,
}

fn start_engine() -> ndk::audio::Result<Engine> {
    let params = Arc::new(SharedParams::new());
    let mut dsp = Dsp {
        phase: 0.0,
        lp_state: 0.0,
        params: Arc::clone(&params),
    };

    let stream = AudioStreamBuilder::new()?
        .direction(AudioDirection::Output)
        .format(AudioFormat::PCM_Float)
        .channel_count(CHANNELS)
        .sample_rate(SAMPLE_RATE)
        .performance_mode(AudioPerformanceMode::LowLatency)
        .sharing_mode(AudioSharingMode::Exclusive)
        .data_callback(Box::new(move |_stream, data, num_frames| {
            // SAFETY: AAudio hands us num_frames frames in the format
            // and channel count we requested: interleaved f32 samples.
            let samples = unsafe {
                std::slice::from_raw_parts_mut(
                    data.cast::<f32>(),
                    (num_frames * CHANNELS) as usize,
                )
            };
            dsp.render(samples);
            AudioCallbackResult::Continue
        }))
        .open_stream()?;

    stream.request_start()?;
    Ok(Engine { stream, params })
}

Three settings do the latency work. LowLatency asks for smaller buffers and the optimized data path, Exclusive asks for sole access to the device, and the callback lets the platform drive the timing. The AAudio guide ties the lowest latency to the LowLatency mode with a callback, and calls exclusive streams likely to have lower latency but more likely to get disconnected (Android Developers, AAudio guide).

Two production notes. The builder is a request, not a promise: the device may hand you a shared stream or a different rate, so real code reads stream.sample_rate() after opening, instead of trusting my SAMPLE_RATE constant, and recomputes whatever depends on it. And streams die in normal use, headphones unplug, so register an error_callback and rebuild when it fires.

A DSP chain that never allocates

The synth is deliberately small: a naive sawtooth into a one-pole low-pass into a gain stage. A saw rather than a sine because harmonics let you hear the filter move. The Dsp struct and its render function, also in rust/audiofx/src/lib.rs:

/// All DSP state, allocated once before the stream starts and
/// moved into the audio callback.
struct Dsp {
    phase: f32,
    lp_state: f32,
    params: Arc<SharedParams>,
}

impl Dsp {
    fn render(&mut self, samples: &mut [f32]) {
        let gain = SharedParams::load(&self.params.gain);
        let cutoff = SharedParams::load(&self.params.cutoff_hz);

        // Plain arithmetic only: no allocation, no locks, no syscalls.
        let dt = 1.0 / SAMPLE_RATE as f32;
        let rc = 1.0 / (2.0 * PI * cutoff);
        let alpha = dt / (rc + dt);
        let step = FREQUENCY_HZ / SAMPLE_RATE as f32;

        for frame in samples.chunks_exact_mut(CHANNELS as usize) {
            // Naive sawtooth in [-1.0, 1.0]. It aliases; fine for a demo.
            let raw = 2.0 * self.phase - 1.0;
            self.phase += step;
            if self.phase >= 1.0 {
                self.phase -= 1.0;
            }
            // One-pole low-pass, then gain.
            self.lp_state += alpha * (raw - self.lp_state);
            let sample = self.lp_state * gain;
            for channel_sample in frame.iter_mut() {
                *channel_sample = sample;
            }
        }
    }
}

Everything the callback needs was allocated before the stream started: oscillator phase, filter state, and the Arc to the shared parameters live inside Dsp, moved into the closure, moved into the stream. From first callback to last, render touches nothing but its own fields and the buffer AAudio handed it, with chunks_exact_mut walking the interleaved stereo frames.

Because the callback must be Send, the compiler checks every field of Dsp for thread-crossing safety. Swap the Arc for an Rc, or sneak in a JNIEnv, and the crate stops compiling with an error naming the field. In C++ that mistake ships, then glitches on a Tuesday.

Passing parameters without locks

The user drags a slider on the main thread; the audio thread needs the value a few milliseconds later. A Mutex is the obvious answer and the forbidden one: if the audio thread waits on a lock held by a lower-priority thread, the deadline is gone. The C++ post used std::atomic<float>. Rust has no stable AtomicF32, so we store the float’s bits in an AtomicU32. The sharing side of rust/audiofx/src/lib.rs:

/// Parameters shared between the UI thread and the audio thread.
/// Each f32 is stored as its raw bits in an AtomicU32, so the
/// audio thread reads them without ever taking a lock.
pub struct SharedParams {
    gain: AtomicU32,
    cutoff_hz: AtomicU32,
}

impl SharedParams {
    fn new() -> Self {
        Self {
            gain: AtomicU32::new(0.5f32.to_bits()),
            cutoff_hz: AtomicU32::new(2_000.0f32.to_bits()),
        }
    }

    fn store(cell: &AtomicU32, value: f32) {
        cell.store(value.to_bits(), Ordering::Relaxed);
    }

    fn load(cell: &AtomicU32) -> f32 {
        f32::from_bits(cell.load(Ordering::Relaxed))
    }
}

Each parameter has one writer, the UI thread, and one reader, the callback. The reader tolerates a value one buffer stale, and no other memory operation depends on the order of these stores. What Relaxed still guarantees is that every read is a complete 32-bit value: a torn float is impossible. A stronger ordering buys nothing.

Single values only get you so far. Events, note on and note off, need a queue lock-free at both ends: the SPSC ring buffer the C++ post builds by hand around two atomic indices. The rtrb crate is a realtime-safe SPSC ring buffer that never allocates after construction; this synth does not need one, so it stays the named next step.

Wiring the Kotlin slider

The boundary uses the raw-pointer handle pattern from Part 7: nativeStart boxes the engine and hands Kotlin the address as a Long, the setters borrow it, and nativeStop reclaims and drops it, closing the stream. There is a Rust reason for it: AudioStream is !Send, so the compiler rejects parking the engine in a static. The handle keeps ownership on the main thread; the audio thread only ever sees the atomics inside the Arc. These functions close out rust/audiofx/src/lib.rs:

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeStart(
    _env: JNIEnv,
    _class: JClass,
) -> jlong {
    match start_engine() {
        Ok(engine) => Box::into_raw(Box::new(engine)) as jlong,
        Err(_) => 0,
    }
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeSetGain(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
    gain: jfloat,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { &*(handle as *const Engine) };
    SharedParams::store(&engine.params.gain, gain.clamp(0.0, 1.0));
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeSetCutoff(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
    cutoff_hz: jfloat,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { &*(handle as *const Engine) };
    SharedParams::store(&engine.params.cutoff_hz, cutoff_hz.clamp(40.0, 8_000.0));
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeStop(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { Box::from_raw(handle as *mut Engine) };
    let _ = engine.stream.request_stop();
    // Dropping the engine closes the stream.
}

The Kotlin bridge is four externals in app/src/main/java/dev/davthecoder/rustseries/AudioFx.kt:

package dev.davthecoder.rustseries

object AudioFx {
    init {
        System.loadLibrary("audiofx")
    }

    external fun nativeStart(): Long
    external fun nativeStop(handle: Long)
    external fun nativeSetGain(handle: Long, gain: Float)
    external fun nativeSetCutoff(handle: Long, cutoffHz: Float)
}

The whole UI is one Compose screen in app/src/main/java/dev/davthecoder/rustseries/SynthScreen.kt:

package dev.davthecoder.rustseries

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun SynthScreen() {
    var handle by remember { mutableLongStateOf(0L) }
    var gain by remember { mutableFloatStateOf(0.5f) }
    var cutoff by remember { mutableFloatStateOf(2_000f) }

    DisposableEffect(Unit) {
        onDispose {
            if (handle != 0L) AudioFx.nativeStop(handle)
        }
    }

    Column(modifier = Modifier.padding(24.dp)) {
        Button(onClick = {
            handle = if (handle == 0L) {
                AudioFx.nativeStart()
            } else {
                AudioFx.nativeStop(handle)
                0L
            }
        }) {
            Text(if (handle == 0L) "Start" else "Stop")
        }

        Text("Gain")
        Slider(
            value = gain,
            onValueChange = {
                gain = it
                if (handle != 0L) AudioFx.nativeSetGain(handle, it)
            },
        )

        Text("Cutoff: ${cutoff.toInt()} Hz")
        Slider(
            value = cutoff,
            valueRange = 40f..8_000f,
            onValueChange = {
                cutoff = it
                if (handle != 0L) AudioFx.nativeSetCutoff(handle, it)
            },
        )
    }
}

Drag the cutoff slider while the saw plays and the filter sweeps cleanly: every slider event is one atomic store, picked up on the callback’s next pass. The DisposableEffect closes the stream when the screen leaves composition, so a rotation does not leak a running engine, the failure mode Part 7 covers. If the tone should survive rotation, hoist the handle into a ViewModel and call nativeStop from onCleared instead.

I left latency numbers out on purpose. They depend on device, sharing mode, and whether the exclusive request was granted; the measured expectations in my C++ audio guide carry over, because both paths sit on the same AAudio streams. When the companion repo ships this module, real measurements land here.

Where Oboe still fits

Oboe is Google’s open source C++ library above AAudio and OpenSL ES: it uses AAudio on API 27 and later and falls back to OpenSL ES below that (Oboe, Android Developers). Two situations justify it over raw AAudio from Rust: a minSdk below 26, where AAudio does not exist, and its workaround catalog, years of fixes for device-specific audio bugs that raw AAudio callers rediscover one report at a time.

From Rust, the oboe crate, at 0.6 as of mid-2026, wraps the C++ library in a safe interface and is the Android backend of cpal, Rust’s standard cross-platform audio library. The trade is your build: it compiles Oboe’s C++ sources, so the C++ toolchain returns as a build dependency. My default is the pure ndk path from this post, with the oboe crate when an older minSdk or a specific device bug forces it.

I say that having shipped the other answer. Klarinet, my Kotlin Multiplatform audio SDK, runs its effects chain in a C++ core on Oboe, and that core does its job. But the bugs that cost me nights were exactly the ones the Rust compiler catches: state shared with the callback that was less thread-safe than code review believed. If I started that engine today, the DSP core would be Rust. It shipped as Klarinet 0.6.0.

Frequently Asked Questions

Why can’t the audio callback call back into Kotlin?

A JNI call can allocate, take locks inside the JVM, and block, all forbidden on the audio thread. Move data with atomics or a lock-free ring buffer and let the Kotlin side observe from a normal thread.

Part 11 turns to a quieter performance problem: multi-megabyte JSON and CSV payloads that stutter the main thread when parsed in Kotlin. Part 11, Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust, puts the chunky-call principle to work. The full series map lives at the hub.

Sources

Rust + NDK on Android, Part 10 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Threading and Async: Tokio, Kotlin Coroutines, and Calling Back Into Kotlin from Rust. Next: Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust.

Puedes cumplir un plazo de audio en tiempo real en Android desde Rust puro, sin C++ en la compilación. AAudio, la API de audio de baja latencia de la plataforma desde Android 8.0, es una API C sencilla (Android Developers, guía de AAudio), y el crate ndk la envuelve en Rust seguro, callback incluido. En esta parte abrirás un flujo de salida de baja latencia desde una cdylib de Rust y renderizarás un sintetizador a través de una cadena de ganancia y filtro que no asigna memoria. Un deslizador de Kotlin controla la ganancia y la frecuencia de corte del filtro mientras suena, y nada en ninguno de los dos lados toma un cerrojo.

Esto es la contrapartida en Rust de mi guía de audio en C++ moderno. El compilador de Rust impone más de esas reglas del hilo de audio que el de C++. Da por sentada la cadena de herramientas de la parte 1, el patrón de manejador de la parte 7 y las reglas de hilos de la parte 9.

Puntos clave

  • Una cdylib de Rust puede controlar AAudio directamente a través del módulo audio del crate ndk. minSdk tiene que ser 26 o superior, porque el crate enlaza libaaudio.so.
  • El contrato del callback es el que Google documenta para Oboe: nada de asignaciones, nada de cerrojos, nada de E/S, lo que descarta también JNI. Rust comprueba las reglas de compartición en tiempo de compilación; las asignaciones siguen siendo disciplina tuya.
  • Los parámetros cruzan al hilo de audio como patrones de bits f32 en un AtomicU32 con ordenación Relaxed. Sin mutex, sin lecturas a medias, sin inversión de prioridad.
  • Oboe sigue teniendo su sitio por debajo de minSdk 26, o cuando quieres sus apaños por dispositivo. El crate oboe envuelve la biblioteca de C++ para Rust.

Por qué Rust encaja con el audio de baja latencia en Android

Un callback de audio es el plazo más duro que suele encontrar el código de una aplicación. El flujo te llama cada pocos milisegundos, rellenas un búfer y, si llegas tarde, quien escucha oye un chasquido. Las reglas de Google para ese callback son explícitas: nada de asignación de memoria, nada de E/S de archivos o de red, nada de mutex ni de otras primitivas de sincronización, nada de dormir, nada de cerrar el flujo desde dentro (guía completa de Oboe de Google). JNI incumple varias a la vez, y por eso el hilo de audio nunca toca Kotlin, una regla que fijó la parte 9.

En C++ esa lista vive en la revisión de código. En Rust, una parte útil pasa al sistema de tipos. El callback de datos del crate ndk es una clausura FnMut metida en un Box que tiene que ser Send, así que el estado que muevas dentro tiene que demostrar que puede cruzar hilos, y todo lo que se comparta con el hilo de la interfaz tiene que ser Sync, lo que te empuja directo a los atómicos y a las colas sin bloqueos. El manejador del flujo es !Send, así que el compilador se niega a dejarte guardarlo en un global. Y la carrera de datos que corrompe un búfer a la semana en un modelo concreto de dispositivo, el fallo que me empujó de C++ hacia Rust, no se puede escribir en Rust seguro.

Y la otra mitad, dicha clara. Vec::push en el callback compila sin aviso, y Mutex::lock también. Rust no tiene recolector de basura, lo que elimina esa clase de fallos de la JVM, pero el asignador sigue siendo no determinista y sigue prohibido. El compilador acorta la lista que impones por disciplina; no la vacía.

Abrir un flujo de AAudio desde Rust

El crate necesita jni para la frontera y ndk con la característica audio para AAudio. Este es rust/audiofx/Cargo.toml entero:

[package]
name = "audiofx"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
jni = "0.21"
ndk = { version = "0.9", features = ["audio"] }

La característica audio enlaza libaaudio.so, que existe en la API 26 y posteriores, así que pon minSdk = 26. Por debajo de eso, sáltate hasta la sección de Oboe.

Todo lo demás vive en rust/audiofx/src/lib.rs, empezando por los imports, las constantes y la puesta en marcha del flujo:

use std::f32::consts::PI;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

use jni::objects::JClass;
use jni::sys::{jfloat, jlong};
use jni::JNIEnv;
use ndk::audio::{
    AudioCallbackResult, AudioDirection, AudioFormat, AudioPerformanceMode,
    AudioSharingMode, AudioStream, AudioStreamBuilder,
};

const SAMPLE_RATE: i32 = 48_000;
const CHANNELS: i32 = 2;
const FREQUENCY_HZ: f32 = 220.0;

/// Owns the stream and the parameters shared with the audio thread.
pub struct Engine {
    stream: AudioStream,
    params: Arc<SharedParams>,
}

fn start_engine() -> ndk::audio::Result<Engine> {
    let params = Arc::new(SharedParams::new());
    let mut dsp = Dsp {
        phase: 0.0,
        lp_state: 0.0,
        params: Arc::clone(&params),
    };

    let stream = AudioStreamBuilder::new()?
        .direction(AudioDirection::Output)
        .format(AudioFormat::PCM_Float)
        .channel_count(CHANNELS)
        .sample_rate(SAMPLE_RATE)
        .performance_mode(AudioPerformanceMode::LowLatency)
        .sharing_mode(AudioSharingMode::Exclusive)
        .data_callback(Box::new(move |_stream, data, num_frames| {
            // SAFETY: AAudio hands us num_frames frames in the format
            // and channel count we requested: interleaved f32 samples.
            let samples = unsafe {
                std::slice::from_raw_parts_mut(
                    data.cast::<f32>(),
                    (num_frames * CHANNELS) as usize,
                )
            };
            dsp.render(samples);
            AudioCallbackResult::Continue
        }))
        .open_stream()?;

    stream.request_start()?;
    Ok(Engine { stream, params })
}

Tres ajustes hacen el trabajo de la latencia. LowLatency pide búferes más pequeños y la ruta de datos optimizada, Exclusive pide acceso en exclusiva al dispositivo y el callback deja que la plataforma marque el tiempo. La guía de AAudio ata la latencia más baja al modo LowLatency con un callback, y dice que los flujos exclusivos es probable que tengan menos latencia, pero también más probabilidad de desconectarse (Android Developers, guía de AAudio).

Dos notas de producción. El builder es una petición, no una promesa: el dispositivo puede darte un flujo compartido o una tasa distinta, así que el código real lee stream.sample_rate() después de abrir, en lugar de fiarse de mi constante SAMPLE_RATE, y recalcula lo que dependa de ella. Y los flujos se mueren en el uso normal, se desconectan los auriculares, así que registra un error_callback y reconstruye cuando se dispare.

Una cadena DSP que no asigna nunca

El sintetizador es pequeño a propósito: un diente de sierra ingenuo, un paso bajo de un polo y una etapa de ganancia. Un diente de sierra y no una senoide, porque los armónicos te dejan oír cómo se mueve el filtro. La struct Dsp y su función de render, también en rust/audiofx/src/lib.rs:

/// All DSP state, allocated once before the stream starts and
/// moved into the audio callback.
struct Dsp {
    phase: f32,
    lp_state: f32,
    params: Arc<SharedParams>,
}

impl Dsp {
    fn render(&mut self, samples: &mut [f32]) {
        let gain = SharedParams::load(&self.params.gain);
        let cutoff = SharedParams::load(&self.params.cutoff_hz);

        // Plain arithmetic only: no allocation, no locks, no syscalls.
        let dt = 1.0 / SAMPLE_RATE as f32;
        let rc = 1.0 / (2.0 * PI * cutoff);
        let alpha = dt / (rc + dt);
        let step = FREQUENCY_HZ / SAMPLE_RATE as f32;

        for frame in samples.chunks_exact_mut(CHANNELS as usize) {
            // Naive sawtooth in [-1.0, 1.0]. It aliases; fine for a demo.
            let raw = 2.0 * self.phase - 1.0;
            self.phase += step;
            if self.phase >= 1.0 {
                self.phase -= 1.0;
            }
            // One-pole low-pass, then gain.
            self.lp_state += alpha * (raw - self.lp_state);
            let sample = self.lp_state * gain;
            for channel_sample in frame.iter_mut() {
                *channel_sample = sample;
            }
        }
    }
}

Todo lo que el callback necesita se asignó antes de que arrancara el flujo: la fase del oscilador, el estado del filtro y el Arc a los parámetros compartidos viven dentro de Dsp, movido a la clausura, movido al flujo. Del primer callback al último, render no toca nada más que sus propios campos y el búfer que le entregó AAudio, con chunks_exact_mut recorriendo los frames estéreo intercalados.

Como el callback tiene que ser Send, el compilador comprueba cada campo de Dsp para ver si puede cruzar hilos con seguridad. Cambia el Arc por un Rc, o cuela un JNIEnv, y el crate deja de compilar con un error que nombra el campo. En C++ ese error se publica y luego falla un martes.

Pasar parámetros sin cerrojos

Quien usa la aplicación arrastra un deslizador en el hilo principal; el hilo de audio necesita el valor unos milisegundos después. Un Mutex es la respuesta obvia y la prohibida: si el hilo de audio espera un cerrojo que tiene un hilo de menor prioridad, el plazo se ha ido. El artículo de C++ usaba std::atomic<float>. Rust no tiene un AtomicF32 estable, así que guardamos los bits del float en un AtomicU32. El lado de la compartición de rust/audiofx/src/lib.rs:

/// Parameters shared between the UI thread and the audio thread.
/// Each f32 is stored as its raw bits in an AtomicU32, so the
/// audio thread reads them without ever taking a lock.
pub struct SharedParams {
    gain: AtomicU32,
    cutoff_hz: AtomicU32,
}

impl SharedParams {
    fn new() -> Self {
        Self {
            gain: AtomicU32::new(0.5f32.to_bits()),
            cutoff_hz: AtomicU32::new(2_000.0f32.to_bits()),
        }
    }

    fn store(cell: &AtomicU32, value: f32) {
        cell.store(value.to_bits(), Ordering::Relaxed);
    }

    fn load(cell: &AtomicU32) -> f32 {
        f32::from_bits(cell.load(Ordering::Relaxed))
    }
}

Cada parámetro tiene un escritor, el hilo de la interfaz, y un lector, el callback. El lector tolera un valor con un búfer de retraso, y ninguna otra operación de memoria depende del orden de estos stores. Lo que Relaxed sigue garantizando es que cada lectura es un valor completo de 32 bits: un float partido es imposible. Cualquier orden más fuerte no compra nada.

Los valores sueltos solo te llevan hasta cierto punto. Los eventos, note on y note off, necesitan una cola sin bloqueos en los dos extremos: el búfer circular SPSC que el artículo de C++ construye a mano alrededor de dos índices atómicos. El crate rtrb es un búfer circular SPSC seguro para tiempo real que no asigna después de construirse; este sintetizador no necesita uno, así que se queda como el siguiente paso, ya nombrado.

Conectar el deslizador de Kotlin

La frontera usa el patrón de manejador con puntero crudo de la parte 7: nativeStart mete el motor en un Box y entrega a Kotlin la dirección como un Long, los setters la toman prestada y nativeStop la recupera y la suelta, cerrando el flujo. Hay una razón de Rust para hacerlo: AudioStream es !Send, así que el compilador rechaza aparcar el motor en un static. El manejador mantiene la propiedad en el hilo principal; el hilo de audio solo ve los atómicos de dentro del Arc. Estas funciones cierran rust/audiofx/src/lib.rs:

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeStart(
    _env: JNIEnv,
    _class: JClass,
) -> jlong {
    match start_engine() {
        Ok(engine) => Box::into_raw(Box::new(engine)) as jlong,
        Err(_) => 0,
    }
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeSetGain(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
    gain: jfloat,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { &*(handle as *const Engine) };
    SharedParams::store(&engine.params.gain, gain.clamp(0.0, 1.0));
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeSetCutoff(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
    cutoff_hz: jfloat,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { &*(handle as *const Engine) };
    SharedParams::store(&engine.params.cutoff_hz, cutoff_hz.clamp(40.0, 8_000.0));
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeStop(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { Box::from_raw(handle as *mut Engine) };
    let _ = engine.stream.request_stop();
    // Dropping the engine closes the stream.
}

El puente de Kotlin son cuatro funciones externas en app/src/main/java/dev/davthecoder/rustseries/AudioFx.kt:

package dev.davthecoder.rustseries

object AudioFx {
    init {
        System.loadLibrary("audiofx")
    }

    external fun nativeStart(): Long
    external fun nativeStop(handle: Long)
    external fun nativeSetGain(handle: Long, gain: Float)
    external fun nativeSetCutoff(handle: Long, cutoffHz: Float)
}

Toda la interfaz es una pantalla de Compose en app/src/main/java/dev/davthecoder/rustseries/SynthScreen.kt:

package dev.davthecoder.rustseries

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun SynthScreen() {
    var handle by remember { mutableLongStateOf(0L) }
    var gain by remember { mutableFloatStateOf(0.5f) }
    var cutoff by remember { mutableFloatStateOf(2_000f) }

    DisposableEffect(Unit) {
        onDispose {
            if (handle != 0L) AudioFx.nativeStop(handle)
        }
    }

    Column(modifier = Modifier.padding(24.dp)) {
        Button(onClick = {
            handle = if (handle == 0L) {
                AudioFx.nativeStart()
            } else {
                AudioFx.nativeStop(handle)
                0L
            }
        }) {
            Text(if (handle == 0L) "Start" else "Stop")
        }

        Text("Gain")
        Slider(
            value = gain,
            onValueChange = {
                gain = it
                if (handle != 0L) AudioFx.nativeSetGain(handle, it)
            },
        )

        Text("Cutoff: ${cutoff.toInt()} Hz")
        Slider(
            value = cutoff,
            valueRange = 40f..8_000f,
            onValueChange = {
                cutoff = it
                if (handle != 0L) AudioFx.nativeSetCutoff(handle, it)
            },
        )
    }
}

Arrastra el deslizador de corte mientras suena el diente de sierra y el filtro barre limpio: cada evento del deslizador es un store atómico, que el callback recoge en la pasada siguiente. El DisposableEffect cierra el flujo cuando la pantalla sale de la composición, así que una rotación no filtra un motor en marcha, el modo de fallo que cubre la parte 7. Si el tono tiene que sobrevivir a la rotación, sube el manejador a un ViewModel y llama a nativeStop desde onCleared.

Dejé fuera los números de latencia a propósito. Dependen del dispositivo, del modo de compartición y de si se concedió la petición exclusiva; las expectativas medidas de mi guía de audio en C++ se trasladan, porque las dos rutas se sientan sobre los mismos flujos de AAudio. Cuando el repositorio complementario publique este módulo, las medidas reales aterrizan aquí.

Dónde sigue encajando Oboe

Oboe es la biblioteca de C++ de código abierto de Google por encima de AAudio y OpenSL ES: usa AAudio en la API 27 y posteriores, y recurre a OpenSL ES por debajo (Oboe, Android Developers). Dos situaciones lo justifican frente a AAudio en crudo desde Rust: un minSdk por debajo de 26, donde AAudio no existe, y su catálogo de apaños, años de correcciones para fallos de audio específicos de cada dispositivo que quien llama a AAudio en crudo redescubre informe a informe.

Desde Rust, el crate oboe, en la 0.6 a mediados de 2026, envuelve la biblioteca de C++ en una interfaz segura y es el backend de Android de cpal, la biblioteca de audio multiplataforma habitual de Rust. Lo que cedes es la compilación: compila las fuentes C++ de Oboe, así que la cadena de herramientas de C++ vuelve como dependencia de compilación. Mi opción por defecto es la vía pura de ndk de este artículo, con el crate oboe cuando un minSdk más antiguo o un fallo concreto de un dispositivo lo obligan.

Lo digo habiendo publicado la otra respuesta. Klarinet, mi SDK de audio para Kotlin Multiplatform, ejecuta su cadena de efectos en un núcleo de C++ sobre Oboe, y ese núcleo hace su trabajo. Pero los fallos que me costaron noches eran exactamente los que pilla el compilador de Rust: estado compartido con el callback que era menos seguro entre hilos de lo que la revisión de código creía. Si empezara ese motor hoy, el núcleo DSP sería Rust. Salió como Klarinet 0.6.0.

Preguntas frecuentes

¿Por qué el callback de audio no puede volver a llamar a Kotlin?

Una llamada JNI puede asignar, tomar cerrojos dentro de la JVM y bloquearse, todo prohibido en el hilo de audio. Mueve los datos con atómicos o con un búfer circular sin bloqueos, y deja que el lado de Kotlin observe desde un hilo normal.

La parte 11 pasa a un problema de rendimiento más callado: cargas JSON y CSV de varios megabytes que hacen tartamudear al hilo principal cuando se parsean en Kotlin. La parte 11, Análisis pesado con Serde: descargar el procesado de JSON y CSV a Rust, pone en práctica el principio de la llamada gruesa. El mapa completo de la serie está en el hub.

Fuentes

Rust + NDK on Android, Part 10 of 15.This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Threading and Async: Tokio, Kotlin Coroutines, and Calling Back Into Kotlin from Rust. Next: Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust.

คุณถือเดดไลน์เสียงเรียลไทม์บน Android จาก Rust ล้วนได้ โดยไม่มี C++ ในบิลด์ AAudio ซึ่งเป็น API เสียงความหน่วงต่ำของแพลตฟอร์มตั้งแต่ Android 8.0 เป็น API ภาษา C ธรรมดา (Android Developers, คู่มือ AAudio) และ crate ndk ห่อมันใน Rust ที่ปลอดภัย รวม callback ในตอนนี้คุณจะเปิดสตรีมเอาต์พุตความหน่วงต่ำจาก cdylib ของ Rust และเรนเดอร์ซินธ์ผ่านโซ่เกนและฟิลเตอร์ที่ไม่จัดสรรหน่วยความจำ สไลเดอร์ Kotlin ขับเกนและความถี่ตัดของฟิลเตอร์ขณะที่เสียงเล่น และไม่มีฝั่งไหนถือล็อก

นี่คือคู่ขนานฝั่ง Rust ของคู่มือเสียง C++ สมัยใหม่ของผม คอมไพเลอร์ของ Rust บังคับกฎเธรดเสียงเหล่านั้นได้มากกว่า C++ บทความนี้ถือว่ามีทูลเชนจากตอนที่ 1 แพตเทิร์นแฮนเดิลจากตอนที่ 7 และกฎเธรดจากตอนที่ 9

ประเด็นหลัก

  • cdylib ของ Rust ขับ AAudio ได้โดยตรงผ่านโมดูล audio ของ crate ndk minSdk ต้องเป็น 26 ขึ้นไป เพราะ crate ลิงก์ libaaudio.so
  • สัญญาของ callback คือสัญญาที่ Google เขียนไว้สำหรับ Oboe: ไม่จัดสรรหน่วยความจำ ไม่ใช้ล็อก ไม่ทำ I/O ซึ่งตัด JNI ออกด้วย Rust ตรวจกฎการแชร์ตอนคอมไพล์ การไม่จัดสรรหน่วยความจำยังเป็นวินัยของคุณ
  • พารามิเตอร์ข้ามไปเธรดเสียงเป็นแพตเทิร์นบิตของ f32 ใน AtomicU32 ด้วยลำดับ Relaxed ไม่มี mutex ไม่มีการอ่านที่ขาด ไม่มี priority inversion
  • Oboe ยังมีที่ของมันเมื่อต่ำกว่า minSdk 26 หรือเมื่อต้องการชุดแก้เฉพาะอุปกรณ์ crate oboe ห่อไลบรารี C++ สำหรับ Rust

ทำไม Rust เข้ากับเสียงความหน่วงต่ำบน Android

callback เสียงคือเดดไลน์ที่หนักที่สุดที่โค้ดแอปส่วนใหญ่เคยเจอ สตรีมเรียกคุณทุกไม่กี่มิลลิวินาที คุณเติมบัฟเฟอร์ และถ้าสายผู้ใช้ได้ยินเสียงคลิก กฎของ Google สำหรับ callback นั้นชัดเจน: ไม่จัดสรรหน่วยความจำ ไม่ทำ I/O ไฟล์หรือเครือข่าย ไม่ใช้ mutex หรือ primitive การซิงโครไนซ์อื่น ไม่หลับ ไม่ปิดสตรีมจากข้างใน (คู่มือเต็ม Oboe ของ Google) JNI พลาดหลายข้อพร้อมกัน ซึ่งเป็นเหตุให้เธรดเสียงไม่แตะ Kotlin กฎที่ตอนที่ 9 วางไว้

ใน C++ รายการนั้นอยู่ในรีวิวโค้ด ใน Rust ส่วนที่มีประโยชน์ย้ายเข้าสู่ระบบชนิด callback ข้อมูลของ crate ndk เป็น closure FnMut ที่ถูก box และต้องเป็น Send ดังนั้นสถานะที่ย้ายเข้าไปต้องพิสูจน์ว่าข้ามเธรดได้ และสิ่งที่แชร์กับเธรด UI ต้องเป็น Sync ซึ่งผลักคุณตรงไปที่อะตอมิกและคิวแบบไม่มีล็อก แฮนเดิลสตรีมเป็น !Send ดังนั้นคอมไพเลอร์ไม่ยอมให้คุณเก็บมันใน global และ data race ที่ทำให้บัฟเฟอร์เสียหนึ่งตัวต่อสัปดาห์บนรุ่นอุปกรณ์หนึ่งตัว บั๊กที่ผลักผมจาก C++ ไปหา Rust เขียนใน Rust ที่ปลอดภัยไม่ได้

พูดตรงเรื่องอีกครึ่ง Vec::push ใน callback คอมไพล์ได้โดยไม่มีคำเตือน และ Mutex::lock ก็เช่นกัน Rust ไม่มีตัวเก็บขยะ ซึ่งตัดกลิตช์ประเภทของ JVM ออก แต่ตัวจัดสรรยังไม่กำหนดเวลาได้ และยังห้ามอยู่ คอมไพเลอร์ย่อรายการที่คุณต้องบังคับด้วยวินัย มันไม่ได้ทำให้รายการนั้นว่าง

เปิดสตรีม AAudio จาก Rust

crate ต้องการ jni สำหรับเขตแดน และ ndk พร้อมฟีเจอร์ audio สำหรับ AAudio นี่คือ rust/audiofx/Cargo.toml ทั้งไฟล์:

[package]
name = "audiofx"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
jni = "0.21"
ndk = { version = "0.9", features = ["audio"] }

ฟีเจอร์ audio ลิงก์ libaaudio.so ซึ่งมีบน API 26 ขึ้นไป ดังนั้นตั้ง minSdk = 26 ต่ำกว่านั้น ข้ามไปส่วน Oboe

ที่เหลืออยู่ใน rust/audiofx/src/lib.rs เริ่มจาก import ค่าคงที่ และการตั้งสตรีม:

use std::f32::consts::PI;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

use jni::objects::JClass;
use jni::sys::{jfloat, jlong};
use jni::JNIEnv;
use ndk::audio::{
    AudioCallbackResult, AudioDirection, AudioFormat, AudioPerformanceMode,
    AudioSharingMode, AudioStream, AudioStreamBuilder,
};

const SAMPLE_RATE: i32 = 48_000;
const CHANNELS: i32 = 2;
const FREQUENCY_HZ: f32 = 220.0;

/// Owns the stream and the parameters shared with the audio thread.
pub struct Engine {
    stream: AudioStream,
    params: Arc<SharedParams>,
}

fn start_engine() -> ndk::audio::Result<Engine> {
    let params = Arc::new(SharedParams::new());
    let mut dsp = Dsp {
        phase: 0.0,
        lp_state: 0.0,
        params: Arc::clone(&params),
    };

    let stream = AudioStreamBuilder::new()?
        .direction(AudioDirection::Output)
        .format(AudioFormat::PCM_Float)
        .channel_count(CHANNELS)
        .sample_rate(SAMPLE_RATE)
        .performance_mode(AudioPerformanceMode::LowLatency)
        .sharing_mode(AudioSharingMode::Exclusive)
        .data_callback(Box::new(move |_stream, data, num_frames| {
            // SAFETY: AAudio hands us num_frames frames in the format
            // and channel count we requested: interleaved f32 samples.
            let samples = unsafe {
                std::slice::from_raw_parts_mut(
                    data.cast::<f32>(),
                    (num_frames * CHANNELS) as usize,
                )
            };
            dsp.render(samples);
            AudioCallbackResult::Continue
        }))
        .open_stream()?;

    stream.request_start()?;
    Ok(Engine { stream, params })
}

สามการตั้งค่าทำงานเรื่องความหน่วง LowLatency ขอบัฟเฟอร์เล็กลงและเส้นทางข้อมูลที่ปรับแล้ว Exclusive ขอสิทธิ์ใช้เครื่องคนเดียว และ callback ให้แพลตฟอร์มขับจังหวะ คู่มือ AAudio ผูกความหน่วงต่ำสุดกับโหมด LowLatency พร้อม callback และบอกว่าสตรีมแบบเอกสิทธิ์มีแนวโน้มความหน่วงต่ำกว่า แต่ก็มีแนวโน้มถูกตัดการเชื่อมต่อมากกว่า (Android Developers, คู่มือ AAudio)

โน้ตโปรดักชันสองข้อ ตัวสร้างคือคำขอ ไม่ใช่คำสัญญา: อุปกรณ์อาจส่งสตรีมแบบแชร์หรืออัตราที่ต่างกัน ดังนั้นโค้ดจริงอ่าน stream.sample_rate() หลังเปิด แทนที่จะเชื่อค่าคงที่ SAMPLE_RATE ของผม แล้วคำนวณใหม่ทุกอย่างที่ขึ้นกับมัน และสตรีมตายในการใช้ปกติ หูฟังถูกถอด ดังนั้นลงทะเบียน error_callback แล้วสร้างใหม่เมื่อมันยิง

โซ่ DSP ที่ไม่จัดสรรหน่วยความจำ

ซินธ์ตั้งใจให้เล็ก: ฟันเลื่อยแบบตรงไปเข้าโลว์พาสหนึ่งขั้ว แล้วเข้าสเตจเกน ใช้ฟันเลื่อยไม่ใช่ไซน์เพราะฮาร์มอนิกให้ได้ยินฟิลเตอร์ขยับ สตรักต์ Dsp และฟังก์ชันเรนเดอร์ อยู่ใน rust/audiofx/src/lib.rs เช่นกัน:

/// All DSP state, allocated once before the stream starts and
/// moved into the audio callback.
struct Dsp {
    phase: f32,
    lp_state: f32,
    params: Arc<SharedParams>,
}

impl Dsp {
    fn render(&mut self, samples: &mut [f32]) {
        let gain = SharedParams::load(&self.params.gain);
        let cutoff = SharedParams::load(&self.params.cutoff_hz);

        // Plain arithmetic only: no allocation, no locks, no syscalls.
        let dt = 1.0 / SAMPLE_RATE as f32;
        let rc = 1.0 / (2.0 * PI * cutoff);
        let alpha = dt / (rc + dt);
        let step = FREQUENCY_HZ / SAMPLE_RATE as f32;

        for frame in samples.chunks_exact_mut(CHANNELS as usize) {
            // Naive sawtooth in [-1.0, 1.0]. It aliases; fine for a demo.
            let raw = 2.0 * self.phase - 1.0;
            self.phase += step;
            if self.phase >= 1.0 {
                self.phase -= 1.0;
            }
            // One-pole low-pass, then gain.
            self.lp_state += alpha * (raw - self.lp_state);
            let sample = self.lp_state * gain;
            for channel_sample in frame.iter_mut() {
                *channel_sample = sample;
            }
        }
    }
}

ทุกอย่างที่ callback ต้องการถูกจัดสรรก่อนสตรีมเริ่ม: เฟสออสซิลเลเตอร์ สถานะฟิลเตอร์ และ Arc ไปพารามิเตอร์ร่วม อยู่ใน Dsp ถูกย้ายเข้า closure แล้วย้ายเข้าสตรีม จาก callback แรกถึงสุดท้าย render ไม่แตะอะไรนอกจากฟิลด์ของตัวเองและบัฟเฟอร์ที่ AAudio ส่งมา โดย chunks_exact_mut เดินเฟรมสเตอริโอแบบอินเตอร์ลีฟ

เพราะ callback ต้องเป็น Send คอมไพเลอร์ตรวจทุกฟิลด์ของ Dsp เรื่องความปลอดภัยในการข้ามเธรด สลับ Arc เป็น Rc หรือแอบใส่ JNIEnv แล้ว crate จะหยุดคอมไพล์ด้วยข้อผิดพลาดที่ชี้ชื่อฟิลด์ ใน C++ ความผิดนั้นถูกส่งออก แล้วกลิตช์ในวันอังคาร

ส่งพารามิเตอร์โดยไม่มีล็อก

ผู้ใช้ลากสไลเดอร์บนเธรดหลัก เธรดเสียงต้องการค่าอีกไม่กี่มิลลิวินาทีถัดไป Mutex คือคำตอบที่เห็นชัดและเป็นคำตอบที่ห้าม: ถ้าเธรดเสียงรอล็อกที่เธรดความสำคัญต่ำกว่าถืออยู่ เดดไลน์หาย โพสต์ C++ ใช้ std::atomic<float> Rust ไม่มี AtomicF32 ที่เสถียร ดังนั้นเราเก็บบิตของ float ใน AtomicU32 ฝั่งการแชร์ของ rust/audiofx/src/lib.rs:

/// Parameters shared between the UI thread and the audio thread.
/// Each f32 is stored as its raw bits in an AtomicU32, so the
/// audio thread reads them without ever taking a lock.
pub struct SharedParams {
    gain: AtomicU32,
    cutoff_hz: AtomicU32,
}

impl SharedParams {
    fn new() -> Self {
        Self {
            gain: AtomicU32::new(0.5f32.to_bits()),
            cutoff_hz: AtomicU32::new(2_000.0f32.to_bits()),
        }
    }

    fn store(cell: &AtomicU32, value: f32) {
        cell.store(value.to_bits(), Ordering::Relaxed);
    }

    fn load(cell: &AtomicU32) -> f32 {
        f32::from_bits(cell.load(Ordering::Relaxed))
    }
}

แต่ละพารามิเตอร์มีผู้เขียนหนึ่งคน คือเธรด UI และผู้อ่านหนึ่งคน คือ callback ผู้อ่านยอมรับค่าที่เก่าไปหนึ่งบัฟเฟอร์ และการทำงานหน่วยความจำอื่นไม่ขึ้นกับลำดับของ store เหล่านี้ สิ่งที่ Relaxed ยังรับประกันคือทุกการอ่านเป็นค่า 32 บิตที่ครบ: float ที่ขาดเป็นไปไม่ได้ ลำดับที่แข็งกว่าไม่ได้ซื้ออะไรเพิ่ม

ค่าเดี่ยวพาไปได้แค่ระดับหนึ่ง เหตุการณ์ note on และ note off ต้องการคิวที่ไม่มีล็อกทั้งสองปลาย: ริงบัฟเฟอร์ SPSC ที่โพสต์ C++ สร้างมือรอบดัชนีอะตอมิกสองตัว crate rtrb เป็นริงบัฟเฟอร์ SPSC ที่ปลอดภัยสำหรับเรียลไทม์ และไม่จัดสรรหลังสร้าง ซินธ์นี้ไม่ต้องการตัวนั้น ดังนั้นมันยังเป็นขั้นถัดไปที่มีชื่อแล้ว

ต่อสไลเดอร์ Kotlin

เขตแดนใช้แพตเทิร์นแฮนเดิลพอยน์เตอร์ดิบจากตอนที่ 7: nativeStart box เอนจินแล้วส่งที่อยู่ให้ Kotlin เป็น Long ตัวตั้งค่ายืมมัน และ nativeStop เอาคืนแล้ว drop ปิดสตรีม มีเหตุผลฝั่ง Rust: AudioStream เป็น !Send ดังนั้นคอมไพเลอร์ปฏิเสธการจอดเอนจินใน static แฮนเดิลเก็บความเป็นเจ้าของบนเธรดหลัก เธรดเสียงเห็นแค่อะตอมิกใน Arc ฟังก์ชันเหล่านี้ปิด rust/audiofx/src/lib.rs:

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeStart(
    _env: JNIEnv,
    _class: JClass,
) -> jlong {
    match start_engine() {
        Ok(engine) => Box::into_raw(Box::new(engine)) as jlong,
        Err(_) => 0,
    }
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeSetGain(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
    gain: jfloat,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { &*(handle as *const Engine) };
    SharedParams::store(&engine.params.gain, gain.clamp(0.0, 1.0));
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeSetCutoff(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
    cutoff_hz: jfloat,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { &*(handle as *const Engine) };
    SharedParams::store(&engine.params.cutoff_hz, cutoff_hz.clamp(40.0, 8_000.0));
}

#[no_mangle]
pub extern "system" fn Java_dev_davthecoder_rustseries_AudioFx_nativeStop(
    _env: JNIEnv,
    _class: JClass,
    handle: jlong,
) {
    if handle == 0 {
        return;
    }
    let engine = unsafe { Box::from_raw(handle as *mut Engine) };
    let _ = engine.stream.request_stop();
    // Dropping the engine closes the stream.
}

สะพาน Kotlin เป็น external สี่ตัวใน app/src/main/java/dev/davthecoder/rustseries/AudioFx.kt:

package dev.davthecoder.rustseries

object AudioFx {
    init {
        System.loadLibrary("audiofx")
    }

    external fun nativeStart(): Long
    external fun nativeStop(handle: Long)
    external fun nativeSetGain(handle: Long, gain: Float)
    external fun nativeSetCutoff(handle: Long, cutoffHz: Float)
}

UI ทั้งก้อนคือหน้าจอ Compose เดียวใน app/src/main/java/dev/davthecoder/rustseries/SynthScreen.kt:

package dev.davthecoder.rustseries

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun SynthScreen() {
    var handle by remember { mutableLongStateOf(0L) }
    var gain by remember { mutableFloatStateOf(0.5f) }
    var cutoff by remember { mutableFloatStateOf(2_000f) }

    DisposableEffect(Unit) {
        onDispose {
            if (handle != 0L) AudioFx.nativeStop(handle)
        }
    }

    Column(modifier = Modifier.padding(24.dp)) {
        Button(onClick = {
            handle = if (handle == 0L) {
                AudioFx.nativeStart()
            } else {
                AudioFx.nativeStop(handle)
                0L
            }
        }) {
            Text(if (handle == 0L) "Start" else "Stop")
        }

        Text("Gain")
        Slider(
            value = gain,
            onValueChange = {
                gain = it
                if (handle != 0L) AudioFx.nativeSetGain(handle, it)
            },
        )

        Text("Cutoff: ${cutoff.toInt()} Hz")
        Slider(
            value = cutoff,
            valueRange = 40f..8_000f,
            onValueChange = {
                cutoff = it
                if (handle != 0L) AudioFx.nativeSetCutoff(handle, it)
            },
        )
    }
}

ลากสไลเดอร์ความถี่ตัดขณะที่ฟันเลื่อยเล่น แล้วฟิลเตอร์กวาดสะอาด: ทุกเหตุการณ์สไลเดอร์คือ store อะตอมิกหนึ่งครั้ง ที่ callback หยิบในรอบถัดไป DisposableEffect ปิดสตรีมเมื่อหน้าจอออกจาก composition ดังนั้นการหมุนจอไม่รั่วเอนจินที่ยังวิ่ง โหมดความล้มเหลวที่ตอนที่ 7 ครอบคลุม ถ้าโทนต้องอยู่รอดการหมุนจอ ยกแฮนเดิลเข้า ViewModel แล้วเรียก nativeStop จาก onCleared แทน

ผมจงใจไม่ใส่ตัวเลขความหน่วง มันขึ้นกับอุปกรณ์ โหมดการแชร์ และว่าคำขอเอกสิทธิ์ได้รับหรือไม่ ความคาดหมายที่วัดในคู่มือเสียง C++ ของผม ย้ายมาได้ เพราะทั้งสองเส้นทางนั่งบนสตรีม AAudio เดียวกัน เมื่อรีโปคู่ขนานส่งโมดูลนี้ การวัดจริงจะลงที่นี่

Oboe ยังเข้าตรงไหน

Oboe คือไลบรารี C++ โอเพนซอร์สของ Google ที่อยู่เหนือ AAudio และ OpenSL ES: ใช้ AAudio บน API 27 ขึ้นไป และถอยไป OpenSL ES เมื่อต่ำกว่านั้น (Oboe, Android Developers) สองสถานการณ์ทำให้มันคุ้มกว่า AAudio ดิบจาก Rust: minSdk ต่ำกว่า 26 ซึ่ง AAudio ไม่มี และแคตตาล็อกชุดแก้ของมัน การแก้บั๊กเสียงเฉพาะอุปกรณ์ที่สะสมมาหลายปี ซึ่งผู้เรียก AAudio ดิบค้นพบใหม่ทีละรายงาน

จาก Rust crate oboe ที่เวอร์ชัน 0.6 ณ กลางปี 2026 ห่อไลบรารี C++ ในอินเทอร์เฟซที่ปลอดภัย และเป็นแบ็กเอนด์ Android ของ cpal ไลบรารีเสียงข้ามแพลตฟอร์มมาตรฐานของ Rust สิ่งที่แลกคือบิลด์: มันคอมไพล์ซอร์ส C++ ของ Oboe ดังนั้นทูลเชน C++ กลับมาเป็นดีเพนเดนซีของบิลด์ ค่าเริ่มต้นของผมคือเส้นทาง ndk ล้วนจากโพสต์นี้ และใช้ crate oboe เมื่อ minSdk ที่เก่ากว่าหรือบั๊กเฉพาะอุปกรณ์บังคับ

ผมพูดแบบนี้หลังจากส่งคำตอบอีกแบบไปแล้ว Klarinet SDK เสียง Kotlin Multiplatform ของผม รันโซ่เอฟเฟกต์ในคอร์ C++ บน Oboe และคอร์นั้นทำงานได้ แต่บั๊กที่กินกลางคืนของผมคือบั๊กที่คอมไพเลอร์ Rust จับได้พอดี: สถานะที่แชร์กับ callback ซึ่งปลอดภัยข้ามเธรดน้อยกว่าที่รีวิวโค้ดเชื่อ ถ้าผมเริ่มเอนจินนั้นวันนี้ คอร์ DSP จะเป็น Rust มันถูกส่งเป็น Klarinet 0.6.0

คำถามที่พบบ่อย

ทำไม callback เสียงเรียกกลับเข้า Kotlin ไม่ได้

การเรียก JNI จัดสรรหน่วยความจำได้ ถือล็อกใน JVM ได้ และบล็อกได้ ทั้งหมดห้ามบนเธรดเสียง ย้ายข้อมูลด้วยอะตอมิกหรือริงบัฟเฟอร์แบบไม่มีล็อก แล้วให้ฝั่ง Kotlin สังเกตจากเธรดปกติ

ตอนที่ 11 หันไปปัญหาประสิทธิภาพที่เงียบกว่า: เพย์โหลด JSON และ CSV หลายเมกะไบต์ที่ทำให้เธรดหลักสะดุดเมื่อแยกวิเคราะห์ใน Kotlin ตอนที่ 11 การแยกวิเคราะห์หนักด้วย Serde: ย้ายการบด JSON และ CSV ไป Rust นำหลักการเรียกแบบก้อนไปใช้ แผนที่ทั้งชุดอยู่ที่ฮับ

แหล่งที่มา

Share:Compartir:แชร์:

CommentsComentariosความคิดเห็น

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…