From 70c98991289cb05e8ab385727ec26ec5ac6320e7 Mon Sep 17 00:00:00 2001 From: AlphaNeon <102443376+ItsAlphaNeon@users.noreply.github.com> Date: Tue, 1 Dec 2026 07:04:55 -0700 Subject: [PATCH] MIDI import: Lemon SoundFont Player as a channel type The Import MIDI data form's Channel type lists Lemon SoundFont Player (issue #440). Accept asks for a SoundFont, and every new channel plays it at its track's General MIDI program and bank, MIDI channel 10 at the drum kit, or the nearest preset the font has. The next import offers the same font. - lemon-soundfont: preset_ids reads a font's presets from its headers, skipping the sample data; general_midi_preset picks the nearest one. - add_channel takes a built-in plugin's saved state; the channel is then hosted from it instead of as a new instance. Co-Authored-By: Claude Opus 5.5 --- crates/os-app/src/app.rs | 3 +- crates/os-app/src/container_ui.rs | 2 +- crates/os-app/src/control/tests.rs | 16 ++ crates/os-app/src/dialog.rs | 2 + crates/os-app/src/lemon_midi_out_ui.rs | 2 +- crates/os-app/src/midi_file.rs | 242 +++++++++++++++++++++-- crates/os-app/src/pattern_render_ui.rs | 1 + crates/os-app/src/playlist.rs | 6 +- crates/os-app/src/plugin_menu.rs | 2 +- crates/os-app/src/track_links_ui.rs | 2 +- crates/os-session/src/control/command.rs | 21 +- crates/os-session/src/soundfont.rs | 77 ++++++++ docs/control-plane.md | 2 +- docs/status.md | 9 +- plugins/lemon-soundfont/src/sf2.rs | 89 +++++++++ plugins/lemon-soundfont/src/state.rs | 12 +- 16 files changed, 459 insertions(+), 29 deletions(-) diff --git a/crates/os-app/src/app.rs b/crates/os-app/src/app.rs index 767bf10b3..50dcbbff5 100644 --- a/crates/os-app/src/app.rs +++ b/crates/os-app/src/app.rs @@ -2344,6 +2344,7 @@ impl App { self.midi_export_chosen(p, piano); } } + Then::MidiFont => self.midi_font_chosen(file), } self.invalidate(); } @@ -4711,7 +4712,7 @@ impl App { Some((r, channel)) => crate::control_ui::command(s, crate::history::LOAD_SAMPLE, None, vec![Command::LoadSample { channel, path }]).map(|_| r), // A new channel named after the file; undone, it goes. None => { - let c = Command::AddChannel { name: stem.clone(), plugin: None, sample: Some(path), track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new() }; + let c = Command::AddChannel { name: stem.clone(), plugin: None, sample: Some(path), track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new(), state: None }; crate::control_ui::command(s, crate::history::LOAD_SAMPLE, None, vec![c]).map(|r| { let id = r.first().and_then(|v| v["channel"].as_u64()).unwrap_or(0) as u32; s.session.project.channels.iter().position(|c| c.id.0 == id).unwrap_or(0) diff --git a/crates/os-app/src/container_ui.rs b/crates/os-app/src/container_ui.rs index a05da2850..ac8e387ef 100644 --- a/crates/os-app/src/container_ui.rs +++ b/crates/os-app/src/container_ui.rs @@ -314,7 +314,7 @@ impl App { } let s = &mut self.state; crate::mixer::track_ids(s); - let c = crate::control::command::Command::AddChannel { name: None, plugin: Some(CONTAINER.into()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new() }; + let c = crate::control::command::Command::AddChannel { name: None, plugin: Some(CONTAINER.into()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new(), state: None }; let id = match crate::control_ui::command(s, crate::history::ADD_CHANNEL, None, vec![c]) { Ok(r) => r.first().and_then(|v| v["channel"].as_u64())? as u32, Err(e) => return Some(e), diff --git a/crates/os-app/src/control/tests.rs b/crates/os-app/src/control/tests.rs index f25f33b4d..a75357651 100644 --- a/crates/os-app/src/control/tests.rs +++ b/crates/os-app/src/control/tests.rs @@ -412,6 +412,22 @@ fn new_things_name_their_ids() { assert_eq!(a.state.session.project.channels.last().unwrap().volume, 0.1); } +/// `add_channel` with a saved state: a built-in plugin's channel keeps it and is hosted from it (no new instance asked +/// for); a sampler's or an empty one is refused. +#[test] +fn a_new_channel_can_start_from_a_saved_state() { + let mut a = app(); + let state = vec![2u8, 0, 0, 0, 1, 0, 0, 0]; + let r = apply(&mut a.state, &test_client(), None, vec![cmd(json!({"op": "add_channel", "plugin": crate::soundfont::LEMON_SOUNDFONT, "state": state}))]).unwrap(); + let ch = r[0]["channel"].as_u64().unwrap() as u32; + let c = a.state.session.project.channels.iter().find(|c| c.id.0 == ch).unwrap(); + assert_eq!((c.plugin.as_deref(), c.plugin_state.as_deref()), (Some(crate::soundfont::FILE_NAME), Some(&state[..]))); + assert!(a.state.session.control.host.is_empty()); + for bad in [json!({"op": "add_channel", "state": state}), json!({"op": "add_channel", "plugin": crate::soundfont::LEMON_SOUNDFONT, "state": []}), json!({"op": "add_channel", "kind": "layer", "state": state})] { + assert!(apply(&mut a.state, &test_client(), None, vec![cmd(bad.clone())]).is_err(), "{bad}"); + } +} + #[test] fn a_transaction_is_one_named_step_and_all_or_nothing() { let mut a = app(); diff --git a/crates/os-app/src/dialog.rs b/crates/os-app/src/dialog.rs index a77cf0678..fac46d41a 100644 --- a/crates/os-app/src/dialog.rs +++ b/crates/os-app/src/dialog.rs @@ -120,6 +120,8 @@ pub enum Then { MidiImport(bool), /// Where to export a MIDI file; true: the piano roll's channel. MidiExport(bool), + /// The SoundFont a MIDI file's import plays with Lemon SoundFont Player (`App::midi_font_chosen`). + MidiFont, /// File ▸ FL Studio factory content folder: the folder picked (`App::set_factory_folder`). FactoryFolder, /// FILE ▸ Save as template...: the template's name, from the save dialog (`crate::project_files`). diff --git a/crates/os-app/src/lemon_midi_out_ui.rs b/crates/os-app/src/lemon_midi_out_ui.rs index 8df529952..c1a6e0421 100644 --- a/crates/os-app/src/lemon_midi_out_ui.rs +++ b/crates/os-app/src/lemon_midi_out_ui.rs @@ -26,7 +26,7 @@ impl crate::app::App { use crate::control::command::Command; let s = &mut self.state; crate::mixer::track_ids(s); - let c = Command::AddChannel { name: None, plugin: Some(LEMON_MIDI_OUT.into()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new() }; + let c = Command::AddChannel { name: None, plugin: Some(LEMON_MIDI_OUT.into()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new(), state: None }; let id = match crate::control_ui::command(s, crate::history::ADD_CHANNEL, None, vec![c]) { Ok(r) => r.first().and_then(|v| v["channel"].as_u64())? as u32, Err(e) => return Some(e), diff --git a/crates/os-app/src/midi_file.rs b/crates/os-app/src/midi_file.rs index 5d42e0935..1f1418d01 100644 --- a/crates/os-app/src/midi_file.rs +++ b/crates/os-app/src/midi_file.rs @@ -52,26 +52,35 @@ pub const TRACKS_LABEL: &str = "Which tracks to import?"; pub const CHANNELS_LABEL: &str = "Which channels to import?"; pub const TYPE_LABEL: &str = "Channel type"; -/// The instrument the import's new channels play (spec §10.3). +/// The instrument the import's new channels play (spec §10.3). Lemon SoundFont Player is Lemon Studio's own entry +/// (issue #440): every channel plays one font chosen at the import, at its track's General MIDI program. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Instrument { Trio, Citrus, Sampler, + SoundFont, } impl Instrument { - pub const ALL: [Instrument; 3] = [Instrument::Trio, Instrument::Citrus, Instrument::Sampler]; + pub const ALL: [Instrument; 4] = [Instrument::Trio, Instrument::Citrus, Instrument::Sampler, Instrument::SoundFont]; pub fn label(self) -> &'static str { match self { Instrument::Trio => crate::osc3::LEMON_TRIO, Instrument::Citrus => crate::citrus::CITRUS, Instrument::Sampler => crate::plugins::LEMON_SAMPLER, + Instrument::SoundFont => crate::soundfont::LEMON_SOUNDFONT, } } } +/// The title of the font's open dialog, which follows the form when the channel type is Lemon SoundFont Player. +pub const FONT_TITLE: &str = "Choose a SoundFont for the new channels"; +/// General MIDI's drum channel (MIDI channel 10) and the bank SoundFonts keep drum kits in. +const DRUM_CHANNEL: u8 = 9; +const DRUM_BANK: u16 = 128; + /// The form's settings (spec §2). #[derive(Debug, Clone, PartialEq)] pub struct Options { @@ -80,6 +89,8 @@ pub struct Options { /// MIDI channels 1 to 16. pub channels: [bool; 16], pub instrument: Instrument, + /// The SoundFont the channels play with Lemon SoundFont Player: the last one chosen this session. + pub font: Option, /// FILE's form: Start new project. pub new_project: bool, /// The piano roll's form: Blend with existing data. @@ -97,6 +108,7 @@ impl Default for Options { track: None, channels: [true; 16], instrument: Instrument::Trio, + font: None, new_project: true, blend: false, realign: false, @@ -143,6 +155,8 @@ thread_local! { static LAST: RefCell> = const { RefCell::new(None) }; /// An import that waits for the save-changes question (Start new project): its file and settings. static PENDING: RefCell> = const { RefCell::new(None) }; + /// FILE's import that waits for its SoundFont's open dialog: its file, what it read and its settings. + static FONT_WAIT: RefCell> = const { RefCell::new(None) }; } /// The settings a form for file `f` opens with: Realign events on for a file with a leading silence (spec §10.5). @@ -228,12 +242,16 @@ pub fn track_name(f: &Smf, i: usize) -> String { .unwrap_or_else(|| format!("Track {}", i + 1)) } -/// A channel the import makes: its name, its notes and channel control points (channel field 0 until placed). +/// A channel the import makes: its name, its notes and channel control points (channel field 0 until placed), and the +/// General MIDI bank and program its MIDI channel plays at its first note (bank 128 on MIDI channel 10), which a +/// Lemon SoundFont Player channel takes. #[derive(Debug, Clone, PartialEq)] pub struct Part { pub name: String, pub notes: Vec, pub controls: Vec, + pub bank: u16, + pub program: u8, } /// What a file gives at the project's PPQ (spec §3 to §6). @@ -295,7 +313,16 @@ pub fn convert(f: &Smf, o: &Options, ppq: u16) -> Imported { for r in &raw { let k = part_of(r.track, r.channel); let name = if o.per_track { track_name(f, r.track) } else { format!("Channel #{}", r.channel + 1) }; - let part = parts.entry(k).or_insert_with(|| Part { name, notes: Vec::new(), controls: Vec::new() }); + // The part's first note (`raw` is in start order) sets its MIDI channel's bank and program. + let part = parts.entry(k).or_insert_with(|| { + let program = value_at(f, r.track, r.channel, r.start, |k| matches!(k, Ev::Program { .. })).unwrap_or(0); + let bank = if r.channel & 15 == DRUM_CHANNEL { + DRUM_BANK + } else { + u16::from(value_at(f, r.track, r.channel, r.start, |k| matches!(k, Ev::Controller { number: 0, .. })).unwrap_or(0)) + }; + Part { name, notes: Vec::new(), controls: Vec::new(), bank, program } + }); let (s, e) = (at(r.start), at(r.end)); part.notes.push(Note { position: s, @@ -361,6 +388,32 @@ pub fn convert(f: &Smf, o: &Options, ppq: u16) -> Imported { imp } +/// What MIDI channel `channel` holds of events `kind` (program changes, a controller) when a note of track `track` +/// starts at `tick`: the last at or before it (the track's own on a tie), else the first after it; from any track, +/// as a MIDI channel is one whichever track sends to it. `None` without one. +fn value_at(f: &Smf, track: usize, channel: u8, tick: u32, kind: impl Fn(&Ev) -> bool) -> Option { + let mut before: Option<((u32, bool), u8)> = None; + let mut after: Option<(u32, u8)> = None; + for (ti, t) in f.tracks.iter().enumerate() { + for e in t.events.iter().filter(|e| kind(&e.kind) && e.kind.channel() == Some(channel)) { + let v = match e.kind { + Ev::Program { program, .. } => program, + Ev::Controller { value, .. } => value, + _ => continue, + }; + if e.tick <= tick { + let at = (e.tick, ti == track); + if before.is_none_or(|(b, _)| at >= b) { + before = Some((at, v)); + } + } else if after.is_none_or(|(a, _)| e.tick < a) { + after = Some((e.tick, v)); + } + } + } + before.map(|b| b.1).or(after.map(|a| a.1)) +} + /// Whether the form is needed for file `f` while "Show when necessary" applies: notes in more than one track or on /// more than one MIDI channel, or a leading silence (spec §10.5). pub fn necessary(f: &Smf) -> bool { @@ -557,7 +610,8 @@ fn stem(path: &Path) -> String { /// The channels' notes go into pattern `n` with the import's control points and signature markers, the markers into /// the playlist; the new channels into a filter group named after the file, which the rack then shows (spec §3, §7). /// One undo step `IMPORT_STEP`, or (`step` false: a new project's first content) none. -fn place(s: &mut State, imp: Imported, o: &Options, name: &str, n: u16, step: bool) { +/// `states`: each part's channel's saved plugin state (Lemon SoundFont Player's), else none. +fn place(s: &mut State, imp: Imported, o: &Options, states: Vec>, name: &str, n: u16, step: bool) { use crate::control::command::Command; crate::control_ui::settle_ids(s); let base = s.session.project.channels.len(); @@ -577,6 +631,7 @@ fn place(s: &mut State, imp: Imported, o: &Options, name: &str, n: u16, step: bo target: None, points: Vec::new(), children: Vec::new(), + state: states.get(i).cloned(), }) .collect(); if s.session.project.pattern(n).is_none() { @@ -691,13 +746,42 @@ impl App { if show { self.show_form(Body::Project(Form::Midi(Box::new(MidiForm { path, smf, piano, o, list: None })))); } else { - self.midi_accepted(path, smf, o, piano); + self.midi_accepted(path, smf, o, piano, false); + } + } + + /// The open dialog for the font FILE's import plays with Lemon SoundFont Player, in the last one's folder with its + /// name filled in; the import waits for it. + fn ask_font(&mut self, path: PathBuf, smf: Smf, o: Options) { + use crate::filedlg::{FileDlg, Mode}; + let last = o.font.clone(); + FONT_WAIT.set(Some((path, smf, o))); + let mut dlg = FileDlg::new(Mode::Open, FONT_TITLE, "soundfont", Then::MidiFont).filter("SoundFont", &["sf2"]).start(last.as_deref().and_then(Path::parent)); + if let Some(name) = last.as_deref().and_then(Path::file_name) { + dlg = dlg.name(&name.to_string_lossy()); + } + self.file_dialog(dlg); + } + + /// The font's open dialog closed: the waiting import plays the font chosen; cancelled, nothing is imported. + pub fn midi_font_chosen(&mut self, font: Option) { + let Some((path, smf, o)) = FONT_WAIT.take() else { return }; + match font { + Some(font) => self.midi_accepted(path, smf, Options { font: Some(font), ..o }, false, false), + None => { + self.state.message = Some(format!("Did not import {}", file_name(&path))); + self.invalidate(); + } } } /// The settings are chosen: the piano roll's import at once; FILE's into this project at once, into a new one - /// once unsaved changes are answered. - fn midi_accepted(&mut self, path: PathBuf, smf: Smf, o: Options, piano: bool) { + /// once unsaved changes are answered. FILE's import with Lemon SoundFont Player asks for the font first when + /// `ask` (the form was shown) or the last one is gone. + fn midi_accepted(&mut self, path: PathBuf, smf: Smf, o: Options, piano: bool, ask: bool) { + if !piano && o.instrument == Instrument::SoundFont && (ask || !o.font.as_deref().is_some_and(Path::is_file)) { + return self.ask_font(path, smf, o); + } // Realign for a file with a leading silence is not remembered: the next file opens as the last other import // left it (spec §10.5). let realign = if leading_silence(&smf) { LAST.with_borrow(|l| l.as_ref().is_some_and(|l| l.realign)) } else { o.realign }; @@ -730,6 +814,17 @@ impl App { if imp.parts.is_empty() { return self.tell(Kind::Info, TITLE, spans(&["", &file_name(path), " has no notes in the tracks and channels chosen."])); } + // Lemon SoundFont Player's states come first: a font that can't be used stops the import before anything changes. + let states = match (o.instrument, o.font.as_deref()) { + (Instrument::SoundFont, Some(font)) => { + let wants: Vec<(u16, u8)> = imp.parts.iter().map(|p| (p.bank, p.program)).collect(); + match crate::soundfont::general_midi_states(font, &wants) { + Ok(v) => v, + Err(e) => return self.tell(Kind::Warning, TITLE, spans(&["Could not use ", &file_name(font), &format!(": {e}.")])), + } + } + _ => Vec::new(), + }; let parts = imp.parts.len(); if o.new_project { self.leave_project(); @@ -748,10 +843,10 @@ impl App { crate::playlist::load_view(s); // A project with nothing in it counts as saved; the import is its first change. self.mark_saved(); - place(&mut self.state, imp, o, &name, 1, false); + place(&mut self.state, imp, o, states, &name, 1, false); } else { let n = self.state.pattern(); - place(&mut self.state, imp, o, &name, n, true); + place(&mut self.state, imp, o, states, &name, n, true); } let s = &mut self.state; crate::piano::center_keys(s, self.piano_grid.map_or(700.0, |g| g.h)); @@ -828,7 +923,7 @@ impl App { /// The form closed: Accept imports; Esc and the caption's × import nothing (spec §2). pub fn midi_form_closed(&mut self, f: MidiForm, reply: Reply) { if reply == Reply::Button(Answer::Ok) { - self.midi_accepted(f.path, f.smf, f.o, f.piano); + self.midi_accepted(f.path, f.smf, f.o, f.piano, true); } } @@ -1132,6 +1227,30 @@ mod tests { assert_eq!(c, [199, -200, 12700]); } + /// Each channel's General MIDI bank and program: what its MIDI channel holds at the first note, from any track + /// (the note's own on a tie), else the first change after it; MIDI channel 10 plays the drum bank. + #[test] + fn parts_take_their_channels_program_and_bank() { + let ids = |f: &Smf, o: &Options| convert(f, o, 96).parts.iter().map(|p| (p.name.clone(), p.bank, p.program)).collect::>(); + let n = |s: &str| s.to_string(); + assert_eq!(ids(&three(96), &Options::default()), [(n("Piano"), 0, 0), (n("Bass"), 0, 0), (n("Drums"), 128, 0)]); + let mut f = three(96); + // The conductor track sets the bass's program; the bass track's own change at the same tick wins. + f.tracks[0].events.push(ev(0, Ev::Program { channel: 1, program: 40 })); + f.tracks[2].events.insert(1, ev(0, Ev::Program { channel: 1, program: 33 })); + f.tracks[2].events.insert(1, ev(0, Ev::Controller { channel: 1, number: 0, value: 8 })); + // The piano's program comes after its first note; a later change on its channel is not the one. + f.tracks[1].events.push(ev(200, Ev::Program { channel: 0, program: 4 })); + f.tracks[1].events.push(ev(300, Ev::Program { channel: 0, program: 5 })); + // A kit on the drum channel keeps the drum bank whatever bank it selects. + f.tracks[3].events.insert(1, ev(0, Ev::Program { channel: 9, program: 16 })); + f.tracks[3].events.insert(1, ev(0, Ev::Controller { channel: 9, number: 0, value: 1 })); + assert_eq!(ids(&f, &Options::default()), [(n("Piano"), 0, 4), (n("Bass"), 8, 33), (n("Drums"), 128, 16)]); + // Per MIDI channel, the same. + let per_channel = Options { per_track: false, ..Options::default() }; + assert_eq!(ids(&f, &per_channel).iter().map(|x| (x.1, x.2)).collect::>(), [(0, 4), (8, 33), (128, 16)]); + } + fn test_app() -> App { let mut app = App::new(None); app.state.session.project = crate::locked::Locked::new(crate::projects::test_project()); @@ -1208,6 +1327,105 @@ mod tests { let _ = std::fs::remove_file(path); } + /// A font file whose presets are `ids` (bank, program), with no zones or samples: all an import reads of it. + #[cfg(feature = "stock-soundfont")] + fn write_font(tag: &str, ids: &[(u16, u16)]) -> PathBuf { + fn ck(id: &[u8], body: &[u8]) -> Vec { + let mut v = id.to_vec(); + v.extend((body.len() as u32).to_le_bytes()); + v.extend(body); + v + } + let mut phdr = Vec::new(); + for &(bank, program) in ids.iter().chain([&(0, 0)]) { + phdr.extend([b'p'; 20]); + phdr.extend(program.to_le_bytes()); + phdr.extend(bank.to_le_bytes()); + phdr.extend([0u8; 14]); + } + let (mut sdta, mut pdta, mut body) = (b"sdta".to_vec(), b"pdta".to_vec(), b"sfbk".to_vec()); + sdta.extend(ck(b"smpl", &[0u8; 64])); + pdta.extend(ck(b"phdr", &phdr)); + body.extend([ck(b"LIST", &sdta), ck(b"LIST", &pdta)].concat()); + let path = std::env::temp_dir().join(format!("os_midi_{tag}_{}.sf2", std::process::id())); + std::fs::write(&path, ck(b"RIFF", &body)).unwrap(); + path + } + + /// Issue #440: Lemon SoundFont Player as the channel type. Accept asks for the font; every channel plays it, at + /// its program where the font has it (else bank 0's first preset), the drums at the drum kit. Cancelled, the + /// import doesn't happen; a file that is not a font stops it with a warning. + #[cfg(feature = "stock-soundfont")] + #[test] + fn soundfont_channel_type_plays_one_font_at_each_program() { + let mut f = three(96); + f.tracks[2].events.insert(1, ev(0, Ev::Program { channel: 1, program: 33 })); + f.tracks[1].events.insert(1, ev(0, Ev::Program { channel: 0, program: 90 })); + let path = std::env::temp_dir().join(format!("os_midi_gm_{}.mid", std::process::id())); + std::fs::write(&path, os_smf::write(&f)).unwrap(); + let font = write_font("gm", &[(0, 0), (0, 33), (128, 0)]); + let open = |app: &mut App| { + crate::dialog::fake::answer(Some(path.clone())); + app.import_midi_dialog(false); + app.dialog_click(crate::dialog::DHit::Form(FHit::Combo(1))); + app.dialog_click(crate::dialog::DHit::Form(FHit::Item(3))); + assert_eq!(form(app).unwrap().combo_text(1), crate::soundfont::LEMON_SOUNDFONT); + }; + // Cancelled: nothing changes. + let mut app = test_app(); + let before = app.state.session.project.clone(); + open(&mut app); + let picks = crate::dialog::fake::shown().0; + crate::dialog::fake::answer(None); + app.dialog_click(crate::dialog::DHit::Form(FHit::Main)); + assert_eq!(crate::dialog::fake::shown().0, picks + 1, "the font's open dialog showed"); + assert_eq!(app.state.session.project, before); + // Not a font: a warning, nothing changes. + open(&mut app); + crate::dialog::fake::answer(Some(path.clone())); + app.dialog_click(crate::dialog::DHit::Form(FHit::Main)); + assert_eq!(app.state.session.project, before); + assert!(app.state.dialogs.last().is_some_and(|d| matches!(d.body, Body::Msg(_))), "the warning shows"); + // The font. + let mut app = test_app(); + app.state.session.plugins.available = crate::plugins::builtin(); + open(&mut app); + crate::dialog::fake::answer(Some(font.clone())); + app.dialog_click(crate::dialog::DHit::Form(FHit::Main)); + let p = &app.state.session.project; + assert_eq!(p.channels.iter().map(|c| c.name.as_deref().unwrap_or("")).collect::>(), ["Piano", "Bass", "Drums"]); + let got: Vec<(String, u32, u32)> = p + .channels + .iter() + .map(|c| { + assert!(crate::soundfont::is_soundfont(c)); + let b = c.plugin_state.clone().unwrap(); + let st = lemon_soundfont::state::State::parse(&b).unwrap(); + let at = |o: usize| u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]); + (st.path(), at(8), at(4) - 1) + }) + .collect(); + let fp = font.to_string_lossy().into_owned(); + assert_eq!(got, [(fp.clone(), 0, 0), (fp.clone(), 0, 33), (fp, 128, 0)]); + assert!(app.state.session.control.host.is_empty(), "the players start from their states, not as new instances"); + // The app hosts each from its state; the step's undo and redo keep the states. + let rows: Vec = (0..3).collect(); + app.sync_soundfont(); + for &r in &rows { + assert!(app.state.session.hosted_rows.contains(&r), "row {r} is hosted"); + assert_eq!(app.state.session.plugins.soundfont_file_state(r), app.state.session.project.channels[r].plugin_state, "row {r} plays its state"); + } + let after = app.state.session.project.channels.clone(); + let _ = crate::history_ui::undo(&mut app.state); + crate::history_ui::redo(&mut app.state); + let states = |c: &[os_model::Channel]| c.iter().map(|c| c.plugin_state.clone()).collect::>(); + assert_eq!(states(&app.state.session.project.channels), states(&after)); + // The next import offers the same font. + assert_eq!(LAST.with_borrow(|l| l.as_ref().and_then(|o| o.font.clone())), Some(font.clone())); + let _ = std::fs::remove_file(path); + let _ = std::fs::remove_file(font); + } + /// The piano roll's import replaces the channel's notes unless Blend is on, and selects what it brought. #[test] fn piano_roll_import() { @@ -1277,7 +1495,7 @@ mod tests { // Realign chosen for an ordinary file is remembered, as the other settings are. LAST.set(Some(Options { realign: true, ..Options::default() })); let into_this = Options { realign: false, new_project: false, ..Options::default() }; - app.midi_accepted(path.clone(), os_smf::read(&LATE_NOTE).unwrap(), into_this, false); + app.midi_accepted(path.clone(), os_smf::read(&LATE_NOTE).unwrap(), into_this, false, false); assert_eq!(LAST.with_borrow(|l| l.as_ref().map(|o| o.realign)), Some(true)); let _ = std::fs::remove_file(path); } diff --git a/crates/os-app/src/pattern_render_ui.rs b/crates/os-app/src/pattern_render_ui.rs index 4594fa1f3..8d512c972 100644 --- a/crates/os-app/src/pattern_render_ui.rs +++ b/crates/os-app/src/pattern_render_ui.rs @@ -71,6 +71,7 @@ fn channel_cmd(s: &State, path: &str, pattern: u16) -> Command { target: None, points: Vec::new(), children: Vec::new(), + state: None, } } diff --git a/crates/os-app/src/playlist.rs b/crates/os-app/src/playlist.rs index 0907ddbcd..fbdabf58e 100644 --- a/crates/os-app/src/playlist.rs +++ b/crates/os-app/src/playlist.rs @@ -1783,6 +1783,7 @@ pub fn make_unique_sample(s: &mut State, i: usize) -> String { target: None, points: Vec::new(), children: Vec::new(), + state: None, }; let clip = clips(&s.session)[i].id.0; let then = move |s: &State, r: &[serde_json::Value]| -> Vec { @@ -1851,7 +1852,7 @@ pub fn create_automation(s: &mut State, tgt: u32, name: &str, value: f64) -> u16 let points = os_flp::project::new_automation(index, tgt, value, beats).points.iter().map(crate::control::command::PointIn::of).collect(); // Spec: ui/settings-choices.md "Light mode and clip note colours (2026-10-16)" (`clip_colors`). let color = crate::control::command::color_text(Some(s.session.clip_colors.new_channel(index))); - let first = vec![Command::AddChannel { name: Some(name), plugin: None, sample: None, track: None, kind: Some("automation".into()), color, target: Some(tgt), points, children: Vec::new() }]; + let first = vec![Command::AddChannel { name: Some(name), plugin: None, sample: None, track: None, kind: Some("automation".into()), color, target: Some(tgt), points, children: Vec::new(), state: None }]; let track = free_track(s, track_after_used(s), a, b); let made = crate::control_ui::command_then(s, crate::history::CREATE_AUTOMATION, first, |s, r| { let id = r.first().and_then(|v| v["channel"].as_u64()).map(|id| id as u32); @@ -1890,7 +1891,7 @@ pub fn automation_channel(s: &mut State, target: u32, name: &str, points: Vec Vec { let id = r.first().and_then(|v| v["channel"].as_u64()).unwrap_or(0) as u32; diff --git a/crates/os-app/src/plugin_menu.rs b/crates/os-app/src/plugin_menu.rs index 08cce6ce1..1386c4ae7 100644 --- a/crates/os-app/src/plugin_menu.rs +++ b/crates/os-app/src/plugin_menu.rs @@ -207,7 +207,7 @@ pub fn add_generator(app: &mut App, index: usize, after: Option) -> Optio crate::mixer::track_ids(s); let n = s.session.project.channels.len(); let to = after.filter(|&r| r + 1 < n).map(|r| r + 1); - let first = vec![Command::AddChannel { name: None, plugin: (!sampler).then(|| d.name.clone()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new() }]; + let first = vec![Command::AddChannel { name: None, plugin: (!sampler).then(|| d.name.clone()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new(), state: None }]; let id_of = |r: &[serde_json::Value]| r.first().and_then(|v| v["channel"].as_u64()).map(|id| id as u32); let made = crate::control_ui::command_then(s, crate::history::ADD_CHANNEL, first, |_, r| { id_of(r).zip(to).map(|(channel, row)| Command::MoveChannel { channel, row }).into_iter().collect() diff --git a/crates/os-app/src/track_links_ui.rs b/crates/os-app/src/track_links_ui.rs index df1b17cba..358e7c4cc 100644 --- a/crates/os-app/src/track_links_ui.rs +++ b/crates/os-app/src/track_links_ui.rs @@ -134,7 +134,7 @@ pub fn new_instrument(app: &mut crate::app::App, t: u16, index: usize) -> Option let s = &mut app.state; let sampler = crate::plugin_menu::is_sampler(&d); crate::control_ui::settle_ids(s); - let first = vec![Command::AddChannel { name: None, plugin: (!sampler).then(|| d.name.clone()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new() }]; + let first = vec![Command::AddChannel { name: None, plugin: (!sampler).then(|| d.name.clone()), sample: None, track: None, kind: None, color: None, target: None, points: Vec::new(), children: Vec::new(), state: None }]; let id_of = |r: &[serde_json::Value]| r.first().and_then(|v| v["channel"].as_u64()).map(|id| id as u32); let made = crate::control_ui::command_then(s, TRACK_MODE, first, |s, r| { let row = id_of(r).and_then(|id| s.session.project.channels.iter().position(|c| c.id.0 == id)); diff --git a/crates/os-session/src/control/command.rs b/crates/os-session/src/control/command.rs index 24016b9e6..043a4b017 100644 --- a/crates/os-session/src/control/command.rs +++ b/crates/os-session/src/control/command.rs @@ -94,6 +94,10 @@ pub enum Command { points: Vec, #[serde(default)] children: Vec, + /// A built-in plugin's saved state as the project file keeps it (the original's), which its instance starts + /// from: a MIDI file import's SoundFont players, each with its font and preset. + #[serde(default)] + state: Option>, }, /// Audio file `path` as a clip at `position` on playlist track `track` (1-based; on an instrument track, the next /// free one below), on a new audio clip channel (through `mixer`, a mixer track's id, when given; else the track's @@ -1982,8 +1986,8 @@ impl Command { none } - Command::AddChannel { name, plugin, sample, track, kind: Some(kind), color, target, points, children } => { - if plugin.is_some() || (sample.is_some() && kind != "audio_clip") { + Command::AddChannel { name, plugin, sample, track, kind: Some(kind), color, target, points, children, state } => { + if plugin.is_some() || state.is_some() || (sample.is_some() && kind != "audio_clip") { return Err("a channel of a kind has no plugin, nor a sample unless an audio clip's".into()); } let track = track.map(|t| track_number(&s.project, t)).transpose()?; @@ -2065,12 +2069,17 @@ impl Command { // The views select the new clip (`View::AudioClipAdded`). Ok(serde_json::json!({ "channel": ch, "clip": c.id.0 })) } - Command::AddChannel { name, plugin, sample, track, .. } => { + Command::AddChannel { name, plugin, sample, track, state, .. } => { let track = track.map(|t| track_number(&s.project, t)).transpose()?; let sampler = plugin.as_deref().is_none_or(|p| p == crate::plugins::LEMON_SAMPLER); if !sampler && sample.is_some() { return Err("a sample goes into a sampler channel (no plugin)".into()); } + // A built-in recreation is kept under the original's id, and its sync hosts it from the stored state. + let built_in = plugin.as_deref().is_some_and(|p| crate::osc3::file_name(p) != p); + if state.as_ref().is_some_and(|b| b.is_empty() || sampler || !built_in) { + return Err("a saved state goes to a built-in plugin's channel, and is not empty".into()); + } let midi_out = plugin.as_deref() == Some(crate::lemon_midi_out::LEMON_MIDI_OUT); let row = match &plugin { Some(p) if !sampler => crate::projects::add_plugin_channel(s.project.get_mut(), p), @@ -2089,6 +2098,10 @@ impl Command { if let Some(t) = track { ch.mixer_track = t; } + let stored = state.is_some(); + if stored { + ch.plugin_state = state; + } if let Some(path) = sample.filter(|p| !p.is_empty()) { crate::edit::rack::auto_name(&s.settings, ch, std::path::Path::new(&path)); crate::edit::rack::read_tags(&s.settings, ch, std::path::Path::new(&path)); @@ -2101,7 +2114,7 @@ impl Command { s.touched.views.push(crate::session::View::RackAutosize); s.control.settle(s.project.get_mut()); let id = s.project.channels[row].id; - if !sampler && !midi_out && !container { + if !sampler && !midi_out && !container && !stored { s.control.host.push(super::HostReq::Instrument { channel: id, plugin: plugin.unwrap_or_default() }); } Ok(id_result("channel", id)) diff --git a/crates/os-session/src/soundfont.rs b/crates/os-session/src/soundfont.rs index 2adce07b8..8ae05f672 100644 --- a/crates/os-session/src/soundfont.rs +++ b/crates/os-session/src/soundfont.rs @@ -81,6 +81,36 @@ pub fn plugin_state(st: &crate::settings_file::SettingsStore, fl: &[u8]) -> Vec< } } +/// The saved states of new players for a MIDI file's channels (FILE ▸ Import ▸ MIDI file with this channel type): +/// each plays font `font` at the preset nearest its (bank, program) of `wants`, as +/// `lemon_soundfont::sf2::general_midi_preset` chooses it from the font's presets. An error when the font can't be +/// read, has no presets, or has a path a state can't keep (more than 255 characters, or ones past Latin-1). +pub fn general_midi_states(font: &std::path::Path, wants: &[(u16, u8)]) -> Result>, String> { + #[cfg(feature = "stock-soundfont")] + { + let path = font.to_string_lossy(); + if path.chars().count() > 255 || path.chars().any(|c| c as u32 > 255) { + return Err(format!("{LEMON_SOUNDFONT} can't keep this file's path; move it to a folder with a shorter or plainer name")); + } + let ids = lemon_soundfont::sf2::preset_ids(font)?; + wants + .iter() + .map(|&(bank, program)| { + let (bank, program) = lemon_soundfont::sf2::general_midi_preset(&ids, bank, u16::from(program)).ok_or("the SoundFont has no presets")?; + let mut st = lemon_soundfont::state::State::default(); + st.set_path(&path); + st.set_program(bank, program); + Ok(st.to_bytes()) + }) + .collect() + } + #[cfg(not(feature = "stock-soundfont"))] + { + let _ = (font, wants); + Err(format!("this build has no {LEMON_SOUNDFONT}")) + } +} + /// Hosts Lemon SoundFont Player on every SoundFont player channel without an instance, started from the channel's /// saved state. A row waiting for the picker's own instance is left to it; a row whose instance failed is not tried /// again. @@ -144,4 +174,51 @@ mod tests { assert_eq!(lemon_soundfont::params::fl_from_plugin_state(&blob), Some(fl)); assert!(String::from_utf8_lossy(&blob).contains("piano.sf2")); } + + /// An import's states name the font and the preset nearest each channel's program; the drum channel its kit. + #[cfg(feature = "stock-soundfont")] + #[test] + fn general_midi_states_name_the_nearest_preset() { + let p = std::env::temp_dir().join(format!("lemon-gm-{}.sf2", std::process::id())); + std::fs::write(&p, gm_font(&[(0, 0), (0, 25), (128, 0)])).unwrap(); + let states = general_midi_states(&p, &[(0, 25), (0, 40), (128, 16)]).unwrap(); + let read = |b: &[u8]| { + let st = lemon_soundfont::state::State::parse(b).unwrap(); + let raw = st.to_bytes(); + let at = |o: usize| u32::from_le_bytes([raw[o], raw[o + 1], raw[o + 2], raw[o + 3]]); + (st.path(), at(8), at(4) - 1) + }; + let path = p.to_string_lossy().into_owned(); + assert_eq!(read(&states[0]), (path.clone(), 0, 25)); + assert_eq!(read(&states[1]), (path.clone(), 0, 0)); + assert_eq!(read(&states[2]), (path, 128, 0)); + assert!(general_midi_states(std::path::Path::new("C:\\no\\such.sf2"), &[(0, 0)]).is_err()); + let _ = std::fs::remove_file(&p); + } + + /// A font file whose presets are `ids` (bank, program), with no zones or samples: all an import reads. + #[cfg(feature = "stock-soundfont")] + fn gm_font(ids: &[(u16, u16)]) -> Vec { + fn ck(id: &[u8], body: &[u8]) -> Vec { + let mut v = id.to_vec(); + v.extend((body.len() as u32).to_le_bytes()); + v.extend(body); + v + } + let mut phdr = Vec::new(); + for &(bank, program) in ids.iter().chain([&(0, 0)]) { + phdr.extend([b'p'; 20]); + phdr.extend(program.to_le_bytes()); + phdr.extend(bank.to_le_bytes()); + phdr.extend([0u8; 14]); + } + let mut pdta = b"pdta".to_vec(); + pdta.extend(ck(b"phdr", &phdr)); + let mut sdta = b"sdta".to_vec(); + sdta.extend(ck(b"smpl", &[0u8; 64])); + let mut body = b"sfbk".to_vec(); + body.extend(ck(b"LIST", &sdta)); + body.extend(ck(b"LIST", &pdta)); + ck(b"RIFF", &body) + } } diff --git a/docs/control-plane.md b/docs/control-plane.md index e2221ecf3..37745ffbb 100644 --- a/docs/control-plane.md +++ b/docs/control-plane.md @@ -106,7 +106,7 @@ change only the fields they are given. Positions and lengths are ticks (`state.p | `set_time_signature` | `numerator`, `denominator` | denominator 2, 4, 8 or 16 | | `set_info` | `title`, `author`, `genre`, `comments`, `url` (all optional) | the Song info | | `set_project` | `beats` (1..=32), `steps` (1..=16), `signature`, `panning_law` (`circular` or `triangular`), `play_truncated`, `pdc`, `performance`, `data_folder_use` (`none`, `relative` or `specified`), `data_folder` (the folder as the file holds it) (all optional) | Settings > Project: the bar, shown as a time signature or a division, the panning law, whether notes a pattern clip cuts off play, automatic plugin delay compensation, performance mode and the data folder. A bar value the project already has is kept even out of range | -| `add_channel` | `name`, `plugin`, `sample`, `track`, `kind` (`"audio_clip"`, `"automation"`, `"layer"`), `color`, `target`, `points`, `children` (all optional) | A channel of `kind` has no plugin: an audio clip channel playing `sample`, an automation clip with `points` (as `set_points` takes them) driving `target`, a layer playing `children` (channels' ids). A Lemon Sampler channel (with `sample` loaded), or one played by generator `plugin`, on mixer track `track`. A MIDI Out channel (`"MIDI Out"`) goes on the master track; `"Lemon Container"` makes an empty container channel. Result: `channel` | +| `add_channel` | `name`, `plugin`, `sample`, `track`, `kind` (`"audio_clip"`, `"automation"`, `"layer"`), `color`, `target`, `points`, `children`, `state` (all optional) | A channel of `kind` has no plugin: an audio clip channel playing `sample`, an automation clip with `points` (as `set_points` takes them) driving `target`, a layer playing `children` (channels' ids). A Lemon Sampler channel (with `sample` loaded), or one played by generator `plugin`, on mixer track `track`. `state` (bytes) is a built-in plugin's saved state as the project file keeps it, which the plugin starts from (a Lemon SoundFont Player with its font and preset). A MIDI Out channel (`"MIDI Out"`) goes on the master track; `"Lemon Container"` makes an empty container channel. Result: `channel` | | `add_audio_clip` | `path`, `track`, `position`; `mixer` (optional) | An audio file as a clip on a new audio clip channel (on an instrument track, the next free track below). Result: `channel`, `clip` | | `set_auto_crossfades` | `on` | Automatic crossfades: on, overlapping audio clips crossfade; off, the crossfades they made go | | `delete_channel` | `channel` | Its notes, clips and automation go too | diff --git a/docs/status.md b/docs/status.md index f7f84aaeb..0bb98d0a7 100644 --- a/docs/status.md +++ b/docs/status.md @@ -645,9 +645,12 @@ and Touch controller. Kept with the program's settings, not the project. Which w ## ✅ MIDI files - FILE ▸ Import ▸ MIDI file... (or a .mid dropped on the window): the Import MIDI data form picks the tracks, the - MIDI channels, the instrument (Lemon Trio, Citrus or Lemon Sampler) and the options; a new project, or the file - added to this one as one undo step. A channel per track (or per MIDI channel) with its notes, volume, pan and pitch - bends, the tempo changes, time signatures and markers, in a channel group named after the file + MIDI channels, the instrument (Lemon Trio, Citrus, Lemon Sampler or Lemon SoundFont Player) and the options; a new + project, or the file added to this one as one undo step. A channel per track (or per MIDI channel) with its notes, + volume, pan and pitch bends, the tempo changes, time signatures and markers, in a channel group named after the file +- With Lemon SoundFont Player, Accept asks for a SoundFont and every new channel plays it, at its track's General MIDI + program and bank (MIDI channel 10 at the drum kit), or the nearest preset the font has. One preset per channel: a + program change later in the track is not followed - The modifier held while choosing the file picks whether the form shows (General ▸ Input ▸ Manage shortcuts, MIDI import window) - FILE ▸ Export MIDI... (Shift+Ctrl+M): the current pattern, or the song's pattern clips, with a track per channel diff --git a/plugins/lemon-soundfont/src/sf2.rs b/plugins/lemon-soundfont/src/sf2.rs index f8005c811..cd3d637fe 100644 --- a/plugins/lemon-soundfont/src/sf2.rs +++ b/plugins/lemon-soundfont/src/sf2.rs @@ -255,6 +255,56 @@ fn chunks(b: &[u8]) -> Vec<(&[u8], &[u8])> { out } +/// The (bank, program) of every preset in font file `path`, sorted, read without the sample data: what a MIDI file's +/// import needs to choose each channel's preset before any player opens the font. +pub fn preset_ids(path: &Path) -> Result, String> { + use std::io::{Read, Seek, SeekFrom}; + let not_sf2 = || "not a SoundFont 2 file".to_string(); + let mut f = std::fs::File::open(path).map_err(|e| e.to_string())?; + let len = f.metadata().map_err(|e| e.to_string())?.len(); + let mut h = [0u8; 12]; + f.read_exact(&mut h).map_err(|_| not_sf2())?; + if &h[0..4] != b"RIFF" || &h[8..12] != b"sfbk" { + return Err(not_sf2()); + } + loop { + f.read_exact(&mut h[..8]).map_err(|_| "missing pdta".to_string())?; + let size = u64::from(u32_at(&h, 4)); + if size > len { + return Err(not_sf2()); + } + if &h[0..4] == b"LIST" && size >= 4 { + f.read_exact(&mut h[8..12]).map_err(|_| not_sf2())?; + if &h[8..12] == b"pdta" { + let mut body = vec![0u8; (size - 4) as usize]; + f.read_exact(&mut body).map_err(|_| not_sf2())?; + let phdr = chunks(&body).into_iter().find(|(id, _)| *id == b"phdr").map(|(_, b)| b).ok_or("missing phdr")?; + if phdr.len() % 38 != 0 || phdr.len() < 38 { + return Err("bad phdr chunk".into()); + } + // The last header is the terminal one (EOP), not a preset. + let mut ids: Vec<(u16, u16)> = phdr.chunks_exact(38).rev().skip(1).map(|p| (u16_at(p, 22), u16_at(p, 20))).collect(); + ids.sort_unstable(); + return Ok(ids); + } + f.seek(SeekFrom::Current((size - 4 + (size & 1)) as i64)).map_err(|e| e.to_string())?; + } else { + f.seek(SeekFrom::Current((size + (size & 1)) as i64)).map_err(|e| e.to_string())?; + } + } +} + +/// The preset a General MIDI channel plays of presets `ids` (bank, program), asked for (`bank`, `program`): that one; +/// else for drums (bank 128) the standard kit (128, 0) or the font's first kit; else the program in bank 0, or in the +/// first melodic bank that has it; else the font's first preset. `None` for a font with no presets. +pub fn general_midi_preset(ids: &[(u16, u16)], bank: u16, program: u16) -> Option<(u16, u16)> { + let has = |b: u16, p: u16| ids.contains(&(b, p)).then_some((b, p)); + let first = |f: &dyn Fn(&(u16, u16)) -> bool| ids.iter().copied().filter(|x| f(x)).min(); + has(bank, program) + .or_else(|| if bank == 128 { has(128, 0).or_else(|| first(&|x| x.0 == 128)) } else { has(0, program).or_else(|| first(&|x| x.0 < 128 && x.1 == program)) }) + .or_else(|| ids.iter().copied().min()) +} + impl Font { pub fn open(path: &Path) -> Result { let b = std::fs::read(path).map_err(|e| e.to_string())?; @@ -552,4 +602,43 @@ pub(crate) mod tests { assert_eq!(v[0].mods.len(), 10); assert_eq!(f.data[1], 1000); } + + /// The presets' ids come from the headers alone, past an odd-sized chunk's pad byte and the sample data. + #[test] + fn preset_ids_skip_the_samples() { + let p = std::env::temp_dir().join(format!("lemon-sf-ids-{}.sf2", std::process::id())); + std::fs::write(&p, named_font_bytes(&[0; 9], 44100, (0, 0), &[], 55, "odd", "p")).unwrap(); + assert_eq!(preset_ids(&p), Ok(vec![(0, 55)])); + std::fs::write(&p, b"RIFFWAVE").unwrap(); + assert!(preset_ids(&p).is_err()); + let _ = std::fs::remove_file(&p); + } + + /// On real fonts, the header read agrees with the whole parse: + /// `OS_SF2="a.sf2;b.sf2" cargo test -p lemon-soundfont preset_ids_match_real_fonts -- --ignored` + #[test] + #[ignore] + fn preset_ids_match_real_fonts() { + let files = std::env::var("OS_SF2").expect("OS_SF2: font files, separated by ;"); + for f in files.split(';').filter(|f| !f.is_empty()) { + let p = Path::new(f); + let ids = preset_ids(p).unwrap(); + let all: Vec<(u16, u16)> = Font::open(p).unwrap().presets.iter().map(|x| (x.bank, x.program)).collect(); + assert_eq!(ids, all, "{f}"); + println!("{f}: {} presets", ids.len()); + } + } + + #[test] + fn general_midi_presets_fall_back_by_kind() { + let ids = [(0, 0), (0, 25), (8, 25), (8, 30), (128, 0), (128, 16)]; + assert_eq!(general_midi_preset(&ids, 8, 25), Some((8, 25))); + assert_eq!(general_midi_preset(&ids, 3, 25), Some((0, 25))); + assert_eq!(general_midi_preset(&ids, 0, 30), Some((8, 30))); + assert_eq!(general_midi_preset(&ids, 0, 40), Some((0, 0))); + assert_eq!(general_midi_preset(&ids, 128, 16), Some((128, 16))); + assert_eq!(general_midi_preset(&ids, 128, 40), Some((128, 0))); + assert_eq!(general_midi_preset(&[(0, 1), (128, 8)], 128, 40), Some((128, 8))); + assert_eq!(general_midi_preset(&[], 0, 0), None); + } } diff --git a/plugins/lemon-soundfont/src/state.rs b/plugins/lemon-soundfont/src/state.rs index 310f6c0e5..b47640f6f 100644 --- a/plugins/lemon-soundfont/src/state.rs +++ b/plugins/lemon-soundfont/src/state.rs @@ -222,11 +222,19 @@ impl State { } } + /// A version 2 state names preset (`bank`, `program`) whatever font it opens (a later version names a place in + /// the font's list, so this leaves it as it is). + pub fn set_program(&mut self, bank: u16, program: u16) { + if self.version() == 2 { + self.set_u32(4, u32::from(program) + 1); + self.set_u32(8, u32::from(bank)); + } + } + pub fn set_preset(&mut self, font: &Font, i: usize) { let Some(p) = font.presets.get(i) else { return }; if self.version() == 2 { - self.set_u32(4, u32::from(p.program) + 1); - self.set_u32(8, u32::from(p.bank)); + self.set_program(p.bank, p.program); } else { let o = self.path_end() + V6_INDEX; self.set_u32(o, i as u32);