refactor: merge plugin, sampler -> mixer; transport -> sequencer; time -> core

This commit is contained in:
🪞👃🪞 2024-08-10 21:23:20 +03:00
parent 6206a43b4a
commit a659062dbc
46 changed files with 128 additions and 198 deletions

View file

@ -1,7 +1,15 @@
pub(crate) use tek_core::*;
pub(crate) use tek_core::ratatui::prelude::*;
pub(crate) use tek_core::crossterm::event::{KeyCode, KeyModifiers};
pub(crate) use tek_core::midly::{num::u7, live::LiveEvent, MidiMessage};
pub(crate) use tek_jack::{*, jack::*};
pub(crate) use std::collections::BTreeMap;
pub(crate) use std::sync::{Arc, Mutex, RwLock};
pub(crate) use std::path::PathBuf;
pub(crate) use std::ffi::OsString;
pub(crate) use std::fs::read_dir;
submod! {
mixer
mixer_cli
@ -10,4 +18,14 @@ submod! {
track
track_view
track_handle
plugin
plugin_lv2
plugin_lv2_gui
plugin_vst2
plugin_vst3
sample
sample_add
sampler
sampler_edn
voice
}

View file

@ -0,0 +1,211 @@
use crate::*;
/// A plugin device.
pub struct Plugin {
pub name: String,
pub path: Option<String>,
pub plugin: Option<PluginKind>,
pub selected: usize,
pub mapping: bool,
pub ports: JackPorts,
}
render!(Plugin = render_plugin);
handle!(Plugin |self, e| handle_keymap(self, e, KEYMAP_PLUGIN));
process!(Plugin = Plugin::process);
/// Supported plugin formats.
pub enum PluginKind {
LV2(LV2Plugin),
VST2 {
instance: ::vst::host::PluginInstance
},
VST3,
}
impl Plugin {
pub fn new_lv2 (name: &str, path: &str) -> Usually<JackDevice> {
let plugin = LV2Plugin::new(path)?;
jack_from_lv2(name, &plugin.plugin)?
.run(|ports|Box::new(Self {
name: name.into(),
path: Some(String::from(path)),
plugin: Some(PluginKind::LV2(plugin)),
selected: 0,
mapping: false,
ports
}))
}
/// Create a plugin host device.
pub fn new (name: &str) -> Usually<Self> {
Ok(Self {
name: name.into(),
path: None,
plugin: None,
selected: 0,
mapping: false,
ports: JackPorts::default()
})
}
pub fn process (&mut self, _: &Client, scope: &ProcessScope) -> Control {
match self.plugin.as_mut() {
Some(PluginKind::LV2(LV2Plugin {
features,
ref mut instance,
ref mut input_buffer,
..
})) => {
let urid = features.midi_urid();
input_buffer.clear();
for port in self.ports.midi_ins.values() {
let mut atom = ::livi::event::LV2AtomSequence::new(
&features,
scope.n_frames() as usize
);
for event in port.iter(scope) {
match event.bytes.len() {
3 => atom.push_midi_event::<3>(
event.time as i64,
urid,
&event.bytes[0..3]
).unwrap(),
_ => {}
}
}
input_buffer.push(atom);
}
let mut outputs = vec![];
for _ in self.ports.midi_outs.iter() {
outputs.push(::livi::event::LV2AtomSequence::new(
&features,
scope.n_frames() as usize
));
}
let ports = ::livi::EmptyPortConnections::new()
.with_atom_sequence_inputs(
input_buffer.iter()
)
.with_atom_sequence_outputs(
outputs.iter_mut()
)
.with_audio_inputs(
self.ports.audio_ins.values().map(|o|o.as_slice(scope))
)
.with_audio_outputs(
self.ports.audio_outs.values_mut().map(|o|o.as_mut_slice(scope))
);
unsafe {
instance.run(scope.n_frames() as usize, ports).unwrap()
};
},
_ => {}
}
Control::Continue
}
}
pub fn render_plugin (state: &Plugin, buf: &mut Buffer, area: Rect)
-> Usually<Rect>
{
let Rect { x, y, height, .. } = area;
let mut width = 20u16;
match &state.plugin {
Some(PluginKind::LV2(LV2Plugin { port_list, instance, .. })) => {
let start = state.selected.saturating_sub((height as usize / 2).saturating_sub(1));
let end = start + height as usize - 2;
//draw_box(buf, Rect { x, y, width, height });
for i in start..end {
if let Some(port) = port_list.get(i) {
let value = if let Some(value) = instance.control_input(port.index) {
value
} else {
port.default_value
};
//let label = &format!("C·· M·· {:25} = {value:.03}", port.name);
let label = &format!("{:25} = {value:.03}", port.name);
width = width.max(label.len() as u16 + 4);
label.blit(buf, x + 2, y + 1 + i as u16 - start as u16, if i == state.selected {
Some(Style::default().green())
} else {
None
})?;
} else {
break
}
}
},
_ => {}
};
draw_header(state, buf, area.x, area.y, width)?;
Ok(Rect { width, ..area })
}
fn draw_header (state: &Plugin, buf: &mut Buffer, x: u16, y: u16, w: u16) -> Usually<Rect> {
let style = Style::default().gray();
let label1 = format!(" {}", state.name);
label1.blit(buf, x + 1, y, Some(style.white().bold()))?;
if let Some(ref path) = state.path {
let label2 = format!("{}", &path[..((w as usize - 10).min(path.len()))]);
label2.blit(buf, x + 2 + label1.len() as u16, y, Some(style.not_dim()))?;
}
Ok(Rect { x, y, width: w, height: 1 })
}
/// Key bindings for plugin device.
pub const KEYMAP_PLUGIN: &'static [KeyBinding<Plugin>] = keymap!(Plugin {
[Up, NONE, "/plugin/cursor_up", "move cursor up", |s: &mut Plugin|{
s.selected = s.selected.saturating_sub(1);
Ok(true)
}],
[Down, NONE, "/plugin/cursor_down", "move cursor down", |s: &mut Plugin|{
s.selected = (s.selected + 1).min(match &s.plugin {
Some(PluginKind::LV2(LV2Plugin { port_list, .. })) => port_list.len() - 1,
_ => unimplemented!()
});
Ok(true)
}],
[PageUp, NONE, "/plugin/cursor_page_up", "move cursor up", |s: &mut Plugin|{
s.selected = s.selected.saturating_sub(8);
Ok(true)
}],
[PageDown, NONE, "/plugin/cursor_page_down", "move cursor down", |s: &mut Plugin|{
s.selected = (s.selected + 10).min(match &s.plugin {
Some(PluginKind::LV2(LV2Plugin { port_list, .. })) => port_list.len() - 1,
_ => unimplemented!()
});
Ok(true)
}],
[Char(','), NONE, "/plugin/decrement", "decrement value", |s: &mut Plugin|{
match s.plugin.as_mut() {
Some(PluginKind::LV2(LV2Plugin { port_list, ref mut instance, .. })) => {
let index = port_list[s.selected].index;
if let Some(value) = instance.control_input(index) {
instance.set_control_input(index, value - 0.01);
}
},
_ => {}
}
Ok(true)
}],
[Char('.'), NONE, "/plugin/decrement", "increment value", |s: &mut Plugin|{
match s.plugin.as_mut() {
Some(PluginKind::LV2(LV2Plugin { port_list, ref mut instance, .. })) => {
let index = port_list[s.selected].index;
if let Some(value) = instance.control_input(index) {
instance.set_control_input(index, value + 0.01);
}
},
_ => {}
}
Ok(true)
}],
[Char('g'), NONE, "/plugin/gui_toggle", "toggle plugin UI", |s: &mut Plugin|{
match s.plugin {
Some(PluginKind::LV2(ref mut plugin)) => {
plugin.ui_thread = Some(run_lv2_ui(LV2PluginUI::new()?)?);
},
Some(_) => unreachable!(),
None => {}
}
Ok(true)
}],
});

