load new samples into sampler

This commit is contained in:
🪞👃🪞 2024-07-20 20:08:32 +03:00
parent f303a8d552
commit 5e75f97e09
3 changed files with 73 additions and 45 deletions

View file

@ -27,7 +27,9 @@ See `demos/project.edn` for the initial contents of the session.
* Save project: * Save project:
* [ ] Preserve EDN layout * [ ] Preserve EDN layout
* Samples: * Samples:
* [ ] Sample browser * [x] Sample browser
* [ ] Resample
* [ ] Repitch
* [ ] Sample editor * [ ] Sample editor
* [ ] Envelope * [ ] Envelope
* [ ] Stretch sample to BPM * [ ] Stretch sample to BPM

View file

@ -6,9 +6,9 @@ use crate::{core::*, view::*, model::MODAL};
pub struct Sampler { pub struct Sampler {
pub name: String, pub name: String,
pub cursor: (usize, usize), pub cursor: (usize, usize),
pub editing: Option<Arc<Sample>>, pub editing: Option<Arc<RwLock<Sample>>>,
pub mapped: BTreeMap<u7, Arc<Sample>>, pub mapped: BTreeMap<u7, Arc<RwLock<Sample>>>,
pub unmapped: Vec<Arc<Sample>>, pub unmapped: Vec<Arc<RwLock<Sample>>>,
pub voices: Vec<Voice>, pub voices: Vec<Voice>,
pub ports: JackPorts, pub ports: JackPorts,
pub buffer: Vec<Vec<f32>>, pub buffer: Vec<Vec<f32>>,
@ -31,7 +31,7 @@ render!(Sampler |self, buf, area| {
break break
} }
let active = j == self.cursor.0; let active = j == self.cursor.0;
width = width.max(draw_sample(buf, x, y + y1, note, sample, active)?); width = width.max(draw_sample(buf, x, y + y1, note, &*sample.read().unwrap(), active)?);
y1 = y1 + 1; y1 = y1 + 1;
j = j + 1; j = j + 1;
} }
@ -75,7 +75,7 @@ pub const KEYMAP_SAMPLER: &'static [KeyBinding<Sampler>] = keymap!(Sampler {
}], }],
[Char('t'), NONE, "sample_play", "play current sample", |state: &mut Sampler| { [Char('t'), NONE, "sample_play", "play current sample", |state: &mut Sampler| {
if let Some(sample) = state.sample() { if let Some(sample) = state.sample() {
state.voices.push(sample.play(0, &100.into())) state.voices.push(Sample::play(sample, 0, &100.into()))
} }
Ok(true) Ok(true)
}], }],
@ -96,7 +96,7 @@ pub const KEYMAP_SAMPLER: &'static [KeyBinding<Sampler>] = keymap!(Sampler {
process!(Sampler = Sampler::process); process!(Sampler = Sampler::process);
impl Sampler { impl Sampler {
pub fn new (name: &str, mapped: Option<BTreeMap<u7, Arc<Sample>>>) -> Usually<JackDevice> { pub fn new (name: &str, mapped: Option<BTreeMap<u7, Arc<RwLock<Sample>>>>) -> Usually<JackDevice> {
Jack::new(name)? Jack::new(name)?
.midi_in("midi") .midi_in("midi")
.audio_in("recL") .audio_in("recL")
@ -117,12 +117,17 @@ impl Sampler {
} }
/// Immutable reference to sample at cursor. /// Immutable reference to sample at cursor.
pub fn sample (&self) -> Option<&Arc<Sample>> { pub fn sample (&self) -> Option<&Arc<RwLock<Sample>>> {
for (i, sample) in self.mapped.values().enumerate() { for (i, sample) in self.mapped.values().enumerate() {
if i == self.cursor.0 { if i == self.cursor.0 {
return Some(sample) return Some(sample)
} }
} }
for (i, sample) in self.unmapped.iter().enumerate() {
if i + self.mapped.len() == self.cursor.0 {
return Some(sample)
}
}
None None
} }
@ -140,7 +145,7 @@ impl Sampler {
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() { if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
if let MidiMessage::NoteOn { ref key, ref vel } = message { if let MidiMessage::NoteOn { ref key, ref vel } = message {
if let Some(sample) = self.mapped.get(key) { if let Some(sample) = self.mapped.get(key) {
self.voices.push(sample.play(time as usize, vel)); self.voices.push(Sample::play(sample, time as usize, vel));
} }
} }
} }
@ -223,14 +228,16 @@ pub struct Sample {
} }
impl Sample { impl Sample {
pub fn new (name: &str, start: usize, end: usize, channels: Vec<Vec<f32>>) -> Arc<Self> { pub fn new (
Arc::new(Self { name: name.to_string(), start, end, channels }) name: &str, start: usize, end: usize, channels: Vec<Vec<f32>>
) -> Arc<RwLock<Self>> {
Arc::new(RwLock::new(Self { name: name.to_string(), start, end, channels }))
} }
pub fn play (self: &Arc<Self>, after: usize, velocity: &u7) -> Voice { pub fn play (sample: &Arc<RwLock<Self>>, after: usize, velocity: &u7) -> Voice {
Voice { Voice {
sample: self.clone(), sample: sample.clone(),
after, after,
position: self.start, position: sample.read().unwrap().start,
velocity: velocity.as_int() as f32 / 127.0 velocity: velocity.as_int() as f32 / 127.0
} }
} }
@ -238,7 +245,7 @@ impl Sample {
/// A currently playing instance of a sample. /// A currently playing instance of a sample.
pub struct Voice { pub struct Voice {
pub sample: Arc<Sample>, pub sample: Arc<RwLock<Sample>>,
pub after: usize, pub after: usize,
pub position: usize, pub position: usize,
pub velocity: f32, pub velocity: f32,
@ -251,12 +258,13 @@ impl Iterator for Voice {
self.after = self.after - 1; self.after = self.after - 1;
return Some([0.0, 0.0]) return Some([0.0, 0.0])
} }
if self.position < self.sample.end { let sample = self.sample.read().unwrap();
if self.position < sample.end {
let position = self.position; let position = self.position;
self.position = self.position + 1; self.position = self.position + 1;
return Some([ return Some([
self.sample.channels[0][position] * self.velocity, sample.channels[0][position] * self.velocity,
self.sample.channels[0][position] * self.velocity, sample.channels[0][position] * self.velocity,
]) ])
} }
None None
@ -270,10 +278,12 @@ pub struct AddSampleModal {
files: Vec<OsString>, files: Vec<OsString>,
cursor: usize, cursor: usize,
offset: usize, offset: usize,
sample: Arc<Sample>, sample: Arc<RwLock<Sample>>,
search: Option<String>, search: Option<String>,
} }
exit!(AddSampleModal); exit!(AddSampleModal);
render!(AddSampleModal |self,buf,area|{ render!(AddSampleModal |self,buf,area|{
make_dim(buf); make_dim(buf);
let area = center_box(area, 64, 20); let area = center_box(area, 64, 20);
@ -300,14 +310,16 @@ render!(AddSampleModal |self,buf,area|{
} }
Lozenge(Style::default()).draw(buf, area) Lozenge(Style::default()).draw(buf, area)
}); });
handle!(AddSampleModal |self,e|{ handle!(AddSampleModal |self,e|{
if handle_keymap(self, e, KEYMAP_ADD_SAMPLE)? { if handle_keymap(self, e, KEYMAP_ADD_SAMPLE)? {
return Ok(true) return Ok(true)
} }
Ok(true) Ok(true)
}); });
impl AddSampleModal { impl AddSampleModal {
fn new (sample: &Arc<Sample>) -> Usually<Self> { fn new (sample: &Arc<RwLock<Sample>>) -> Usually<Self> {
let dir = std::env::current_dir()?; let dir = std::env::current_dir()?;
let (subdirs, files) = scan(&dir)?; let (subdirs, files) = scan(&dir)?;
Ok(Self { Ok(Self {
@ -321,22 +333,6 @@ impl AddSampleModal {
search: None search: None
}) })
} }
}
fn scan (dir: &PathBuf) -> Usually<(Vec<OsString>, Vec<OsString>)> {
Ok(read_dir(dir)?.fold(
(vec!["..".into()], vec![]),
|(mut subdirs, mut files), entry|{
let entry = entry.expect("failed to read drectory entry");
let meta = entry.metadata().expect("failed to read entry metadata");
if meta.is_file() {
files.push(entry.file_name());
} else if meta.is_dir() {
subdirs.push(entry.file_name());
}
(subdirs, files)
}))
}
impl AddSampleModal {
fn rescan (&mut self) -> Usually<()> { fn rescan (&mut self) -> Usually<()> {
scan(&self.dir).map(|(subdirs, files)|{ scan(&self.dir).map(|(subdirs, files)|{
self.subdirs = subdirs; self.subdirs = subdirs;
@ -349,22 +345,35 @@ impl AddSampleModal {
fn next (&mut self) { fn next (&mut self) {
self.cursor = self.cursor + 1; self.cursor = self.cursor + 1;
} }
fn pick (&mut self) -> Usually<()> { fn pick (&mut self) -> Usually<bool> {
if self.cursor == 0 { if self.cursor == 0 {
if let Some(parent) = self.dir.parent() { if let Some(parent) = self.dir.parent() {
self.dir = parent.into(); self.dir = parent.into();
self.rescan()?; self.rescan()?;
self.cursor = 0;
return Ok(false)
} }
} else if self.cursor < self.subdirs.len() { }
if self.cursor < self.subdirs.len() {
self.dir = self.dir.join(&self.subdirs[self.cursor]); self.dir = self.dir.join(&self.subdirs[self.cursor]);
self.rescan()?; self.rescan()?;
} else if (self.cursor - self.subdirs.len()) < self.files.len() { self.cursor = 0;
return Ok(false)
} else {
} }
Ok(()) if (self.cursor - self.subdirs.len()) < self.files.len() {
let file = &self.files[self.cursor - self.subdirs.len()];
let path = self.dir.join(file);
let (end, channels) = read_sample_data(&path.to_string_lossy())?;
let mut sample = self.sample.write().unwrap();
sample.name = file.to_string_lossy().into();
sample.end = end;
sample.channels = channels;
return Ok(true)
}
return Ok(false)
} }
} }
pub const KEYMAP_ADD_SAMPLE: &'static [KeyBinding<AddSampleModal>] = keymap!(AddSampleModal { pub const KEYMAP_ADD_SAMPLE: &'static [KeyBinding<AddSampleModal>] = keymap!(AddSampleModal {
[Esc, NONE, "add_sample_close", "close help dialog", |modal: &mut AddSampleModal|{ [Esc, NONE, "add_sample_close", "close help dialog", |modal: &mut AddSampleModal|{
modal.exit(); modal.exit();
@ -379,7 +388,24 @@ pub const KEYMAP_ADD_SAMPLE: &'static [KeyBinding<AddSampleModal>] = keymap!(Add
Ok(true) Ok(true)
}], }],
[Enter, NONE, "add_sample_enter", "activate selected entry", |modal: &mut AddSampleModal|{ [Enter, NONE, "add_sample_enter", "activate selected entry", |modal: &mut AddSampleModal|{
modal.pick()?; if modal.pick()? {
modal.exit();
}
Ok(true) Ok(true)
}], }],
}); });
fn scan (dir: &PathBuf) -> Usually<(Vec<OsString>, Vec<OsString>)> {
Ok(read_dir(dir)?.fold(
(vec!["..".into()], vec![]),
|(mut subdirs, mut files), entry|{
let entry = entry.expect("failed to read drectory entry");
let meta = entry.metadata().expect("failed to read entry metadata");
if meta.is_file() {
files.push(entry.file_name());
} else if meta.is_dir() {
subdirs.push(entry.file_name());
}
(subdirs, files)
}))
}

View file

@ -260,7 +260,7 @@ impl Sampler {
if let Some(midi) = midi { if let Some(midi) = midi {
samples.insert(midi, sample); samples.insert(midi, sample);
} else { } else {
panic!("sample without midi binding: {}", sample.name); panic!("sample without midi binding: {}", sample.read().unwrap().name);
} }
}, },
_ => panic!("unexpected in sampler {name}: {args:?}") _ => panic!("unexpected in sampler {name}: {args:?}")
@ -272,7 +272,7 @@ impl Sampler {
} }
impl Sample { impl Sample {
fn load_edn <'e> (dir: &str, args: &[Edn<'e>]) -> Usually<(Option<u7>, Arc<Self>)> { fn load_edn <'e> (dir: &str, args: &[Edn<'e>]) -> Usually<(Option<u7>, Arc<RwLock<Self>>)> {
let mut name = String::new(); let mut name = String::new();
let mut file = String::new(); let mut file = String::new();
let mut midi = None; let mut midi = None;