Add automation inputs for audio graphs
This commit is contained in:
@@ -35,6 +35,7 @@ dasp_peak = "0.11"
|
||||
dasp_rms = "0.11"
|
||||
petgraph = "0.6"
|
||||
serde_json = "1.0"
|
||||
zip = "0.6"
|
||||
|
||||
# BeamDSP scripting engine
|
||||
beamdsp = { path = "../lightningbeam-ui/beamdsp" }
|
||||
|
||||
@@ -1655,7 +1655,7 @@ impl Engine {
|
||||
// Extract the directory path from the preset path for resolving relative sample paths
|
||||
let preset_base_path = std::path::Path::new(&preset_path).parent();
|
||||
|
||||
match AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path) {
|
||||
match AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path, None) {
|
||||
Ok(graph) => {
|
||||
// Replace the track's graph
|
||||
match self.project.get_track_mut(track_id) {
|
||||
@@ -1705,6 +1705,80 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphLoadLbins(track_id, path) => {
|
||||
match crate::audio::node_graph::lbins::load_lbins(&path) {
|
||||
Ok((preset, assets)) => {
|
||||
match AudioGraph::from_preset(&preset, self.sample_rate, 8192, None, Some(&assets)) {
|
||||
Ok(graph) => {
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => {
|
||||
track.instrument_graph = graph;
|
||||
track.graph_is_default = true;
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
|
||||
}
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
track.effects_graph = graph;
|
||||
track.graph_is_default = true;
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
|
||||
}
|
||||
Some(TrackNode::Group(track)) => {
|
||||
track.audio_graph = graph;
|
||||
track.graph_is_default = true;
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
|
||||
track_id,
|
||||
format!("Failed to load .lbins graph: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
|
||||
track_id,
|
||||
format!("Failed to open .lbins file: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphSaveLbins(track_id, path, preset_name, description, tags) => {
|
||||
let graph = match self.project.get_track(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let mut preset = graph.to_preset(&preset_name);
|
||||
preset.metadata.description = description;
|
||||
preset.metadata.tags = tags;
|
||||
preset.metadata.author = String::from("User");
|
||||
|
||||
match crate::audio::node_graph::lbins::save_lbins(&path, &preset, None) {
|
||||
Ok(()) => {
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetSaved(
|
||||
track_id,
|
||||
path.to_string_lossy().to_string(),
|
||||
));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
|
||||
track_id,
|
||||
format!("Failed to save .lbins: {}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphSaveTemplatePreset(track_id, voice_allocator_id, preset_path, preset_name) => {
|
||||
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
|
||||
|
||||
@@ -2456,6 +2530,27 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
Query::GetAutomationRange(track_id, node_id) => {
|
||||
use crate::audio::node_graph::nodes::AutomationInputNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track(track_id) {
|
||||
let graph = &track.instrument_graph;
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node(node_idx) {
|
||||
if let Some(auto_node) = graph_node.node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
QueryResponse::AutomationRange(Ok((auto_node.value_min, auto_node.value_max)))
|
||||
} else {
|
||||
QueryResponse::AutomationRange(Err(format!("Node {} is not an AutomationInputNode", node_id)))
|
||||
}
|
||||
} else {
|
||||
QueryResponse::AutomationRange(Err(format!("Node {} not found", node_id)))
|
||||
}
|
||||
} else {
|
||||
QueryResponse::AutomationRange(Err(format!("Track {} not found or is not a MIDI track", track_id)))
|
||||
}
|
||||
}
|
||||
|
||||
Query::SerializeAudioPool(project_path) => {
|
||||
QueryResponse::AudioPoolSerialized(self.audio_pool.serialize(&project_path))
|
||||
}
|
||||
@@ -2509,12 +2604,12 @@ impl Engine {
|
||||
match track_node {
|
||||
TrackNode::Audio(track) => {
|
||||
// Load into effects graph with proper buffer size (8192 to handle any callback size)
|
||||
track.effects_graph = AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path)?;
|
||||
track.effects_graph = AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path, None)?;
|
||||
Ok(())
|
||||
}
|
||||
TrackNode::Midi(track) => {
|
||||
// Load into instrument graph with proper buffer size (8192 to handle any callback size)
|
||||
track.instrument_graph = AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path)?;
|
||||
track.instrument_graph = AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path, None)?;
|
||||
Ok(())
|
||||
}
|
||||
TrackNode::Group(_) => {
|
||||
@@ -3396,6 +3491,25 @@ impl EngineController {
|
||||
));
|
||||
}
|
||||
|
||||
/// Add a keyframe to an AutomationInput node
|
||||
pub fn automation_add_keyframe(&mut self, track_id: TrackId, node_id: u32,
|
||||
time: f64, value: f32, interpolation: String,
|
||||
ease_out: (f32, f32), ease_in: (f32, f32)) {
|
||||
let _ = self.command_tx.push(Command::AutomationAddKeyframe(
|
||||
track_id, node_id, time, value, interpolation, ease_out, ease_in));
|
||||
}
|
||||
|
||||
/// Remove a keyframe from an AutomationInput node
|
||||
pub fn automation_remove_keyframe(&mut self, track_id: TrackId, node_id: u32, time: f64) {
|
||||
let _ = self.command_tx.push(Command::AutomationRemoveKeyframe(
|
||||
track_id, node_id, time));
|
||||
}
|
||||
|
||||
/// Set the display name of an AutomationInput node
|
||||
pub fn automation_set_name(&mut self, track_id: TrackId, node_id: u32, name: String) {
|
||||
let _ = self.command_tx.push(Command::AutomationSetName(track_id, node_id, name));
|
||||
}
|
||||
|
||||
/// Start recording on a track
|
||||
pub fn start_recording(&mut self, track_id: TrackId, start_time: f64) {
|
||||
let _ = self.command_tx.push(Command::StartRecording(track_id, start_time));
|
||||
@@ -3542,6 +3656,16 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::GraphLoadPreset(track_id, preset_path));
|
||||
}
|
||||
|
||||
/// Load a `.lbins` instrument bundle into a track's graph
|
||||
pub fn graph_load_lbins(&mut self, track_id: TrackId, path: std::path::PathBuf) {
|
||||
let _ = self.command_tx.push(Command::GraphLoadLbins(track_id, path));
|
||||
}
|
||||
|
||||
/// Save a track's graph as a `.lbins` instrument bundle
|
||||
pub fn graph_save_lbins(&mut self, track_id: TrackId, path: std::path::PathBuf, preset_name: String, description: String, tags: Vec<String>) {
|
||||
let _ = self.command_tx.push(Command::GraphSaveLbins(track_id, path, preset_name, description, tags));
|
||||
}
|
||||
|
||||
/// Save a VoiceAllocator's template graph as a preset
|
||||
pub fn graph_save_template_preset(&mut self, track_id: TrackId, voice_allocator_id: u32, preset_path: String, preset_name: String) {
|
||||
let _ = self.command_tx.push(Command::GraphSaveTemplatePreset(track_id, voice_allocator_id, preset_path, preset_name));
|
||||
@@ -3809,6 +3933,25 @@ impl EngineController {
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Query automation node value range (min, max)
|
||||
pub fn query_automation_range(&mut self, track_id: TrackId, node_id: u32) -> Result<(f32, f32), String> {
|
||||
if let Err(_) = self.query_tx.push(Query::GetAutomationRange(track_id, node_id)) {
|
||||
return Err("Failed to send query - queue full".to_string());
|
||||
}
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let timeout = std::time::Duration::from_millis(100);
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::AutomationRange(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_micros(50));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Serialize the audio pool for project saving
|
||||
pub fn serialize_audio_pool(&mut self, project_path: &std::path::Path) -> Result<Vec<crate::audio::pool::AudioPoolEntry>, String> {
|
||||
// Send query
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use symphonia::core::io::MediaSourceStream;
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::probe::Hint;
|
||||
use std::fs::File;
|
||||
use std::io::Cursor;
|
||||
use std::path::Path;
|
||||
|
||||
/// Loaded audio sample data
|
||||
@@ -20,33 +21,36 @@ pub struct SampleData {
|
||||
/// Load an audio file and decode it to mono f32 samples
|
||||
pub fn load_audio_file(path: impl AsRef<Path>) -> Result<SampleData, String> {
|
||||
let path = path.as_ref();
|
||||
|
||||
// Open the file
|
||||
let file = File::open(path)
|
||||
.map_err(|e| format!("Failed to open file: {}", e))?;
|
||||
|
||||
// Create a media source stream
|
||||
let file = File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
|
||||
let mss = MediaSourceStream::new(Box::new(file), Default::default());
|
||||
|
||||
// Create a hint to help the format registry guess the format
|
||||
let mut hint = Hint::new();
|
||||
if let Some(extension) = path.extension() {
|
||||
if let Some(ext_str) = extension.to_str() {
|
||||
hint.with_extension(ext_str);
|
||||
}
|
||||
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
decode_mss(mss, hint)
|
||||
}
|
||||
|
||||
// Probe the media source for a format
|
||||
let format_opts = FormatOptions::default();
|
||||
let metadata_opts = MetadataOptions::default();
|
||||
/// Load audio from an in-memory byte slice and decode it to mono f32 samples.
|
||||
/// Supports WAV, FLAC, MP3, AAC, and any other format Symphonia recognises.
|
||||
/// `filename_hint` is used to help Symphonia detect the format (e.g. "kick.wav").
|
||||
pub fn load_audio_from_bytes(bytes: &[u8], filename_hint: &str) -> Result<SampleData, String> {
|
||||
let cursor = Cursor::new(bytes.to_vec());
|
||||
let mss = MediaSourceStream::new(Box::new(cursor), Default::default());
|
||||
let mut hint = Hint::new();
|
||||
if let Some(ext) = std::path::Path::new(filename_hint).extension().and_then(|e| e.to_str()) {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
decode_mss(mss, hint)
|
||||
}
|
||||
|
||||
/// Shared decode logic: probe `mss`, find the first audio track, decode to mono f32.
|
||||
fn decode_mss(mss: MediaSourceStream, hint: Hint) -> Result<SampleData, String> {
|
||||
let probed = symphonia::default::get_probe()
|
||||
.format(&hint, mss, &format_opts, &metadata_opts)
|
||||
.format(&hint, mss, &FormatOptions::default(), &MetadataOptions::default())
|
||||
.map_err(|e| format!("Failed to probe format: {}", e))?;
|
||||
|
||||
let mut format = probed.format;
|
||||
|
||||
// Find the first audio track
|
||||
let track = format
|
||||
.tracks()
|
||||
.iter()
|
||||
@@ -56,47 +60,33 @@ pub fn load_audio_file(path: impl AsRef<Path>) -> Result<SampleData, String> {
|
||||
let track_id = track.id;
|
||||
let sample_rate = track.codec_params.sample_rate.unwrap_or(48000);
|
||||
|
||||
// Create a decoder for the track
|
||||
let dec_opts = DecoderOptions::default();
|
||||
let mut decoder = symphonia::default::get_codecs()
|
||||
.make(&track.codec_params, &dec_opts)
|
||||
.make(&track.codec_params, &DecoderOptions::default())
|
||||
.map_err(|e| format!("Failed to create decoder: {}", e))?;
|
||||
|
||||
// Decode all packets
|
||||
let mut all_samples = Vec::new();
|
||||
|
||||
loop {
|
||||
// Get the next packet
|
||||
let packet = match format.next_packet() {
|
||||
Ok(packet) => packet,
|
||||
Err(SymphoniaError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
|
||||
// End of stream
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(format!("Error reading packet: {}", e));
|
||||
}
|
||||
Err(e) => return Err(format!("Error reading packet: {}", e)),
|
||||
};
|
||||
|
||||
// Skip packets that don't belong to the selected track
|
||||
if packet.track_id() != track_id {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Decode the packet
|
||||
let decoded = decoder
|
||||
.decode(&packet)
|
||||
.map_err(|e| format!("Failed to decode packet: {}", e))?;
|
||||
|
||||
// Convert to f32 samples and mix to mono
|
||||
let samples = convert_to_mono_f32(&decoded);
|
||||
all_samples.extend_from_slice(&samples);
|
||||
all_samples.extend_from_slice(&convert_to_mono_f32(&decoded));
|
||||
}
|
||||
|
||||
Ok(SampleData {
|
||||
samples: all_samples,
|
||||
sample_rate,
|
||||
})
|
||||
Ok(SampleData { samples: all_samples, sample_rate })
|
||||
}
|
||||
|
||||
/// Convert an audio buffer to mono f32 samples
|
||||
|
||||
@@ -438,7 +438,7 @@ impl Metatrack {
|
||||
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
|
||||
if let Some(preset) = &self.audio_graph_preset {
|
||||
if !preset.nodes.is_empty() && preset.output_node.is_some() {
|
||||
self.audio_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
|
||||
self.audio_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None, None)?;
|
||||
// graph_is_default remains as serialized (false for user-modified graphs)
|
||||
} else {
|
||||
self.audio_graph = Self::create_empty_graph(sample_rate, buffer_size);
|
||||
@@ -703,7 +703,7 @@ impl MidiTrack {
|
||||
/// Rebuild the instrument graph from preset after deserialization
|
||||
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
|
||||
if let Some(preset) = &self.instrument_graph_preset {
|
||||
self.instrument_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
|
||||
self.instrument_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None, None)?;
|
||||
} else {
|
||||
// No preset - create default graph
|
||||
self.instrument_graph = AudioGraph::new(sample_rate, buffer_size);
|
||||
@@ -985,7 +985,7 @@ impl AudioTrack {
|
||||
|
||||
if has_nodes && has_output {
|
||||
// Valid preset - rebuild from it
|
||||
self.effects_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
|
||||
self.effects_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None, None)?;
|
||||
} else {
|
||||
// Empty or invalid preset - create default graph
|
||||
self.effects_graph = Self::create_default_graph(sample_rate, buffer_size);
|
||||
|
||||
@@ -181,6 +181,10 @@ pub enum Command {
|
||||
GraphSavePreset(TrackId, String, String, String, Vec<String>),
|
||||
/// Load a preset into a track's graph (track_id, preset_path)
|
||||
GraphLoadPreset(TrackId, String),
|
||||
/// Load a .lbins instrument bundle into a track's graph (track_id, path)
|
||||
GraphLoadLbins(TrackId, std::path::PathBuf),
|
||||
/// Save a track's graph as a .lbins instrument bundle (track_id, path, preset_name, description, tags)
|
||||
GraphSaveLbins(TrackId, std::path::PathBuf, String, String, Vec<String>),
|
||||
|
||||
// Metatrack subtrack graph commands
|
||||
/// Replace a metatrack's mixing graph with the default SubtrackInputs→Mixer→Output layout.
|
||||
@@ -392,6 +396,8 @@ pub enum Query {
|
||||
GetAutomationKeyframes(TrackId, u32),
|
||||
/// Get the display name of an AutomationInput node (track_id, node_id)
|
||||
GetAutomationName(TrackId, u32),
|
||||
/// Get the value range (min, max) of an AutomationInput node (track_id, node_id)
|
||||
GetAutomationRange(TrackId, u32),
|
||||
/// Serialize audio pool for project saving (project_path)
|
||||
SerializeAudioPool(std::path::PathBuf),
|
||||
/// Load audio pool from serialized entries (entries, project_path)
|
||||
@@ -480,6 +486,8 @@ pub enum QueryResponse {
|
||||
AutomationKeyframes(Result<Vec<AutomationKeyframeData>, String>),
|
||||
/// Automation node name
|
||||
AutomationName(Result<String, String>),
|
||||
/// Automation node value range (min, max)
|
||||
AutomationRange(Result<(f32, f32), String>),
|
||||
/// Serialized audio pool entries
|
||||
AudioPoolSerialized(Result<Vec<crate::audio::pool::AudioPoolEntry>, String>),
|
||||
/// Audio pool loaded (returns list of missing pool indices)
|
||||
|
||||
Reference in New Issue
Block a user