View file

@ -0,0 +1,75 @@
use super::*;
use ::livi::{
World,
Instance,
Plugin as LiviPlugin,
Features,
FeaturesBuilder,
Port,
event::LV2AtomSequence,
};
use std::thread::JoinHandle;
/// A LV2 plugin.
pub struct LV2Plugin {
pub world: World,
pub instance: Instance,
pub plugin: LiviPlugin,
pub features: Arc<Features>,
pub port_list: Vec<Port>,
pub input_buffer: Vec<LV2AtomSequence>,
pub ui_thread: Option<JoinHandle<()>>,
}
impl LV2Plugin {
pub fn from_edn <'e> (args: &[Edn<'e>]) -> Usually<JackDevice> {
let mut name = String::new();
let mut path = String::new();
edn!(edn in args {
Edn::Map(map) => {
if let Some(Edn::Str(n)) = map.get(&Edn::Key(":name")) {
name = String::from(*n);
}
if let Some(Edn::Str(p)) = map.get(&Edn::Key(":path")) {
path = String::from(*p);
}
},
_ => panic!("unexpected in lv2 '{name}'"),
});
Plugin::new_lv2(&name, &path)
}
pub fn new (uri: &str) -> Usually<Self> {
// Get 1st plugin at URI
let world = World::with_load_bundle(&uri);
let features = FeaturesBuilder { min_block_length: 1, max_block_length: 65536 };
let features = world.build_features(features);
let mut plugin = None;
for p in world.iter_plugins() {
plugin = Some(p);
break
}
let plugin = plugin.unwrap();
let err = &format!("init {uri}");
// Instantiate
Ok(Self {
world,
instance: unsafe {
plugin
.instantiate(features.clone(), 48000.0)
.expect(&err)
},
port_list: {
let mut port_list = vec![];
for port in plugin.ports() {
port_list.push(port);
}
port_list
},
plugin,
features,
input_buffer: Vec::with_capacity(1024),
ui_thread: None
})
}
}

