tunes 1.1.0

A music composition, synthesis, and audio generation library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# tunes

A standalone Rust library for music composition, synthesis, and audio generation with real-time, concurrent playback and control.
Build complex musical pieces with an intuitive, expressive API — no runtime dependencies required.
Perfect for algorithmic music, game audio, generative art, and interactive installations.

> **Performance:** CPU synthesis measured at 100x realtime (uncached) and 20.0x realtime (cached complex compositions) on decade old hardware. SIMD sample playback: 1000+ with true concurrent playback (all samples playing simultaneously)** - can handle 500-1500+ concurrent samples in real-world scenarios.  Optional GPU acceleration available via `gpu` feature - provides minimal benefit on integrated GPUs (~1.0x on i5 6500) but scales with discrete GPU hardware.

## Table of Contents

- [Features]#features
- [Who this is and isn't for]#who-this-is-and-isnt-for
- [PROS]#pros / [CONS]#cons
- [Installation]#installation
  - [Platform Requirements]#platform-requirements
- [Quick Start]#quick-start-super-simple
  - [Real-time Playback]#real-time-playback
  - [Sample Playback (Game Audio)]#sample-playback-game-audio---simple
  - [Export to WAV or FLAC]#export-to-wav-or-flac
  - [MIDI Import/Export]#midi-importexport
  - [Live Coding (Hot Reload)]#live-coding-hot-reload
- [Comparison with Other Libraries]#comparison-with-other-music-programming-libraries
  - [When to use tunes]#when-to-use-tunes
  - [tunes' unique position]#tunes-unique-position
- [Documentation]#documentation
- [Testing]#testing
- [Examples]#examples
- [Documentation Book]#documentation-book
- [Performance & Benchmarks]#performance--benchmarks
  - [Measured Performance]#measured-performance-i5-6500--32ghz-intel-hd-530
  - [Automatic Optimizations]#automatic-optimizations
  - [Optional GPU Acceleration]#optional-gpu-acceleration
  - [Run Benchmarks Yourself]#run-benchmarks-yourself
- [License]#license
- [Contributing]#contributing

---

## Features

- **Music Theory**: Scales, chords, patterns, progressions, and transposition
- **Composition DSL**: Fluent API for building musical sequences
- **Sections & Arrangements**: Create reusable sections (verse, chorus, bridge) and arrange them
- **Synthesis**: FM synthesis, Granular synthesis, Karplus Strong, additive synthesis, filter envelopes, wavetable oscillators
- **Instruments**: 150+ Pre-configured synthesizers, bass, pads, leads, guitars, percussion, brass, strings, woodwinds and more
- **Rhythm & Drums**: 100+ pre-configured drum sounds, drum grids, euclidean rhythms, 808-style synthesis, and pattern sequencing
- **Effects, Automation and Filters**: Delay, convolution reverb, distortion, parametric EQ, chorus, modulation, tremolo, autopan, gate, limiter, compressor (with multiband support), bitcrusher, eq, phaser, flanger, saturation, sidechaining/ducking, various filters, many spectral effects
- **Musical Patterns**: Arpeggios, ornaments, tuplets, and many classical techniques and patterns built-in
- **Algorithmic Sequences**: 50+ algorithms, including Primes, Fib, 2^x, Markov, L-map, Collatz, Euclidean, Golden ratio, random/bounded walks, Thue-Morse, Recamán's, Van der Corput, L-System, Cantor, Shepherd, Cellular Automaton, and many more
- **Tempo & Timing**: Tempo changes, time signatures (3/4, 5/4, 7/8, etc.), key signatures with modal support
- **Key Signatures & Modes**: Major, minor, and all 7 Greek modes (Dorian, Phrygian, Lydian, etc.)
- **Real-time Playback**: Cross-platform audio output with concurrent mixing, live volume/pan control
- **Live Audio Recording**: Record from microphone or line-in to WAV files, then process with full effects pipeline
- **Sample Playback**: Load and play audio files (MP3, OGG, FLAC, WAV, AAC) with pitch shifting, time dilation and slicing, powered by SIMD with auto caching for efficient sample playback
- **GPU Acceleration** (optional `gpu` feature): GPU compute shader acceleration via wgpu for synthesis and export. Transparent API integration - enable with `AudioEngine::new_with_gpu()`. Performance scales with GPU hardware; integrated GPUs show minimal improvement while discrete GPUs can provide significant acceleration
- **WebAssembly Support** (optional `web` feature): Full browser support via WebAssembly - synthesis, effects, sample playback, and real-time audio in web applications. Powered by Web Audio API through cpal's wasm-bindgen integration
- **Streaming Audio**: Memory-efficient streaming for long background music and ambience without loading entire files into RAM (native-only)
- **Spatial Audio**: 3D sound positioning with distance attenuation, azimuth panning, doppler effect, and listener orientation, sound cones, and occlusion for immersive game audio
- **Audio Export**: WAV (uncompressed), FLAC (lossless ~50-60% compression), STEM export
- **MIDI Import/Export**: Import Standard MIDI Files and export compositions to MIDI with proper metadata
- **Live Coding**: Hot-reload system - edit code and hear changes instantly
  * The library includes **1547 comprehensive tests and 659 doc tests** ensuring reliability and correctness.


## Who this is and isn't for:
    For:
        learners
        tinkerers
        algorithmic/generative/procedural music
        experimental musicians
        game jammers and indie devs,
        rust coders looking to play with Digital Signal Processing without having to re-implement everything from scratch
    Not for: 
        professional producers
        DAW dwellers
        DSP engineers
        live-repl-first musicians

## PROS
    rust making music is cool
    music theory integration
    batteries included approach
    composition and code first environment (rust's ide integration and your choice of ide is everything here)
    high CPU performance and automatic simd (100x realtime synthesis uncached, 20.0x cached on complex compositions)
    multi-core parallelism (automatic via Rayon)
    optional GPU compute shader acceleration with transparent API

## CONS
    no gui or graphical elements
    no "instant feedback" outside of hot-reloading segments
    no external control or input (no midi in, osc or network controls) or hardware control
    no plugin system
    rust (not as beginner friendly as something like sonic pi)

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
tunes = "1.1.0"

# Optional: Enable GPU acceleration (requires discrete GPU for best results)
# tunes = { version = "1.1.0", features = ["gpu"] }

# Optional: Enable WebAssembly support for browser-based applications
# tunes = { version = "1.1.0", features = ["web"] }
```

### Platform Requirements

**Linux users** need ALSA development libraries:
```bash
# Debian/Ubuntu
sudo apt install libasound2-dev

# Fedora/RHEL
sudo dnf install alsa-lib-devel
```

**macOS and Windows** work out of the box with no additional dependencies.

**WebAssembly** requires wasm-pack for building:
```bash
cargo install wasm-pack
wasm-pack build --target web --features web
```

See [book/src/advanced/wasm.md](book/src/advanced/wasm.md) for complete WebAssembly setup and usage guide.

## Quick Start: Super simple!!
### Real-time Playback

```rust
use tunes::prelude::*;

fn main() -> Result<(), anyhow::Error> {
    let engine = AudioEngine::new()?;
    let mut comp = Composition::new(Tempo::new(120.0));
    let eighth = comp.tempo().eighth_note();  //getting this value to use in the next example

    // This is where you can do everything. 
    // Notes and chords can be input as floats with frequencies in hz or using or by prelude constants
    // Durations can be input as a duration of seconds as a float or using durations inferred by tempo
    
    comp.instrument("piano", &Instrument::electric_piano())
        .note(&[C4], 0.5)    //plays a c4 for half a second
        .note(&[280.0], eighth); //plays 280.0 hz note for half a second
        //continue chaining methods after the second note if you want.
    engine.play_mixer(&comp.into_mixer())?;
    Ok(())
}
```

### Sample Playback (Game Audio - Simple!)

```rust
use tunes::prelude::*;

fn main() -> Result<(), anyhow::Error> {
    let engine = AudioEngine::new()?;

    // That's it! Play samples with automatic caching and SIMD acceleration
    engine.play_sample("explosion.wav");  // Loads once, caches, plays with SIMD
    engine.play_sample("footstep.wav");   // Loads once, caches
    engine.play_sample("footstep.wav");   // Instant! Uses cache, SIMD playback
    
    play_sample!(engine, "sample.wav"); // Works the same but has compile time path resolution and runtime startup file validation
    

    // All samples play concurrently with automatic mixing
    Ok(())
}
```

### Export to WAV or FLAC

```rust
use tunes::prelude::*;

fn main() -> Result<(), anyhow::Error> {
    let engine = AudioEngine::new()?;
    let mut comp = Composition::new(Tempo::new(120.0));

    // Create a melody with instruments and effects
    comp.instrument("lead", &Instrument::synth_lead())
        .filter(Filter::low_pass(1200.0, 0.6))
        .notes(&[C4, E4, G4, C5], 0.5);

    // Export to WAV (sample rate inferred from engine)
    let mut mixer = comp.into_mixer();
    engine.export_wav(&mut mixer, "my_song.wav")?;

    // Or export to FLAC (lossless compression)
    engine.export_flac(&mut mixer, "my_song.flac")?;

    Ok(())
}
```


### MIDI Import/Export

```rust
use tunes::prelude::*;

fn main() -> Result<(), anyhow::Error> {
    // Export: Create and export a composition to MIDI
    let mut comp = Composition::new(Tempo::new(120.0));
    comp.instrument("melody", &Instrument::synth_lead())
        .notes(&[C4, E4, G4, C5], 0.5);
    comp.track("drums")
        .drum_grid(16, 0.125)
        .kick(&[0, 4, 8, 12])
        .snare(&[4, 12]);

    let mixer = comp.into_mixer();
    mixer.export_midi("song.mid")?;

    // Import: Load a MIDI file and render to audio
    let engine = AudioEngine::new()?;
    let mut imported = Mixer::import_midi("song.mid")?;
    engine.export_wav(&mut imported, "output.wav")?;

    // Or play it directly
    engine.play_mixer(&imported)?;
    Ok(())
}
```

### Live Coding (Hot Reload)

```bash
# 1. Copy the template
cp templates/live_template.rs my_live.rs

# 2. Start live coding mode
cargo run --bin tunes-live -- my_live.rs

# 3. Edit my_live.rs and save - hear changes instantly!
```

The live coding system watches your file and automatically:
- ✅ Recompiles when you save
- ✅ Stops the old version
- ✅ Starts playing the new version
- ✅ Shows compilation errors in real-time

Perfect for iterative composition and experimentation!

```rust
// my_live.rs - edit and save to hear changes!
use tunes::prelude::*;

fn main() -> anyhow::Result<()> {
    let mut comp = Composition::new(Tempo::new(140.0));

    comp.track("drums")
        .drum_grid(16, 0.125)
        .kick(&[0, 4, 8, 12]);

    // Try changing notes here and saving!
    comp.instrument("lead", &Instrument::synth_lead())
        .notes(&[C4, E4, G4], 0.25);

    let mixer = comp.into_mixer();

    // 4096 samples = ~93ms latency - good balance for live coding
    let engine = AudioEngine::with_buffer_size(4096)?;

    // Start looping playback
    let loop_id = engine.play_looping(&mixer)?;

    // Keep program running (live reload will restart)
    loop {
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}
```

**Important:**
- Use `play_looping()` for seamless loops without gaps
- Buffer size 4096 works well for most systems (increase to 8192 or 16384 if you hear glitches)
- The live reload system will automatically stop and restart with your changes


## Comparison with Other Music Programming Libraries

`tunes` occupies a unique position in the music programming landscape:

| Feature                 | SuperCollider | Sonic Pi        | Leipzig         | Strudel           | **tunes**          | Music21 |
|-------------------------|---------------|-----------------|-----------------|-------------------|--------------------|---------|
| **Type safety**         | No            | No              | No (Clojure)    | Partial (TS)      | **Yes (Rust)**     | No      |
| **Real-time audio**     | Yes           | Yes             | Yes (Overtone)  | Yes (Web Audio)   | **Yes**            | No      |
| **Sample playback**     | Yes           | Yes             | Yes (Overtone)  | Yes               | **Yes**            | No      |
| **WebAssembly support** | No            | No              | No              | Yes (JS native)   | **Yes (Rust)**     | No      |
| **GPU acceleration**    | No            | No              | No              | No                | **Yes (wgpu)**     | No      |
| **SIMD acceleration**   | Some          | No              | Via Overtone    | No                | **Yes**            | No      |
| **WAV export**          | Yes (manual)  | No              | Via Overtone    | No (browser)      | **Yes (easy)**     | Yes     |
| **FLAC export**         | Yes (manual)  | No              | No              | No                | **Yes (easy)**     | No      |
| **MIDI import/export**  | Yes           | No              | No              | No                | **Yes**            | Yes     |
| **No dependencies**     | No (needs SC) | No (needs Ruby) | No (Clojure+SC) | No (browser/Node) | **Yes**            | No      |
| **Music theory**        | Manual        | Manual          | Yes             | Some              | **Yes (built-in)** | Yes     |
| **Standalone binary**   | No            | No              | No              | No                | **Yes**            | No      |
| **Embeddable**          | No            | No              | No              | No                | **Yes**            | No      |

### When to use `tunes`

**tunes excels at:**
- Building Rust applications with music generation (games, art installations, tools)
- Browser-based music applications and interactive web demos
- Algorithmic composition with type-safe APIs
- Offline music generation and batch processing
- Learning music programming without complex setup
- Prototyping musical ideas with immediate feedback

**Use alternatives if you need:**
- **SuperCollider**: Extreme synthesis flexibility and live coding ecosystem
- **Sonic Pi**: Classroom-ready live coding with visual feedback
- **Leipzig**: Functional composition with Clojure's elegance
- **Strudel**: Browser-based collaboration and live coding
- **Music21**: Academic music analysis and score manipulation

### tunes' unique position

`tunes` is the only **standalone, embeddable, type-safe** music library with synthesis + sample playback that works on both **native and WebAssembly**. It compiles to a single binary with no runtime dependencies, making it ideal for:
- Rust game developers (Bevy, ggez, etc.)
- Browser-based music applications and web audio tools
- Desktop music applications
- Command-line music tools
- Embedded audio systems

## Documentation

Run `cargo doc --open` to view the full API documentation with detailed examples for each module.

## Testing
### Over ~2200 tests to ensure stability and prevent regressions!
```bash
cargo test
```


## Examples

Run the included **100+ examples** to hear the library in action:

```bash
# Sample playback (WAV file loading and playback)
cargo run --release --example sample_playback_demo

# Export to WAV file
cargo run --release --example wav_export_demo

# Synthesis showcase (FM, filters, envelopes)
cargo run --release --example synthesis_demo

# Theory and scales
cargo run --example theory_demo

# Effects and effect automation (dynamic parameter changes over time)
cargo run --example effects_showcase
cargo run --example automation_demo

# And many more...
cargo run -- example example-name-here
```

**Note:** Use `--release` for examples with very complex synthesis to avoid audio underruns.

## Documentation Book

**📚 Comprehensive Guide Available!**

Tunes includes a complete book with tutorials, examples, and in-depth comparisons with other audio libraries.

**Find it at:** `book/` directory in the repository

**To read locally:**
```bash
# Install mdbook if you don't have it
cargo install mdbook

# Serve the book locally
cd book
mdbook serve --open
```

The book includes:
- 🚀 **Getting Started** - From first sound to algorithmic music
- 🎵 **Core Concepts** - Architecture, engine, mixer, composition layers
- 🎮 **Game Audio Patterns** - Samples, concurrent SFX, dynamic music, spatial audio
- 🎹 **Synthesis & Effects** - FM synthesis, granular, effects chains
- 🔬 **Advanced Topics** - Generators, transformations, MIDI, optimization
- ⚖️ **Comparisons** - Clinical, honest comparisons with Kira, Rodio, SoLoud, TidalCycles, Sonic Pi, and more

**Not sure if Tunes is right for you?** Check the [Comparisons](book/src/comparisons.md) page for honest, technical comparisons with other libraries.

---

## Performance & Benchmarks

Tunes is designed for exceptional performance with automatic optimizations:

### Measured Performance (i5-6500 @ 3.2GHz, Intel HD 530)

**CPU Performance (SIMD + Rayon):**
- Uncached synthesis: 100x realtime (192 FM notes)
- Cached complex composition: 20.0-x realtime
- SIMD concurrent sample playback: 15x realtime (25-100 samples playing simultaneously)
- Conservative concurrent capacity: **1000+ samples** in real-world scenarios
- SIMD effects (all stacked): 100x realtime
- WAV export: 15x realtime (124-second multi-track composition)

**For game audio with true concurrent samples:**
- SIMD handles 50-100 samples playing **simultaneously** at **15x realtime**
- Conservative estimate: **1000+ concurrent samples** in real-world scenarios
- This is **10-20x more than other libraries** claiming "50 or dozens" of concurrent samples!
- Automatic caching and multi-core parallelism optimize performance


### Automatic Optimizations

Tunes automatically applies:
- **SIMD vectorization** (AVX2/SSE/NEON) - 15x realtime concurrent sample playback, 100x effects
-**Multi-core parallelism** (Rayon) - automatic scaling across CPU cores
-**Block processing** (512-sample chunks) - reduces overhead
-**Integer-based routing** (Vec-indexed, not HashMap)
-**Sample caching** (LRU eviction, Arc-based sharing)

### Optional GPU Acceleration

Enable with the `gpu` feature flag in Cargo.toml:
```toml
tunes = { version = "1.1.0", features = ["gpu"] }
```

**Automatic GPU acceleration (recommended):**
```rust
// GPU automatically enabled for all export/render operations
let engine = AudioEngine::new_with_gpu()?;
let mut mixer = comp.into_mixer();

engine.export_wav(&mut mixer, "output.wav")?;  // GPU accelerated
engine.export_flac(&mut mixer, "output.flac")?;  // GPU accelerated
engine.play_mixer_realtime(&mixer)?;  // GPU accelerated
```

**Manual GPU control (per-mixer):**
```rust
let engine = AudioEngine::new()?;  // CPU-only engine
let mut mixer = comp.into_mixer();

mixer.enable_gpu();  // Enable GPU for this mixer
engine.export_wav(&mut mixer, "output.wav")?;  // Uses GPU

mixer.disable_gpu();  // Disable GPU for this mixer
engine.export_wav(&mut mixer, "output2.wav")?;  // Uses CPU
```

**Performance characteristics:**
- Fallback-safe: Automatically uses CPU if GPU unavailable
- Transparent: No API changes required beyond engine initialization
- Cross-platform: wgpu supports Vulkan, Metal, DX12, WebGPU

**GPU Performance (Intel HD 530 integrated (decade old integrated gpu)):**
- Speedup: ~1.1x vs CPU (marginal improvement on integrated graphics)
- Note: Integrated GPUs show minimal benefit
- Discrete GPUs: Performance scales with compute capacity and memory bandwidth
- Note: Integrated GPU matches full CPU performance while using a fraction of system resources
### Run Benchmarks Yourself

```bash
# CPU performance on concurrent sample playback
cargo bench --bench realistic_game_audio

# Export performance (CPU and GPU)
cargo bench --bench export_speed --features gpu

# Additional benchmarks to be found in the benches/ directory!
```

---

## License

MIT OR Apache-2.0

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.