tek/src/model/sampler.rs
2024-07-12 18:41:00 +03:00

250 lines
8.2 KiB
Rust

use crate::core::*;
pub struct Sampler {
pub name: String,
pub cursor: (usize, usize),
pub editing: Option<Arc<Sample>>,
pub mapped: BTreeMap<u7, Arc<Sample>>,
pub unmapped: Vec<Arc<Sample>>,
pub voices: Vec<Voice>,
pub ports: JackPorts,
pub buffer: Vec<Vec<f32>>,
pub output_gain: f32
}
render!(Sampler |self, buf, area| {
let Rect { x, y, height, .. } = area;
let style = Style::default().gray();
let title = format!(" {} ({})", self.name, self.voices.len());
title.blit(buf, x+1, y, Some(style.white().bold().not_dim()))?;
let mut width = title.len() + 2;
for (i, (note, sample)) in self.mapped.iter().enumerate() {
let style = if i == self.cursor.0 {
Style::default().green()
} else {
Style::default()
};
let i = i as u16;
let y1 = y+1+i;
if y1 >= y + height {
break
}
if i as usize == self.cursor.0 {
"".blit(buf, x+1, y1, Some(style.bold()))?;
}
let label1 = format!("{note:3} {:12}", sample.name);
let label2 = format!("{:>6} {:>6} +0.0", sample.start, sample.end);
label1.blit(buf, x+2, y1, Some(style.bold()))?;
label2.blit(buf, x+3+label1.len()as u16, y1, Some(style))?;
width = width.max(label1.len() + label2.len() + 4);
}
let height = ((2 + self.mapped.len()) as u16).min(height);
Ok(Rect { x, y, width: (width as u16).min(area.width), height })
});
handle!(Sampler = crate::control::sampler::handle);
process!(Sampler = Sampler::process);
impl Sampler {
pub fn new (name: &str, mapped: Option<BTreeMap<u7, Arc<Sample>>>) -> Usually<JackDevice> {
Jack::new(name)?
.midi_in("midi")
.audio_in("recL")
.audio_in("recR")
.audio_out("outL")
.audio_out("outR")
.run(|ports|Box::new(Self {
name: name.into(),
cursor: (0, 0),
editing: None,
mapped: mapped.unwrap_or_else(||BTreeMap::new()),
unmapped: vec![],
voices: vec![],
ports,
buffer: vec![vec![0.0;16384];2],
output_gain: 0.5,
}))
}
/// Immutable reference to sample at cursor.
pub fn sample (&self) -> Option<&Arc<Sample>> {
for (i, sample) in self.mapped.values().enumerate() {
if i == self.cursor.0 {
return Some(sample)
}
}
None
}
pub fn process (&mut self, _: &Client, scope: &ProcessScope) -> Control {
self.process_midi_in(scope);
self.clear_output_buffer();
self.process_audio_out(scope);
self.write_output_buffer(scope);
Control::Continue
}
fn process_midi_in (&mut self, scope: &ProcessScope) {
for RawMidi { time, bytes } in self.ports.midi_ins.get("midi").unwrap().iter(scope) {
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
if let MidiMessage::NoteOn { ref key, ref vel } = message {
if let Some(sample) = self.mapped.get(key) {
self.voices.push(sample.play(time as usize, vel));
}
}
}
}
}
fn clear_output_buffer (&mut self) {
for buffer in self.buffer.iter_mut() {
buffer.fill(0.0);
}
}
fn process_audio_out (&mut self, scope: &ProcessScope) {
let channel_count = self.buffer.len();
self.voices.retain_mut(|voice|{
for index in 0..scope.n_frames() as usize {
if let Some(frame) = voice.next() {
for (channel, sample) in frame.iter().enumerate() {
//self.buffer[channel % channel_count][index] = (
//(self.buffer[channel % channel_count][index] + sample * self.output_gain) / 2.0
//);
self.buffer[channel % channel_count][index] += sample * self.output_gain;
}
} else {
return false
}
}
return true
});
}
/// Write output buffer to output ports.
fn write_output_buffer (&mut self, scope: &ProcessScope) {
for (i, port) in self.ports.audio_outs.values_mut().enumerate() {
let buffer = &self.buffer[i];
for (i, value) in port.as_mut_slice(scope).iter_mut().enumerate() {
*value = *buffer.get(i).unwrap_or(&0.0);
}
}
}
}
/// Load sample from WAV and assign to MIDI note.
#[macro_export] macro_rules! sample {
($note:expr, $name:expr, $src:expr) => {{
let (end, data) = read_sample_data($src)?;
(
u7::from_int_lossy($note).into(),
Sample::new($name, 0, end, data).into()
)
}};
}
pub fn read_sample_data (src: &str) -> Usually<(usize, Vec<Vec<f32>>)> {
let mut channels: Vec<wavers::Samples<f32>> = vec![];
for channel in wavers::Wav::from_path(src)?.channels() {
channels.push(channel);
}
let mut end = 0;
let mut data: Vec<Vec<f32>> = vec![];
for samples in channels.iter() {
let channel = Vec::from(samples.as_ref());
end = end.max(channel.len());
data.push(channel);
}
Ok((end, data))
}
pub struct Sample {
pub name: String,
pub start: usize,
pub end: usize,
pub channels: Vec<Vec<f32>>,
}
impl Sample {
pub fn new (name: &str, start: usize, end: usize, channels: Vec<Vec<f32>>) -> Arc<Self> {
Arc::new(Self { name: name.to_string(), start, end, channels })
}
pub fn play (self: &Arc<Self>, after: usize, velocity: &u7) -> Voice {
Voice {
sample: self.clone(),
after,
position: self.start,
velocity: velocity.as_int() as f32 / 127.0
}
}
}
pub struct Voice {
pub sample: Arc<Sample>,
pub after: usize,
pub position: usize,
pub velocity: f32,
}
impl Iterator for Voice {
type Item = [f32;2];
fn next (&mut self) -> Option<Self::Item> {
if self.after > 0 {
self.after = self.after - 1;
return Some([0.0, 0.0])
}
if self.position < self.sample.end {
let position = self.position;
self.position = self.position + 1;
return Some([
self.sample.channels[0][position] * self.velocity,
self.sample.channels[0][position] * self.velocity,
])
}
None
}
}
//fn render_table (
//self: &mut Sampler,
//stdout: &mut Stdout,
//offset: (u16, u16),
//) -> Result<(), Box<dyn Error>> {
//let move_to = |col, row| crossterm::cursor::MoveTo(offset.0 + col, offset.1 + row);
//stdout.queue(move_to(0, 3))?.queue(
//Print(" Name Rate Trigger Route")
//)?;
//for (i, sample) in self.samples.lock().unwrap().iter().enumerate() {
//let row = 4 + i as u16;
//for (j, (column, field)) in [
//(0, format!(" {:7} ", sample.name)),
//(9, format!(" {:.1}Hz ", sample.rate)),
//(18, format!(" MIDI C{} {} ", sample.trigger.0, sample.trigger.1)),
//(33, format!(" {:.1}dB -> Output ", sample.gain)),
//(50, format!(" {} ", sample.playing.unwrap_or(0))),
//].into_iter().enumerate() {
//stdout.queue(move_to(column, row))?;
//if self.selected_sample == i && self.selected_column == j {
//stdout.queue(PrintStyledContent(field.to_string().bold().reverse()))?;
//} else {
//stdout.queue(PrintStyledContent(field.to_string().bold()))?;
//}
//}
//}
//Ok(())
//}
//fn render_meters (
//self: &mut Sampler,
//stdout: &mut Stdout,
//offset: (u16, u16),
//) -> Result<(), Box<dyn Error>> {
//let move_to = |col, row| crossterm::cursor::MoveTo(offset.0 + col, offset.1 + row);
//for (i, sample) in self.samples.lock().iter().enumerate() {
//let row = 4 + i as u16;
//stdout.queue(move_to(32, row))?.queue(
//PrintStyledContent("▁".green())
//)?;
//}
//Ok(())
//}