View file

@ -0,0 +1,76 @@
use crate::*;
use std::thread::{spawn, JoinHandle};
use ::winit::{
application::ApplicationHandler,
event::WindowEvent,
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
window::{Window, WindowId},
platform::x11::EventLoopBuilderExtX11
};
//pub struct LV2PluginUI {
//write: (),
//controller: (),
//widget: (),
//features: (),
//transfer: (),
//}
pub fn run_lv2_ui (mut ui: LV2PluginUI) -> Usually<JoinHandle<()>> {
Ok(spawn(move||{
let event_loop = EventLoop::builder().with_x11().with_any_thread(true).build().unwrap();
event_loop.set_control_flow(ControlFlow::Wait);
event_loop.run_app(&mut ui).unwrap()
}))
}
/// A LV2 plugin's X11 UI.
pub struct LV2PluginUI {
pub window: Option<Window>
}
impl LV2PluginUI {
pub fn new () -> Usually<Self> {
Ok(Self { window: None })
}
}
impl ApplicationHandler for LV2PluginUI {
fn resumed (&mut self, event_loop: &ActiveEventLoop) {
self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
}
fn window_event (&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
match event {
WindowEvent::CloseRequested => {
self.window.as_ref().unwrap().set_visible(false);
event_loop.exit();
},
WindowEvent::RedrawRequested => {
self.window.as_ref().unwrap().request_redraw();
}
_ => (),
}
}
}
fn lv2_ui_instantiate (kind: &str) {
//let host = Suil
}
pub fn jack_from_lv2 (name: &str, plugin: &::livi::Plugin) -> Usually<Jack> {
let counts = plugin.port_counts();
let mut jack = Jack::new(name)?;
for i in 0..counts.atom_sequence_inputs {
jack = jack.midi_in(&format!("midi-in-{i}"))
}
for i in 0..counts.atom_sequence_outputs {
jack = jack.midi_out(&format!("midi-out-{i}"));
}
for i in 0..counts.audio_inputs {
jack = jack.audio_in(&format!("audio-in-{i}"));
}
for i in 0..counts.audio_outputs {
jack = jack.audio_out(&format!("audio-out-{i}"));
}
Ok(jack)
}

View file

@ -0,0 +1,6 @@
//! Plugin host
include!("lib.rs");
pub fn main () -> Usually<()> {
tek_core::run(Arc::new(RwLock::new(crate::Plugin::new("")?)))?;
Ok(())
}

View file

@ -0,0 +1,13 @@
use crate::*;
impl ::vst::host::Host for Plugin {}
fn set_vst_plugin (host: &Arc<Mutex<Plugin>>, _path: &str) -> Usually<PluginKind> {
let mut loader = ::vst::host::PluginLoader::load(
&std::path::Path::new("/nix/store/ij3sz7nqg5l7v2dygdvzy3w6cj62bd6r-helm-0.9.0/lib/lxvst/helm.so"),
host.clone()
)?;
Ok(PluginKind::VST2 {
instance: loader.instance()?
})
}

