Add automation inputs for audio graphs

This commit is contained in:
Skyler Lehmkuhl
2026-03-18 11:25:48 -04:00
parent 8acac71d86
commit 4f3da810d0
18 changed files with 1412 additions and 107 deletions
+70 -20
View File
@@ -1053,7 +1053,7 @@ impl AudioGraph {
}
/// Deserialize a preset into the graph
pub fn from_preset(preset: &crate::audio::node_graph::preset::GraphPreset, sample_rate: u32, buffer_size: usize, preset_base_path: Option<&std::path::Path>) -> Result<Self, String> {
pub fn from_preset(preset: &crate::audio::node_graph::preset::GraphPreset, sample_rate: u32, buffer_size: usize, preset_base_path: Option<&std::path::Path>, embedded_assets: Option<&std::collections::HashMap<String, Vec<u8>>>) -> Result<Self, String> {
use crate::audio::node_graph::nodes::*;
use petgraph::stable_graph::NodeIndex;
use std::collections::HashMap;
@@ -1124,7 +1124,7 @@ impl AudioGraph {
if serialized_node.node_type == "VoiceAllocator" {
if let Some(ref template_preset) = serialized_node.template_graph {
if let Some(va) = node.as_any_mut().downcast_mut::<VoiceAllocatorNode>() {
let template_graph = Self::from_preset(template_preset, sample_rate, buffer_size, preset_base_path)?;
let template_graph = Self::from_preset(template_preset, sample_rate, buffer_size, preset_base_path, embedded_assets)?;
*va.template_graph_mut() = template_graph;
va.rebuild_voices();
}
@@ -1182,10 +1182,28 @@ impl AudioGraph {
sampler_node.set_sample(samples, embedded.sample_rate as f32);
}
} else if let Some(ref path) = file_path {
// Fall back to loading from file (resolve path relative to preset)
let resolved_path = resolve_sample_path(path);
if let Err(e) = sampler_node.load_sample_from_file(&resolved_path) {
eprintln!("Failed to load sample from {}: {}", resolved_path, e);
// Check embedded assets map first (from .lbins bundle)
let loaded = if let Some(assets) = embedded_assets {
if let Some(bytes) = assets.get(path.as_str()) {
match crate::audio::sample_loader::load_audio_from_bytes(bytes, path) {
Ok(data) => {
sampler_node.set_sample(data.samples, data.sample_rate as f32);
true
}
Err(e) => {
eprintln!("Failed to decode bundled sample {}: {}", path, e);
false
}
}
} else { false }
} else { false };
if !loaded {
// Fall back to loading from filesystem
let resolved_path = resolve_sample_path(path);
if let Err(e) = sampler_node.load_sample_from_file(&resolved_path) {
eprintln!("Failed to load sample from {}: {}", resolved_path, e);
}
}
}
}
@@ -1225,20 +1243,49 @@ impl AudioGraph {
);
}
} else if let Some(ref path) = layer.file_path {
// Fall back to loading from file (resolve path relative to preset)
let resolved_path = resolve_sample_path(path);
if let Err(e) = multi_sampler_node.load_layer_from_file(
&resolved_path,
layer.key_min,
layer.key_max,
layer.root_key,
layer.velocity_min,
layer.velocity_max,
layer.loop_start,
layer.loop_end,
layer.loop_mode,
) {
eprintln!("Failed to load sample layer from {}: {}", resolved_path, e);
// Check embedded assets map first (from .lbins bundle)
let loaded = if let Some(assets) = embedded_assets {
if let Some(bytes) = assets.get(path.as_str()) {
match crate::audio::sample_loader::load_audio_from_bytes(bytes, path) {
Ok(data) => {
multi_sampler_node.add_layer(
data.samples,
data.sample_rate as f32,
layer.key_min,
layer.key_max,
layer.root_key,
layer.velocity_min,
layer.velocity_max,
layer.loop_start,
layer.loop_end,
layer.loop_mode,
);
true
}
Err(e) => {
eprintln!("Failed to decode bundled sample layer {}: {}", path, e);
false
}
}
} else { false }
} else { false };
if !loaded {
// Fall back to loading from filesystem
let resolved_path = resolve_sample_path(path);
if let Err(e) = multi_sampler_node.load_layer_from_file(
&resolved_path,
layer.key_min,
layer.key_max,
layer.root_key,
layer.velocity_min,
layer.velocity_max,
layer.loop_start,
layer.loop_end,
layer.loop_mode,
) {
eprintln!("Failed to load sample layer from {}: {}", resolved_path, e);
}
}
}
}
@@ -1258,6 +1305,9 @@ impl AudioGraph {
let result = if let Some(bundled_name) = model_path.strip_prefix("bundled:") {
eprintln!("[AmpSim] Preset: loading bundled model {:?}", bundled_name);
amp_sim.load_bundled_model(bundled_name)
} else if let Some(bytes) = embedded_assets.and_then(|a| a.get(model_path.as_str())) {
eprintln!("[AmpSim] Preset: loading from bundle {:?}", model_path);
amp_sim.load_model_from_bytes(model_path, bytes)
} else {
let resolved_path = resolve_sample_path(model_path);
eprintln!("[AmpSim] Preset: loading from file {:?}", resolved_path);
+192
View File
@@ -0,0 +1,192 @@
/// Load and save `.lbins` instrument bundle files.
///
/// A `.lbins` file is a ZIP archive with the following layout:
///
/// ```
/// instrument.lbins (ZIP)
/// ├── instrument.json ← GraphPreset JSON (existing schema)
/// ├── samples/
/// │ ├── kick.wav
/// │ └── snare.flac
/// └── models/
/// └── amp.nam
/// ```
///
/// All asset paths in `instrument.json` are ZIP-relative
/// (e.g. `"samples/kick.wav"`, `"models/amp.nam"`).
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::Path;
use crate::audio::node_graph::preset::{GraphPreset, SampleData};
/// Load a `.lbins` file.
///
/// Returns the deserialized `GraphPreset` together with a map of all
/// non-JSON entries keyed by their ZIP-relative path (e.g. `"samples/kick.wav"`).
pub fn load_lbins(path: &Path) -> Result<(GraphPreset, HashMap<String, Vec<u8>>), String> {
let file = std::fs::File::open(path)
.map_err(|e| format!("Failed to open .lbins file: {}", e))?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| format!("Failed to read ZIP archive: {}", e))?;
// Read instrument.json first
let preset_json = {
let mut entry = archive
.by_name("instrument.json")
.map_err(|_| "Missing instrument.json in .lbins archive".to_string())?;
let mut buf = String::new();
entry
.read_to_string(&mut buf)
.map_err(|e| format!("Failed to read instrument.json: {}", e))?;
buf
};
let preset = GraphPreset::from_json(&preset_json)
.map_err(|e| format!("Failed to parse instrument.json: {}", e))?;
// Read all other entries into memory
let mut assets: HashMap<String, Vec<u8>> = HashMap::new();
for i in 0..archive.len() {
let mut entry = archive
.by_index(i)
.map_err(|e| format!("Failed to read ZIP entry {}: {}", i, e))?;
let entry_name = entry.name().to_string();
if entry_name == "instrument.json" || entry.is_dir() {
continue;
}
let mut bytes = Vec::new();
entry
.read_to_end(&mut bytes)
.map_err(|e| format!("Failed to read {}: {}", entry_name, e))?;
assets.insert(entry_name, bytes);
}
Ok((preset, assets))
}
/// Save a preset to a `.lbins` file.
///
/// Asset paths in `preset` are rewritten to ZIP-relative form
/// (`samples/<basename>` or `models/<basename>`).
/// If the path is already ZIP-relative (starts with `samples/` or `models/`)
/// it is used as-is. Absolute / relative filesystem paths are resolved
/// relative to `asset_base` (typically the directory that contained the
/// original `.json` preset) and then read from disk.
pub fn save_lbins(path: &Path, preset: &GraphPreset, asset_base: Option<&Path>) -> Result<(), String> {
let file = std::fs::File::create(path)
.map_err(|e| format!("Failed to create .lbins file: {}", e))?;
let mut zip = zip::ZipWriter::new(file);
let options = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
// We'll build a rewritten copy of the preset while collecting assets
let mut rewritten = preset.clone();
// Map: original path → (zip_path, file_bytes)
let mut asset_map: HashMap<String, (String, Vec<u8>)> = HashMap::new();
// Helper: given an original asset path string and a subdirectory ("samples" or "models"),
// resolve the bytes and return the canonical ZIP-relative path.
let mut resolve_asset = |orig_path: &str, subdir: &str| -> Result<String, String> {
// Already a ZIP-relative path — no re-reading needed, caller stored bytes already
// or the asset will be provided by a prior pass. Just normalise the subdirectory.
if orig_path.starts_with(&format!("{}/", subdir)) {
return Ok(orig_path.to_string());
}
let basename = Path::new(orig_path)
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| format!("Cannot determine filename for asset: {}", orig_path))?;
let zip_path = format!("{}/{}", subdir, basename);
if !asset_map.contains_key(orig_path) {
// Resolve to an absolute filesystem path
let fs_path = if Path::new(orig_path).is_absolute() {
std::path::PathBuf::from(orig_path)
} else if let Some(base) = asset_base {
base.join(orig_path)
} else {
std::path::PathBuf::from(orig_path)
};
let bytes = std::fs::read(&fs_path)
.map_err(|e| format!("Failed to read asset {}: {}", fs_path.display(), e))?;
asset_map.insert(orig_path.to_string(), (zip_path.clone(), bytes));
}
Ok(zip_path)
};
// Rewrite paths in all nodes
for node in &mut rewritten.nodes {
// Sample data paths
if let Some(ref mut sample_data) = node.sample_data {
match sample_data {
SampleData::SimpleSampler { ref mut file_path, .. } => {
if let Some(ref orig) = file_path.clone() {
if !orig.is_empty() {
match resolve_asset(orig, "samples") {
Ok(zip_path) => *file_path = Some(zip_path),
Err(e) => eprintln!("Warning: {}", e),
}
}
}
}
SampleData::MultiSampler { ref mut layers } => {
for layer in layers.iter_mut() {
if let Some(ref orig) = layer.file_path.clone() {
if !orig.is_empty() {
match resolve_asset(orig, "samples") {
Ok(zip_path) => layer.file_path = Some(zip_path),
Err(e) => eprintln!("Warning: {}", e),
}
}
}
}
}
}
}
// NAM model path
if let Some(ref orig) = node.nam_model_path.clone() {
if !orig.starts_with("bundled:") && !orig.is_empty() {
match resolve_asset(orig, "models") {
Ok(zip_path) => node.nam_model_path = Some(zip_path),
Err(e) => eprintln!("Warning: {}", e),
}
}
}
}
// Write all collected assets to the ZIP
for (_, (zip_path, bytes)) in &asset_map {
zip.start_file(zip_path, options)
.map_err(|e| format!("Failed to start ZIP entry {}: {}", zip_path, e))?;
zip.write_all(bytes)
.map_err(|e| format!("Failed to write {}: {}", zip_path, e))?;
}
// Write instrument.json last (after assets so paths are already rewritten)
let json = rewritten
.to_json()
.map_err(|e| format!("Failed to serialize preset: {}", e))?;
zip.start_file("instrument.json", options)
.map_err(|e| format!("Failed to start instrument.json entry: {}", e))?;
zip.write_all(json.as_bytes())
.map_err(|e| format!("Failed to write instrument.json: {}", e))?;
zip.finish()
.map_err(|e| format!("Failed to finalize ZIP: {}", e))?;
Ok(())
}
+1
View File
@@ -1,6 +1,7 @@
mod graph;
mod node_trait;
mod types;
pub mod lbins;
pub mod nodes;
pub mod preset;
@@ -75,6 +75,21 @@ impl AmpSimNode {
Ok(())
}
/// Load a .nam model from in-memory bytes (used when loading from a .lbins bundle).
/// `zip_path` is the ZIP-relative path stored back in `model_path` for serialization.
pub fn load_model_from_bytes(&mut self, zip_path: &str, bytes: &[u8]) -> Result<(), String> {
let basename = std::path::Path::new(zip_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(zip_path);
let mut model = nam_ffi::NamModel::from_bytes(basename, bytes)
.map_err(|e| format!("{}", e))?;
model.set_max_buffer_size(1024);
self.model = Some(model);
self.model_path = Some(zip_path.to_string());
Ok(())
}
/// Get the loaded model path (for preset serialization).
pub fn model_path(&self) -> Option<&str> {
self.model_path.as_deref()
@@ -49,6 +49,10 @@ pub struct AutomationInputNode {
parameters: Vec<Parameter>,
/// Shared playback time (set by the graph before processing)
playback_time: Arc<RwLock<f64>>,
/// Minimum output value (for UI display range)
pub value_min: f32,
/// Maximum output value (for UI display range)
pub value_max: f32,
}
impl AutomationInputNode {
@@ -62,10 +66,12 @@ impl AutomationInputNode {
Self {
name: name.clone(),
display_name: "Automation".to_string(),
keyframes: Vec::new(),
keyframes: vec![AutomationKeyframe::new(0.0, 0.0)],
outputs,
parameters: Vec::new(),
playback_time: Arc::new(RwLock::new(0.0)),
value_min: -1.0,
value_max: 1.0,
}
}
@@ -275,6 +281,8 @@ impl AudioNode for AutomationInputNode {
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
playback_time: Arc::new(RwLock::new(0.0)),
value_min: self.value_min,
value_max: self.value_max,
})
}