Initial release: 8-bit sound synthesizer with LLM/MCP integration
Soundgen is a Rust workspace for generating 8-bit/chiptune sound effects, UI sounds, and ambient textures for game audio assets. It features JSON-first sound specs, an MCP server for LLM tool-use, an egui GUI editor, and a runtime library with NES-authentic DAC emulation. Features: - 6 voice types: pulse, triangle, noise, DPCM, wavetable, FM - Effects: ADSR envelope, frequency sweep, biquad filter, vibrato - 13 built-in presets (SFX/UI/ambient) as JSON data files - MCP server: list_presets, generate_sfx, render_sound tools - Pattern-based sequencer (JSON song format) - egui GUI: virtual keyboard, preset browser, channel editor, undo/redo - Runtime: NES nonlinear DAC + SoundBank for game embedding - 90 tests, 0 warnings Crates: - soundgen-core: synthesis engine (no I/O) - soundgen-fmt: SoundSpec JSON schema + PresetRegistry - soundgen-io: WAV writer + audio playback - soundgen-seq: sequencer (patterns, songs) - soundgen-cli: gen/render/render-song/list-presets - soundgen-mcp: MCP server for LLM integration - soundgen-gui: egui editor - soundgen-runtime: NES DAC + SoundBank
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "soundgen-io"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
realtime = ["dep:cpal"]
|
||||
|
||||
[dependencies]
|
||||
soundgen-core.workspace = true
|
||||
soundgen-fmt.workspace = true
|
||||
hound.workspace = true
|
||||
cpal = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,14 @@
|
||||
//! WAV I/O using `hound`.
|
||||
//! Audio playback via subprocess (paplay/aplay) or cpal (realtime feature).
|
||||
|
||||
pub mod player;
|
||||
pub mod wav;
|
||||
|
||||
pub use player::{play, play_spec, PlaybackHandle};
|
||||
pub use wav::{write_wav, write_wav_bits, write_wav_mono, write_wav_mono_bits};
|
||||
|
||||
#[cfg(feature = "realtime")]
|
||||
pub mod realtime;
|
||||
|
||||
#[cfg(feature = "realtime")]
|
||||
pub use realtime::AudioPlayer;
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Audio playback — uses cpal if realtime feature is enabled,
|
||||
//! otherwise falls back to subprocess (paplay/aplay).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
static FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Play interleaved stereo samples. Returns a handle that can be used to stop.
|
||||
pub fn play(samples: &[f32], sample_rate: u32) -> Result<PlaybackHandle, String> {
|
||||
// Write to a unique temp WAV (unique per call, not per process)
|
||||
let id = FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let tmp = std::env::temp_dir().join(format!(
|
||||
"soundgen_preview_{}_{}.wav",
|
||||
std::process::id(),
|
||||
id
|
||||
));
|
||||
crate::write_wav(&tmp, samples, sample_rate)?;
|
||||
|
||||
// Try paplay, then aplay, then pw-play
|
||||
let child = Command::new("paplay")
|
||||
.arg(&tmp)
|
||||
.spawn()
|
||||
.or_else(|_| Command::new("aplay").arg("-q").arg(&tmp).spawn())
|
||||
.or_else(|_| Command::new("pw-play").arg(&tmp).spawn())
|
||||
.map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
format!(
|
||||
"no audio player available (tried paplay, aplay, pw-play): {}",
|
||||
e
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(PlaybackHandle {
|
||||
child: Some(child),
|
||||
tmp_file: Some(tmp),
|
||||
stopped: Arc::new(AtomicBool::new(false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Handle to a playing sound. Drop to let it finish naturally.
|
||||
pub struct PlaybackHandle {
|
||||
child: Option<std::process::Child>,
|
||||
tmp_file: Option<PathBuf>,
|
||||
stopped: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl PlaybackHandle {
|
||||
/// Check if playback is still running.
|
||||
pub fn is_playing(&mut self) -> bool {
|
||||
if self.stopped.load(Ordering::Relaxed) {
|
||||
return false;
|
||||
}
|
||||
match &mut self.child {
|
||||
Some(child) => match child.try_wait() {
|
||||
Ok(Some(_)) => false,
|
||||
Ok(None) => true,
|
||||
Err(_) => false,
|
||||
},
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop playback — kills the subprocess and cleans up.
|
||||
pub fn stop(&mut self) {
|
||||
if self.stopped.swap(true, Ordering::Relaxed) {
|
||||
return; // already stopped
|
||||
}
|
||||
if let Some(child) = &mut self.child {
|
||||
let _ = child.kill();
|
||||
}
|
||||
// Clean up temp file immediately on explicit stop
|
||||
if let Some(path) = &self.tmp_file {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
self.tmp_file = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PlaybackHandle {
|
||||
fn drop(&mut self) {
|
||||
// On drop: if not explicitly stopped, let the subprocess finish
|
||||
// naturally and clean up the temp file after.
|
||||
if !self.stopped.load(Ordering::Relaxed) {
|
||||
// Wait briefly for the child to finish, then clean up
|
||||
if let Some(child) = &mut self.child {
|
||||
// Give it up to 5 seconds to finish
|
||||
let _ = child.wait();
|
||||
}
|
||||
if let Some(path) = &self.tmp_file {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
// If explicitly stopped, cleanup already happened in stop()
|
||||
}
|
||||
}
|
||||
|
||||
/// Play a SoundSpec by rendering it and playing the result.
|
||||
pub fn play_spec(spec: &soundgen_fmt::SoundSpec) -> Result<PlaybackHandle, String> {
|
||||
let samples = soundgen_fmt::render_spec(spec);
|
||||
play(&samples, spec.sample_rate)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Realtime audio playback via cpal.
|
||||
//!
|
||||
//! Pre-renders sound to a buffer and plays it through the default audio device.
|
||||
//! Suitable for SFX preview and short clips.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A shared playback buffer with atomic read position.
|
||||
/// The audio callback reads from this; the main thread fills it.
|
||||
struct PlaybackState {
|
||||
buffer: Vec<f32>,
|
||||
position: AtomicUsize,
|
||||
channels: u16,
|
||||
}
|
||||
|
||||
/// Realtime audio player. Drop to stop playback.
|
||||
pub struct AudioPlayer {
|
||||
_stream: cpal::Stream,
|
||||
state: Arc<PlaybackState>,
|
||||
}
|
||||
|
||||
impl AudioPlayer {
|
||||
/// Play interleaved stereo samples through the default audio device.
|
||||
pub fn play(samples: &[f32], sample_rate: u32) -> Result<Self, String> {
|
||||
Self::play_with_channels(samples, sample_rate, 2)
|
||||
}
|
||||
|
||||
/// Play interleaved samples with the given channel count.
|
||||
pub fn play_with_channels(
|
||||
samples: &[f32],
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
) -> Result<Self, String> {
|
||||
let host = cpal::default_host();
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.ok_or("no audio output device available")?;
|
||||
|
||||
let supported_config = device
|
||||
.supported_output_configs()
|
||||
.map_err(|e| format!("enumerate configs: {}", e))?
|
||||
.find(|c| c.channels() == channels)
|
||||
.or_else(|| {
|
||||
device
|
||||
.supported_output_configs()
|
||||
.ok()
|
||||
.and_then(|mut c| c.next())
|
||||
})
|
||||
.ok_or("no supported output config")?;
|
||||
|
||||
let config = supported_config
|
||||
.with_sample_rate(cpal::SampleRate(sample_rate))
|
||||
.config();
|
||||
|
||||
let state = Arc::new(PlaybackState {
|
||||
buffer: samples.to_vec(),
|
||||
position: AtomicUsize::new(0),
|
||||
channels: config.channels,
|
||||
});
|
||||
|
||||
let state_clone = Arc::clone(&state);
|
||||
let data_type = config.sample_format;
|
||||
|
||||
let stream = match data_type {
|
||||
cpal::SampleFormat::F32 => {
|
||||
let data_fn = move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
||||
read_samples(&state_clone, data);
|
||||
};
|
||||
device
|
||||
.build_output_stream(
|
||||
&config,
|
||||
data_fn,
|
||||
|err| eprintln!("audio error: {}", err),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| format!("build stream: {}", e))?
|
||||
}
|
||||
cpal::SampleFormat::I16 => {
|
||||
let data_fn = move |data: &mut [i16], _: &cpal::OutputCallbackInfo| {
|
||||
read_samples_i16(&state_clone, data);
|
||||
};
|
||||
device
|
||||
.build_output_stream(
|
||||
&config,
|
||||
data_fn,
|
||||
|err| eprintln!("audio error: {}", err),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| format!("build stream: {}", e))?
|
||||
}
|
||||
cpal::SampleFormat::U16 => {
|
||||
let data_fn = move |data: &mut [u16], _: &cpal::OutputCallbackInfo| {
|
||||
read_samples_u16(&state_clone, data);
|
||||
};
|
||||
device
|
||||
.build_output_stream(
|
||||
&config,
|
||||
data_fn,
|
||||
|err| eprintln!("audio error: {}", err),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| format!("build stream: {}", e))?
|
||||
}
|
||||
_ => return Err("unsupported sample format".to_string()),
|
||||
};
|
||||
|
||||
stream.play().map_err(|e| format!("start stream: {}", e))?;
|
||||
|
||||
Ok(Self {
|
||||
_stream: stream,
|
||||
state,
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if playback has finished.
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.state.position.load(Ordering::Relaxed) >= self.state.buffer.len()
|
||||
}
|
||||
|
||||
/// Stop playback.
|
||||
pub fn stop(&self) {
|
||||
self.state
|
||||
.position
|
||||
.store(self.state.buffer.len(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_samples(state: &PlaybackState, output: &mut [f32]) {
|
||||
let mut pos = state.position.load(Ordering::Relaxed);
|
||||
for frame in output.chunks_mut(state.channels as usize) {
|
||||
if pos >= state.buffer.len() {
|
||||
for s in frame.iter_mut() {
|
||||
*s = 0.0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let src_channels = state.channels as usize;
|
||||
for (i, s) in frame.iter_mut().enumerate() {
|
||||
let src_idx = pos + (i % src_channels);
|
||||
*s = if src_idx < state.buffer.len() {
|
||||
state.buffer[src_idx]
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
}
|
||||
pos += src_channels;
|
||||
}
|
||||
state.position.store(pos, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn read_samples_i16(state: &PlaybackState, output: &mut [i16]) {
|
||||
let mut pos = state.position.load(Ordering::Relaxed);
|
||||
for frame in output.chunks_mut(state.channels as usize) {
|
||||
if pos >= state.buffer.len() {
|
||||
for s in frame.iter_mut() {
|
||||
*s = 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let src_channels = state.channels as usize;
|
||||
for (i, s) in frame.iter_mut().enumerate() {
|
||||
let src_idx = pos + (i % src_channels);
|
||||
*s = if src_idx < state.buffer.len() {
|
||||
(state.buffer[src_idx] * 32767.0) as i16
|
||||
} else {
|
||||
0
|
||||
};
|
||||
}
|
||||
pos += src_channels;
|
||||
}
|
||||
state.position.store(pos, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn read_samples_u16(state: &PlaybackState, output: &mut [u16]) {
|
||||
let mut pos = state.position.load(Ordering::Relaxed);
|
||||
for frame in output.chunks_mut(state.channels as usize) {
|
||||
if pos >= state.buffer.len() {
|
||||
for s in frame.iter_mut() {
|
||||
*s = 32768;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let src_channels = state.channels as usize;
|
||||
for (i, s) in frame.iter_mut().enumerate() {
|
||||
let src_idx = pos + (i % src_channels);
|
||||
*s = if src_idx < state.buffer.len() {
|
||||
((state.buffer[src_idx] + 1.0) * 32767.0) as u16
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
}
|
||||
pos += src_channels;
|
||||
}
|
||||
state.position.store(pos, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Play a single sound spec and block until it finishes.
|
||||
pub fn play_spec_blocking(spec: &soundgen_fmt::SoundSpec) -> Result<(), String> {
|
||||
let samples = soundgen_fmt::render_spec(spec);
|
||||
let player = AudioPlayer::play(&samples, spec.sample_rate)?;
|
||||
while !player.is_finished() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! WAV file writer — converts `Vec<f32>` samples to WAV files.
|
||||
|
||||
use hound::{SampleFormat, WavSpec, WavWriter};
|
||||
use std::path::Path;
|
||||
|
||||
/// Write interleaved stereo samples to a 16-bit WAV file.
|
||||
///
|
||||
/// `samples` is interleaved: [L, R, L, R, ...].
|
||||
pub fn write_wav(path: &Path, samples: &[f32], sample_rate: u32) -> Result<(), String> {
|
||||
write_wav_bits(path, samples, sample_rate, 16)
|
||||
}
|
||||
|
||||
/// Write interleaved stereo samples to a WAV file with specified bit depth (16 or 24).
|
||||
pub fn write_wav_bits(
|
||||
path: &Path,
|
||||
samples: &[f32],
|
||||
sample_rate: u32,
|
||||
bits_per_sample: u16,
|
||||
) -> Result<(), String> {
|
||||
let spec = WavSpec {
|
||||
channels: 2,
|
||||
sample_rate,
|
||||
bits_per_sample,
|
||||
sample_format: SampleFormat::Int,
|
||||
};
|
||||
|
||||
let mut writer = WavWriter::create(path, spec).map_err(|e| format!("create WAV: {}", e))?;
|
||||
|
||||
let max_val = (1 << (bits_per_sample - 1)) - 1;
|
||||
|
||||
for &sample in samples {
|
||||
let clamped = sample.clamp(-1.0, 1.0);
|
||||
let int_sample = (clamped * max_val as f32) as i32;
|
||||
if bits_per_sample == 24 {
|
||||
writer
|
||||
.write_sample::<i32>(int_sample)
|
||||
.map_err(|e| format!("write sample: {}", e))?;
|
||||
} else {
|
||||
writer
|
||||
.write_sample::<i16>(int_sample as i16)
|
||||
.map_err(|e| format!("write sample: {}", e))?;
|
||||
}
|
||||
}
|
||||
|
||||
writer
|
||||
.finalize()
|
||||
.map_err(|e| format!("finalize WAV: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write mono samples to a WAV file.
|
||||
pub fn write_wav_mono(path: &Path, samples: &[f32], sample_rate: u32) -> Result<(), String> {
|
||||
write_wav_mono_bits(path, samples, sample_rate, 16)
|
||||
}
|
||||
|
||||
pub fn write_wav_mono_bits(
|
||||
path: &Path,
|
||||
samples: &[f32],
|
||||
sample_rate: u32,
|
||||
bits_per_sample: u16,
|
||||
) -> Result<(), String> {
|
||||
let spec = WavSpec {
|
||||
channels: 1,
|
||||
sample_rate,
|
||||
bits_per_sample,
|
||||
sample_format: SampleFormat::Int,
|
||||
};
|
||||
|
||||
let mut writer = WavWriter::create(path, spec).map_err(|e| format!("create WAV: {}", e))?;
|
||||
|
||||
let max_val = (1 << (bits_per_sample - 1)) - 1;
|
||||
|
||||
for &sample in samples {
|
||||
let clamped = sample.clamp(-1.0, 1.0);
|
||||
let int_sample = (clamped * max_val as f32) as i32;
|
||||
if bits_per_sample == 24 {
|
||||
writer
|
||||
.write_sample::<i32>(int_sample)
|
||||
.map_err(|e| format!("write sample: {}", e))?;
|
||||
} else {
|
||||
writer
|
||||
.write_sample::<i16>(int_sample as i16)
|
||||
.map_err(|e| format!("write sample: {}", e))?;
|
||||
}
|
||||
}
|
||||
|
||||
writer
|
||||
.finalize()
|
||||
.map_err(|e| format!("finalize WAV: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_write_wav_stereo() {
|
||||
let path = std::env::temp_dir().join("soundgen_test_stereo.wav");
|
||||
let samples: Vec<f32> = (0..88200)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 44100.0;
|
||||
(t * 440.0 * 2.0 * std::f32::consts::PI).sin() * 0.5
|
||||
})
|
||||
.collect();
|
||||
// Interleave: mono → stereo by duplicating
|
||||
let stereo: Vec<f32> = samples.iter().flat_map(|&s| [s, s]).collect();
|
||||
write_wav(&path, &stereo, 44100).unwrap();
|
||||
assert!(path.exists());
|
||||
|
||||
// Verify by reading back
|
||||
let reader = hound::WavReader::open(&path).unwrap();
|
||||
let spec = reader.spec();
|
||||
assert_eq!(spec.channels, 2);
|
||||
assert_eq!(spec.sample_rate, 44100);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_wav_mono() {
|
||||
let path = std::env::temp_dir().join("soundgen_test_mono.wav");
|
||||
let samples: Vec<f32> = (0..44100)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 44100.0;
|
||||
(t * 220.0 * 2.0 * std::f32::consts::PI).sin() * 0.5
|
||||
})
|
||||
.collect();
|
||||
write_wav_mono(&path, &samples, 44100).unwrap();
|
||||
assert!(path.exists());
|
||||
|
||||
let reader = hound::WavReader::open(&path).unwrap();
|
||||
assert_eq!(reader.spec().channels, 1);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_wav_clamps() {
|
||||
let path = std::env::temp_dir().join("soundgen_test_clamp.wav");
|
||||
let samples = vec![2.0, -2.0, 1.0, -1.0, 0.0]; // out of range
|
||||
write_wav_mono(&path, &samples, 44100).unwrap();
|
||||
assert!(path.exists());
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user