View file

@ -0,0 +1 @@
//! TODO

View file

@ -0,0 +1,79 @@
use super::*;
/// A sound sample.
#[derive(Default, Debug)]
pub struct Sample {
pub name: String,
pub start: usize,
pub end: usize,
pub channels: Vec<Vec<f32>>,
pub rate: Option<usize>,
}
impl Sample {
pub fn from_edn <'e> (dir: &str, args: &[Edn<'e>]) -> Usually<(Option<u7>, Arc<RwLock<Self>>)> {
let mut name = String::new();
let mut file = String::new();
let mut midi = None;
let mut start = 0usize;
edn!(edn in args {
Edn::Map(map) => {
if let Some(Edn::Str(n)) = map.get(&Edn::Key(":name")) {
name = String::from(*n);
}
if let Some(Edn::Str(f)) = map.get(&Edn::Key(":file")) {
file = String::from(*f);
}
if let Some(Edn::Int(i)) = map.get(&Edn::Key(":start")) {
start = *i as usize;
}
if let Some(Edn::Int(m)) = map.get(&Edn::Key(":midi")) {
midi = Some(u7::from(*m as u8));
}
},
_ => panic!("unexpected in sample {name}"),
});
let (end, data) = read_sample_data(&format!("{dir}/{file}"))?;
Ok((midi, Arc::new(RwLock::new(Self::new(&name, start, end, data)))))
}
pub fn new (name: &str, start: usize, end: usize, channels: Vec<Vec<f32>>) -> Self {
Self { name: name.to_string(), start, end, channels, rate: None }
}
pub fn play (sample: &Arc<RwLock<Self>>, after: usize, velocity: &u7) -> Voice {
Voice {
sample: sample.clone(),
after,
position: sample.read().unwrap().start,
velocity: velocity.as_int() as f32 / 127.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()
)
}};
}
/// Read WAV from file
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))
}

View file

