mkaudiolibrary
A Rust library for real-time audio signal processing, featuring analog modeling through numeric functions and circuit simulation via Modified Nodal Analysis (MNA).
Features
- Thread-safe buffers with
RwLock-based concurrent access - Analog modeling for tube/tape-style saturation with asymmetric parameters
- Circuit simulation with real-time transient analysis using MNA
- DSP primitives including convolution, compression, limiting, and delay
- Audio file I/O for WAV and AIFF formats with Buffer integration
- Plugin system via MKAU format for modular processing chains
- Real-time streaming via RTAudio-style API (optional
realtimefeature) - Zero-copy design with boxed slices for minimal allocation overhead
Installation
Add to your Cargo.toml:
[]
= "1.3"
For real-time audio streaming, enable the realtime feature:
[]
= { = "1.3", = ["realtime"] }
For MIDI support with mkmidilibrary integration:
[]
= { = "1.3", = ["midi"] }
Quick Start
use ;
use Compression;
use Buffer;
// Load an audio file
let mut audio = default;
audio.load;
println!;
// Convert to thread-safe buffers for processing
let buffers = audio.to_buffers;
// Apply compression to each channel
let mut comp = new;
comp.threshold = -12.0;
comp.ratio = 4.0;
for buffer in &buffers
// Save result
audio.save;
Modules
buffer
Thread-safe audio buffers designed for concurrent multi-threaded access:
| Type | Description | Use Case |
|---|---|---|
Buffer<T> |
General-purpose buffer with read/write locking | Sample storage, inter-thread communication |
PushBuffer<T> |
FIFO buffer that shifts samples on push | FIR filters, convolution |
CircularBuffer<T> |
Ring buffer with power-of-2 sizing | Delay lines, lookahead buffers |
All buffers use Arc<RwLock<...>> internally, allowing multiple concurrent readers or exclusive write access.
use Buffer;
use thread;
let buffer = new;
let buffer_clone = buffer.clone; // Shares underlying data
// Writer thread
let writer = spawn;
writer.join.unwrap;
// Reader thread
let guard = buffer.read;
println!;
dsp
Audio processing components organized by category:
Utility Functions
use ;
let db = ratio_to_db; // ~6.02 dB
let ratio = db_to_ratio; // ~0.5
Saturation (Analog Modeling)
Asymmetric logarithmic saturation model for analog-style harmonic generation:
- Alpha parameters - Independent drive/knee control for positive and negative signals
- Beta parameters - Separate compression/gain characteristics per polarity
- Delta parameter - DC bias offset for curve positioning
- Gamma parameter - Boolean polarity inversion
use Saturation;
use Buffer;
let sat = new;
// Process single sample
let output = sat.process;
// Process buffer
let input = from_slice;
let output = new;
sat.run;
Circuit Simulation (Modified Nodal Analysis)
Sample-by-sample circuit analysis for real-time filtering:
- Component library - Resistors, capacitors, and inductors with companion model discretization
- Gaussian elimination solver with partial pivoting
- Single preprocessing step builds the static admittance matrix
- Per-sample updates for reactive element state
use ;
// Create an RC lowpass filter: fc = 1/(2πRC) ≈ 159Hz
let mut circuit = new;
circuit.add_component; // 1kΩ
circuit.add_component; // 1µF
// Build Y matrix (call once before processing)
circuit.preprocess;
// Process samples
for input_sample in audio_input
Dynamics Processing
use ;
use Buffer;
// Compressor with soft knee
let mut compressor = new;
compressor.threshold = -20.0; // dB
compressor.ratio = 4.0; // 4:1
compressor.attack = 10.0; // ms
compressor.release = 100.0; // ms
compressor.makeup = 6.0; // dB
compressor.knee = 6.0; // dB (soft knee width)
// Brickwall limiter
let mut limiter = new;
limiter.gain = 0.0; // dB input gain
limiter.ceiling = -0.1; // dB output ceiling
limiter.release = 100.0; // ms
// Process buffers
let input = new;
let output = new;
compressor.run;
Time-Based Effects
use ;
use Buffer;
// Convolution with impulse response
let impulse_response = vec!;
let conv = new.unwrap;
let input = new;
let output = new;
conv.run;
// Feedback delay
let mut delay = new; // 250ms delay
delay.feedback = 0.5; // 50% feedback
delay.mix = 0.5; // 50% wet
audiofile
Load and save audio files with automatic format detection:
use ;
// Load audio file (WAV or AIFF auto-detected)
let mut audio = default;
audio.load;
// Inspect file properties
println!;
println!;
println!;
println!;
println!;
println!;
// Direct channel access
if let Some = audio.channel
// Modify samples
if let Some = audio.channel_mut
// Save in different format
audio.set_bit_depth;
audio.save;
Buffer Integration
Seamlessly integrate with thread-safe buffers for DSP processing:
use AudioFile;
use Buffer;
let mut audio = default;
audio.load;
// Convert to thread-safe buffers
let buffers = audio.to_buffers;
// Process each channel in parallel (example)
// ... parallel processing ...
// Copy results back
audio.from_buffers;
BWF (Broadcast Wave Format)
Support for professional broadcast metadata, markers, and tempo information:
use ;
let mut audio = default;
audio.load;
// Access BWF metadata
if let Some = audio.bext
// Work with markers
for marker in audio.markers
// Add markers
audio.add_marker;
audio.add_marker;
// Set tempo for DAW integration
audio.set_tempo;
audio.set_tempo_with_time_sig;
// Set tempo at a specific sample position
audio.set_tempo_at; // 140 BPM starting at 30 seconds
// Set BWF metadata
let mut bext = with_description;
bext.set_datetime;
audio.set_bext;
// Save as BWF (includes bext chunk)
audio.save_bwf;
processor
MKAU plugin format for modular audio processing chains with thread-safe Buffer-based I/O:
use ;
// Load a plugin
let plugin = load.expect;
println!;
// Prepare for playback
plugin.prepare_to_play;
// Create audio I/O buffers
let mut audio = stereo;
// Process audio
plugin.run;
Creating Plugins
use ;
use Buffer;
// Export as dynamic library
declare_plugin!;
MIDI Processing (requires midi feature)
use ;
// Process with MIDI
let mut audio = stereo;
let mut midi = new;
// Add MIDI input messages
midi.input = Some;
// Run processor with MIDI
plugin.run_with_midi;
// Check MIDI output
for msg in midi.output.iter.flatten
realtime (Optional Feature)
Real-time audio streaming I/O inspired by the C++ RTAudio library. Enable with the realtime feature.
Supported Backends
| Platform | Backend | API |
|---|---|---|
| macOS | CoreAudio | Api::CoreAudio |
| Windows | WASAPI | Api::Wasapi |
| Linux | ALSA | Api::Alsa |
Basic Usage
use ;
// Create audio interface (auto-detects best API)
let mut audio = new.unwrap;
// List available devices
for id in audio.get_device_ids
// Define audio callback
let callback: AudioCallback = Boxnew;
// Configure output stream
let output_params = StreamParameters ;
// Configure input stream
let input_params = StreamParameters ;
// Open duplex stream
audio.open_stream.unwrap;
// Start streaming
audio.start_stream.unwrap;
// ... do work ...
// Stop and cleanup
audio.stop_stream.unwrap;
audio.close_stream;
Stereo Processing Helper
use ;
// Create callback that works with separate L/R channels
let callback = stereo_callback;
let mut audio = new.unwrap;
// ... configure and open stream with callback ...
Buffer Integration
use ;
use Buffer;
use Compression;
use ;
// Shared DSP processor
let compressor = new;
let comp_clone = compressor.clone;
let callback: AudioCallback = Boxnew;
Thread Safety
All buffer types implement Send + Sync and use interior mutability with RwLock:
| Operation | Behavior |
|---|---|
buffer.read() |
Returns BufferReadGuard, multiple allowed |
buffer.write() |
Returns BufferWriteGuard, exclusive access |
buffer.clone() |
Creates new handle to same data (like Arc) |
Guards automatically release locks when dropped (RAII pattern).
Supported Audio Formats
| Format | Extension | Read | Write | Notes |
|---|---|---|---|---|
| WAV | .wav |
Yes | Yes | PCM, IEEE Float |
| BWF | .wav |
Yes | Yes | WAV with bext chunk, markers, tempo |
| AIFF | .aiff, .aif |
Yes | Yes | Uncompressed, AIFC |
Supported bit depths: 8, 16, 24, 32-bit
Changelog
1.3.0
- Buffer-based Processor I/O: Changed
Processor::run()to useAudioIOstruct with thread-safeBuffer<f64>types - MIDI support: New
midifeature withMidiIOstruct andrun_with_midi()method - mkmidilibrary integration: Re-exports
MidiMessagefrom mkmidilibrary for MIDI event handling AudioIOprovidesstereo(),mono(), andnew()constructors for flexible channel configurations
1.2.0
- BWF (Broadcast Wave Format) support with
bextchunk for broadcast metadata - Markers/cue points with labels via
cueandLISTchunks - Tempo information via
acidchunk for DAW integration
1.1.0
- Added
realtimefeature with cross-platform audio streaming I/O Realtimestruct providing callback-based audio input/output- Platform backends: CoreAudio (macOS), WASAPI (Windows), ALSA (Linux)
- Helper functions for buffer interleaving/deinterleaving
stereo_callbackwrapper for simplified stereo processing- Seamless integration with thread-safe
Buffertypes
1.0.0
- Major update with thread-safe buffers using
RwLock - New saturation model with asymmetric numeric modeling
- Circuit simulation with MNA solver
- Refined compression and limiting with proper envelope detection
- Enhanced audiofile module with Buffer integration
- Comprehensive documentation for all modules
0.3.0
- Reconstructed sized buffer, used slice instead of buffer for plugins
0.2.x
- Added audiofile module
- Lock/unlock mechanisms for data safety
- Updated processor loader and documentation
0.1.x
- Initial development versions
- Buffer implementations with reference counting
- Basic DSP components
License
This library is dual-licensed:
- GPL-3.0 for open source projects
- Commercial license available for closed source usage
For commercial licensing inquiries, contact: minjaekim@mkaudio.company