@ -0,0 +1,279 @@
use super::*;
use std::fs::File;
use symphonia::core::codecs::CODEC_TYPE_NULL;
use symphonia::core::errors::Error;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::probe::Hint;
use symphonia::core::audio::SampleBuffer;
use symphonia::default::get_codecs;
pub struct AddSampleModal {
exited: bool,
dir: PathBuf,
subdirs: Vec<OsString>,
files: Vec<OsString>,
cursor: usize,
offset: usize,
sample: Arc<RwLock<Sample>>,
voices: Arc<RwLock<Vec<Voice>>>,
_search: Option<String>,
}
exit!(AddSampleModal);
render!(AddSampleModal |self,buf,area|{
make_dim(buf);
let area = center_box(
area,
64.max(area.width.saturating_sub(8)),
20.max(area.width.saturating_sub(8)),
);
fill_fg(buf, area, Color::Reset);
fill_bg(buf, area, Nord::bg_lo(true, true));
fill_char(buf, area, ' ');
format!("{}", &self.dir.to_string_lossy())
.blit(buf, area.x+2, area.y+1, Some(Style::default().bold()))?;
"Select sample:"
.blit(buf, area.x+2, area.y+2, Some(Style::default().bold()))?;
for (i, (is_dir, name)) in self.subdirs.iter()
.map(|path|(true, path))
.chain(self.files.iter().map(|path|(false, path)))
.enumerate()
.skip(self.offset)
{
if i >= area.height as usize - 4 {
break
}
let t = if is_dir { "" } else { "" };
let line = format!("{t} {}", name.to_string_lossy());
let line = &line[..line.len().min(area.width as usize - 4)];
line.blit(buf, area.x + 2, area.y + 3 + i as u16, Some(if i == self.cursor {
Style::default().green()
} else {
Style::default().white()
}))?;
}
Lozenge(Style::default()).draw(buf, area)
});
handle!(AddSampleModal |self,e|{
if handle_keymap(self, e, KEYMAP_ADD_SAMPLE)? {
return Ok(true)
}
Ok(true)
});
impl AddSampleModal {
pub fn new (
sample: &Arc<RwLock<Sample>>,
voices: &Arc<RwLock<Vec<Voice>>>
) -> Usually<Self> {
let dir = std::env::current_dir()?;
let (subdirs, files) = scan(&dir)?;
Ok(Self {
exited: false,
dir,
subdirs,
files,
cursor: 0,
offset: 0,
sample: sample.clone(),
voices: voices.clone(),
_search: None
})
}
fn rescan (&mut self) -> Usually<()> {
scan(&self.dir).map(|(subdirs, files)|{
self.subdirs = subdirs;
self.files = files;
})
}
fn prev (&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
fn next (&mut self) {
self.cursor = self.cursor + 1;
}
fn try_preview (&mut self) -> Usually<()> {
if let Some(path) = self.cursor_file() {
if let Ok(sample) = Sample::from_file(&path) {
*self.sample.write().unwrap() = sample;
self.voices.write().unwrap().push(
Sample::play(&self.sample, 0, &u7::from(100u8))
);
}
//load_sample(&path)?;
//let src = std::fs::File::open(&path)?;
//let mss = MediaSourceStream::new(Box::new(src), Default::default());
//let mut hint = Hint::new();
//if let Some(ext) = path.extension() {
//hint.with_extension(&ext.to_string_lossy());
//}
//let meta_opts: MetadataOptions = Default::default();
//let fmt_opts: FormatOptions = Default::default();
//if let Ok(mut probed) = symphonia::default::get_probe()
//.format(&hint, mss, &fmt_opts, &meta_opts)
//{
//panic!("{:?}", probed.format.metadata());
//};
}
Ok(())
}
fn cursor_dir (&self) -> Option<PathBuf> {
if self.cursor < self.subdirs.len() {
Some(self.dir.join(&self.subdirs[self.cursor]))
} else {
None
}
}
fn cursor_file (&self) -> Option<PathBuf> {
if self.cursor < self.subdirs.len() {
return None
}
let index = self.cursor.saturating_sub(self.subdirs.len());
if index < self.files.len() {
Some(self.dir.join(&self.files[index]))
} else {
None
}
}
fn pick (&mut self) -> Usually<bool> {
if self.cursor == 0 {
if let Some(parent) = self.dir.parent() {
self.dir = parent.into();
self.rescan()?;
self.cursor = 0;
return Ok(false)
}
}
if let Some(dir) = self.cursor_dir() {
self.dir = dir;
self.rescan()?;
self.cursor = 0;
return Ok(false)
}
if let Some(path) = self.cursor_file() {
let (end, channels) = read_sample_data(&path.to_string_lossy())?;
let mut sample = self.sample.write().unwrap();
sample.name = path.file_name().unwrap().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 {
[Esc, NONE, "sampler/add/close", "close help dialog", |modal: &mut AddSampleModal|{
modal.exit();
Ok(true)
}],
[Up, NONE, "sampler/add/prev", "select previous entry", |modal: &mut AddSampleModal|{
modal.prev();
Ok(true)
}],
[Down, NONE, "sampler/add/next", "select next entry", |modal: &mut AddSampleModal|{
modal.next();
Ok(true)
}],
[Enter, NONE, "sampler/add/enter", "activate selected entry", |modal: &mut AddSampleModal|{
if modal.pick()? {
modal.exit();
}
Ok(true)
}],
[Char('p'), NONE, "sampler/add/preview", "preview selected entry", |modal: &mut AddSampleModal|{
modal.try_preview()?;
Ok(true)
}]
});
fn scan (dir: &PathBuf) -> Usually<(Vec<OsString>, Vec<OsString>)> {
let (mut subdirs, mut files) = 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)
});
subdirs.sort();
files.sort();
Ok((subdirs, files))
}
impl Sample {
fn from_file (path: &PathBuf) -> Usually<Self> {
let mut sample = Self::default();
sample.name = path.file_name().unwrap().to_string_lossy().into();
// Use file extension if present
let mut hint = Hint::new();
if let Some(ext) = path.extension() {
hint.with_extension(&ext.to_string_lossy());
}
let probed = symphonia::default::get_probe().format(
&hint,
MediaSourceStream::new(
Box::new(File::open(path)?),
Default::default(),
),
&Default::default(),
&Default::default()
)?;
let mut format = probed.format;
let mut decoder = get_codecs().make(
&format.tracks().iter()
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
.expect("no tracks found")
.codec_params,
&Default::default()
)?;
loop {
match format.next_packet() {
Ok(packet) => {
// Decode a packet
let decoded = match decoder.decode(&packet) {
Ok(decoded) => decoded,
Err(err) => { return Err(err.into()); }
};
// Determine sample rate
let spec = *decoded.spec();
if let Some(rate) = sample.rate {
if rate != spec.rate as usize {
panic!("sample rate changed");
}
} else {
sample.rate = Some(spec.rate as usize);
}
// Determine channel count
while sample.channels.len() < spec.channels.count() {
sample.channels.push(vec![]);
}
// Load sample
let mut samples = SampleBuffer::new(
decoded.frames() as u64,
spec
);
if samples.capacity() > 0 {
samples.copy_interleaved_ref(decoded);
for frame in samples.samples().chunks(spec.channels.count()) {
for (chan, frame) in frame.iter().enumerate() {
sample.channels[chan].push(*frame)
}
}
}
},
Err(Error::IoError(_)) => break decoder.last_decoded(),
Err(err) => return Err(err.into()),
};
};
sample.end = sample.channels.iter().fold(0, |l, c|l + c.len());
Ok(sample)
}
}

View file

@ -0,0 +1,226 @@
use crate::*;
/// The sampler plugin plays sounds.
pub struct Sampler {
pub name: String,
pub cursor: (usize, usize),
pub editing: Option<Arc<RwLock<Sample>>>,
pub mapped: BTreeMap<u7, Arc<RwLock<Sample>>>,
pub unmapped: Vec<Arc<RwLock<Sample>>>,
pub voices: Arc<RwLock<Vec<Voice>>>,
pub ports: JackPorts,
pub buffer: Vec<Vec<f32>>,
pub modal: Arc<Mutex<Option<Box<dyn Exit + Send>>>>,
pub output_gain: f32
}
process!(Sampler = Sampler::process);
handle!(Sampler |self, event| handle_keymap(self, event, KEYMAP_SAMPLER));
render!(Sampler |self, buf, area| {
let Rect { x, y, height, .. } = area;
let style = Style::default().gray();
let title = format!(" {} ({})", self.name, self.voices.read().unwrap().len());
title.blit(buf, x+1, y, Some(style.white().bold().not_dim()))?;
let mut width = title.len() + 2;
let mut y1 = 1;
let mut j = 0;
for (note, sample) in self.mapped.iter()
.map(|(note, sample)|(Some(note), sample))
.chain(self.unmapped.iter().map(|sample|(None, sample)))
{
if y1 >= height {
break
}
let active = j == self.cursor.0;
width = width.max(draw_sample(buf, x, y + y1, note, &*sample.read().unwrap(), active)?);
y1 = y1 + 1;
j = j + 1;
}
let height = ((2 + y1) as u16).min(height);
Ok(Rect { x, y, width: (width as u16).min(area.width), height })
});
fn draw_sample (
buf: &mut Buffer, x: u16, y: u16, note: Option<&u7>, sample: &Sample, focus: bool
) -> Usually<usize> {
let style = if focus { Style::default().green() } else { Style::default() };
if focus {
"🬴".blit(buf, x+1, y, Some(style.bold()))?;
}
let label1 = format!("{:3} {:12}",
note.map(|n|n.to_string()).unwrap_or(String::default()),
sample.name);
let label2 = format!("{:>6} {:>6} +0.0",
sample.start,
sample.end);
label1.blit(buf, x+2, y, Some(style.bold()))?;
label2.blit(buf, x+3+label1.len()as u16, y, Some(style))?;
Ok(label1.len() + label2.len() + 4)
}
/// Key bindings for sampler device.
pub const KEYMAP_SAMPLER: &'static [KeyBinding<Sampler>] = keymap!(Sampler {
[Up, NONE, "/sampler/cursor/up", "move cursor up", |state: &mut Sampler| {
state.cursor.0 = if state.cursor.0 == 0 {
state.mapped.len() + state.unmapped.len() - 1
} else {
state.cursor.0 - 1
};
Ok(true)
}],
[Down, NONE, "/sampler/cursor/down", "move cursor down", |state: &mut Sampler| {
state.cursor.0 = (state.cursor.0 + 1) % (state.mapped.len() + state.unmapped.len());
Ok(true)
}],
[Char('p'), NONE, "/sampler/play", "play current sample", |state: &mut Sampler| {
if let Some(sample) = state.sample() {
state.voices.write().unwrap().push(Sample::play(sample, 0, &100.into()));
}
Ok(true)
}],
[Char('a'), NONE, "/sampler/add", "add a new sample", |state: &mut Sampler| {
let sample = Arc::new(RwLock::new(Sample::new("", 0, 0, vec![])));
*state.modal.lock().unwrap() = Some(Exit::boxed(AddSampleModal::new(&sample, &state.voices)?));
state.unmapped.push(sample);
Ok(true)
}],
[Char('r'), NONE, "/sampler/replace", "replace selected sample", |state: &mut Sampler| {
if let Some(sample) = state.sample() {
*state.modal.lock().unwrap() = Some(Exit::boxed(AddSampleModal::new(&sample, &state.voices)?));
}
Ok(true)
}],
[Enter, NONE, "/sampler/edit", "edit selected sample", |state: &mut Sampler| {
if let Some(sample) = state.sample() {
state.editing = Some(sample.clone());
}
Ok(true)
}],
});
impl Sampler {
pub fn from_edn <'e> (args: &[Edn<'e>]) -> Usually<JackDevice> {
let mut name = String::new();
let mut dir = String::new();
let mut samples = BTreeMap::new();
edn!(edn in args {
Edn::Map(map) => {
if let Some(Edn::Str(n)) = map.get(&Edn::Key(":name")) {
name = String::from(*n);
}
if let Some(Edn::Str(n)) = map.get(&Edn::Key(":dir")) {
dir = String::from(*n);
}
},
Edn::List(args) => match args.get(0) {
Some(Edn::Symbol("sample")) => {
let (midi, sample) = Sample::from_edn(&dir, &args[1..])?;
if let Some(midi) = midi {
samples.insert(midi, sample);
} else {
panic!("sample without midi binding: {}", sample.read().unwrap().name);
}
},
_ => panic!("unexpected in sampler {name}: {args:?}")
},
_ => panic!("unexpected in sampler {name}: {edn:?}")
});
Self::new(&name, Some(samples))
}
pub fn new (name: &str, mapped: Option<BTreeMap<u7, Arc<RwLock<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: Arc::new(RwLock::new(vec![])),
ports,
buffer: vec![vec![0.0;16384];2],
output_gain: 0.5,
modal: Default::default()
}))
}
/// Immutable reference to sample at cursor.
pub fn sample (&self) -> Option<&Arc<RwLock<Sample>>> {
for (i, sample) in self.mapped.values().enumerate() {
if i == self.cursor.0 {
return Some(sample)
}
}
for (i, sample) in self.unmapped.iter().enumerate() {
if i + self.mapped.len() == 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
}
/// Create [Voice]s from [Sample]s in response to MIDI input.
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.write().unwrap().push(Sample::play(sample, time as usize, vel));
}
}
}
}
}
/// Zero the output buffer.
fn clear_output_buffer (&mut self) {
for buffer in self.buffer.iter_mut() {
buffer.fill(0.0);
}
}
/// Mix all currently playing samples into the output.
fn process_audio_out (&mut self, scope: &ProcessScope) {
let channel_count = self.buffer.len();
self.voices.write().unwrap().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() {
// Averaging mixer:
//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);
}
}
}
}

View file

@ -0,0 +1,7 @@
use crate::*;
impl Sampler {
}
impl Sample {
}

View file

@ -0,0 +1,6 @@
//! Sample player
include!("lib.rs");
pub fn main () -> Usually<()> {
tek_core::run(Arc::new(RwLock::new(crate::Sampler::new("", None)?)))?;
Ok(())
}

View file

@ -0,0 +1,29 @@
use super::*;
/// A currently playing instance of a sample.
pub struct Voice {
pub sample: Arc<RwLock<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])
}
let sample = self.sample.read().unwrap();
if self.position < sample.end {
let position = self.position;
self.position = self.position + 1;
return sample.channels[0].get(position).map(|_amplitude|[
sample.channels[0][position] * self.velocity,
sample.channels[0][position] * self.velocity,
])
}
None
}
}