mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-07 12:16:42 +01:00
wip: refactor into fewer crates
This commit is contained in:
parent
c367a0444e
commit
77703d83a5
105 changed files with 64 additions and 131 deletions
0
crates/device/src/lib.rs
Normal file
0
crates/device/src/lib.rs
Normal file
8
crates/device/src/plugin.rs
Normal file
8
crates/device/src/plugin.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
mod plugin; pub use self::plugin::*;
|
||||
mod lv2; pub use self::lv2::*;
|
||||
pub(crate) use std::cmp::Ord;
|
||||
pub(crate) use std::fmt::{Debug, Formatter};
|
||||
pub(crate) use std::sync::{Arc, RwLock};
|
||||
pub(crate) use std::thread::JoinHandle;
|
||||
pub(crate) use ::tek_jack::{*, jack::*};
|
||||
pub(crate) use ::tengri::{output::*, tui::{*, ratatui::prelude::*}};
|
||||
40
crates/device/src/plugin/lv2.rs
Normal file
40
crates/device/src/plugin/lv2.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
use crate::*;
|
||||
|
||||
/// A LV2 plugin.
|
||||
#[derive(Debug)]
|
||||
pub struct LV2Plugin {
|
||||
pub world: livi::World,
|
||||
pub instance: livi::Instance,
|
||||
pub plugin: livi::Plugin,
|
||||
pub features: Arc<livi::Features>,
|
||||
pub port_list: Vec<livi::Port>,
|
||||
pub input_buffer: Vec<livi::event::LV2AtomSequence>,
|
||||
pub ui_thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl LV2Plugin {
|
||||
const INPUT_BUFFER: usize = 1024;
|
||||
pub fn new (uri: &str) -> Usually<Self> {
|
||||
let world = livi::World::with_load_bundle(&uri);
|
||||
let features = world
|
||||
.build_features(livi::FeaturesBuilder {
|
||||
min_block_length: 1,
|
||||
max_block_length: 65536,
|
||||
});
|
||||
let plugin = world.iter_plugins().nth(0)
|
||||
.unwrap_or_else(||panic!("plugin not found: {uri}"));
|
||||
Ok(Self {
|
||||
instance: unsafe {
|
||||
plugin
|
||||
.instantiate(features.clone(), 48000.0)
|
||||
.expect(&format!("instantiate failed: {uri}"))
|
||||
},
|
||||
port_list: plugin.ports().collect::<Vec<_>>(),
|
||||
input_buffer: Vec::with_capacity(Self::INPUT_BUFFER),
|
||||
ui_thread: None,
|
||||
world,
|
||||
features,
|
||||
plugin,
|
||||
})
|
||||
}
|
||||
}
|
||||
59
crates/device/src/plugin/lv2_gui.rs
Normal file
59
crates/device/src/plugin/lv2_gui.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
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
|
||||
}
|
||||
|
||||
47
crates/device/src/plugin/lv2_tui.rs
Normal file
47
crates/device/src/plugin/lv2_tui.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
|
||||
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 {
|
||||
const INPUT_BUFFER: usize = 1024;
|
||||
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;
|
||||
if let Some(p) = world.iter_plugins().next() { plugin = Some(p); }
|
||||
let plugin = plugin.expect("plugin not found");
|
||||
let err = &format!("init {uri}");
|
||||
let instance = unsafe { plugin.instantiate(features.clone(), 48000.0).expect(&err) };
|
||||
let mut port_list = vec![];
|
||||
for port in plugin.ports() {
|
||||
port_list.push(port);
|
||||
}
|
||||
let input_buffer = Vec::with_capacity(Self::INPUT_BUFFER);
|
||||
// Instantiate
|
||||
Ok(Self {
|
||||
world, instance, port_list, plugin, features, input_buffer, ui_thread: None
|
||||
})
|
||||
}
|
||||
}
|
||||
275
crates/device/src/plugin/plugin.rs
Normal file
275
crates/device/src/plugin/plugin.rs
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
use crate::*;
|
||||
|
||||
/// A plugin device.
|
||||
#[derive(Debug)]
|
||||
pub struct Plugin {
|
||||
/// JACK client handle (needs to not be dropped for standalone mode to work).
|
||||
pub jack: Jack,
|
||||
pub name: Arc<str>,
|
||||
pub path: Option<Arc<str>>,
|
||||
pub plugin: Option<PluginKind>,
|
||||
pub selected: usize,
|
||||
pub mapping: bool,
|
||||
pub midi_ins: Vec<Port<MidiIn>>,
|
||||
pub midi_outs: Vec<Port<MidiOut>>,
|
||||
pub audio_ins: Vec<Port<AudioIn>>,
|
||||
pub audio_outs: Vec<Port<AudioOut>>,
|
||||
}
|
||||
|
||||
/// Supported plugin formats.
|
||||
#[derive(Default)]
|
||||
pub enum PluginKind {
|
||||
#[default] None,
|
||||
LV2(LV2Plugin),
|
||||
VST2 { instance: () /*::vst::host::PluginInstance*/ },
|
||||
VST3,
|
||||
}
|
||||
|
||||
impl Debug for PluginKind {
|
||||
fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
write!(f, "{}", match self {
|
||||
Self::None => "(none)",
|
||||
Self::LV2(_) => "LV2",
|
||||
Self::VST2{..} => "VST2",
|
||||
Self::VST3 => "VST3",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Plugin {
|
||||
pub fn new_lv2 (
|
||||
jack: &Jack,
|
||||
name: &str,
|
||||
path: &str,
|
||||
) -> Usually<Self> {
|
||||
Ok(Self {
|
||||
jack: jack.clone(),
|
||||
name: name.into(),
|
||||
path: Some(String::from(path).into()),
|
||||
plugin: Some(PluginKind::LV2(LV2Plugin::new(path)?)),
|
||||
selected: 0,
|
||||
mapping: false,
|
||||
midi_ins: vec![],
|
||||
midi_outs: vec![],
|
||||
audio_ins: vec![],
|
||||
audio_outs: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PluginAudio(Arc<RwLock<Plugin>>);
|
||||
from!(|model: &Arc<RwLock<Plugin>>| PluginAudio = Self(model.clone()));
|
||||
audio!(|self: PluginAudio, _client, scope|{
|
||||
let state = &mut*self.0.write().unwrap();
|
||||
match state.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 state.midi_ins.iter() {
|
||||
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 state.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(state.audio_ins.iter().map(|o|o.as_slice(scope)))
|
||||
.with_audio_outputs(state.audio_outs.iter_mut().map(|o|o.as_mut_slice(scope)));
|
||||
unsafe {
|
||||
instance.run(scope.n_frames() as usize, ports).unwrap()
|
||||
};
|
||||
},
|
||||
_ => todo!("only lv2 is supported")
|
||||
}
|
||||
Control::Continue
|
||||
});
|
||||
|
||||
//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)
|
||||
//}
|
||||
|
||||
impl Plugin {
|
||||
/// Create a plugin host device.
|
||||
pub fn new (
|
||||
jack: &Jack,
|
||||
name: &str,
|
||||
) -> Usually<Self> {
|
||||
Ok(Self {
|
||||
//_engine: Default::default(),
|
||||
jack: jack.clone(),
|
||||
name: name.into(),
|
||||
path: None,
|
||||
plugin: None,
|
||||
selected: 0,
|
||||
mapping: false,
|
||||
audio_ins: vec![],
|
||||
audio_outs: vec![],
|
||||
midi_ins: vec![],
|
||||
midi_outs: vec![],
|
||||
//ports: JackPorts::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Content<TuiOut> for Plugin {
|
||||
fn render (&self, to: &mut TuiOut) {
|
||||
let area = to.area();
|
||||
let [x, y, _, height] = area;
|
||||
let mut width = 20u16;
|
||||
match &self.plugin {
|
||||
Some(PluginKind::LV2(LV2Plugin { port_list, instance, .. })) => {
|
||||
let start = self.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);
|
||||
let style = if i == self.selected {
|
||||
Some(Style::default().green())
|
||||
} else {
|
||||
None
|
||||
} ;
|
||||
to.blit(&label, x + 2, y + 1 + i as u16 - start as u16, style);
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
};
|
||||
draw_header(self, to, x, y, width);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_header (state: &Plugin, to: &mut TuiOut, x: u16, y: u16, w: u16) {
|
||||
let style = Style::default().gray();
|
||||
let label1 = format!(" {}", state.name);
|
||||
to.blit(&label1, 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()))]);
|
||||
to.blit(&label2, x + 2 + label1.len() as u16, y, Some(style.not_dim()));
|
||||
}
|
||||
//Ok(Rect { x, y, width: w, height: 1 })
|
||||
}
|
||||
|
||||
//handle!(TuiIn: |self:Plugin, from|{
|
||||
//match from.event() {
|
||||
//kpat!(KeyCode::Up) => {
|
||||
//self.selected = self.selected.saturating_sub(1);
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//kpat!(KeyCode::Down) => {
|
||||
//self.selected = (self.selected + 1).min(match &self.plugin {
|
||||
//Some(PluginKind::LV2(LV2Plugin { port_list, .. })) => port_list.len() - 1,
|
||||
//_ => unimplemented!()
|
||||
//});
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//kpat!(KeyCode::PageUp) => {
|
||||
//self.selected = self.selected.saturating_sub(8);
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//kpat!(KeyCode::PageDown) => {
|
||||
//self.selected = (self.selected + 10).min(match &self.plugin {
|
||||
//Some(PluginKind::LV2(LV2Plugin { port_list, .. })) => port_list.len() - 1,
|
||||
//_ => unimplemented!()
|
||||
//});
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//kpat!(KeyCode::Char(',')) => {
|
||||
//match self.plugin.as_mut() {
|
||||
//Some(PluginKind::LV2(LV2Plugin { port_list, ref mut instance, .. })) => {
|
||||
//let index = port_list[self.selected].index;
|
||||
//if let Some(value) = instance.control_input(index) {
|
||||
//instance.set_control_input(index, value - 0.01);
|
||||
//}
|
||||
//},
|
||||
//_ => {}
|
||||
//}
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//kpat!(KeyCode::Char('.')) => {
|
||||
//match self.plugin.as_mut() {
|
||||
//Some(PluginKind::LV2(LV2Plugin { port_list, ref mut instance, .. })) => {
|
||||
//let index = port_list[self.selected].index;
|
||||
//if let Some(value) = instance.control_input(index) {
|
||||
//instance.set_control_input(index, value + 0.01);
|
||||
//}
|
||||
//},
|
||||
//_ => {}
|
||||
//}
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//kpat!(KeyCode::Char('g')) => {
|
||||
//match self.plugin {
|
||||
////Some(PluginKind::LV2(ref mut plugin)) => {
|
||||
////plugin.ui_thread = Some(run_lv2_ui(LV2PluginUI::new()?)?);
|
||||
////},
|
||||
//Some(_) => unreachable!(),
|
||||
//None => {}
|
||||
//}
|
||||
//Ok(Some(true))
|
||||
//},
|
||||
//_ => Ok(None)
|
||||
//}
|
||||
//});
|
||||
|
||||
//from_atom!("plugin/lv2" => |jack: &Jack, args| -> Plugin {
|
||||
//let mut name = String::new();
|
||||
//let mut path = String::new();
|
||||
//atom!(atom in args {
|
||||
//Atom::Map(map) => {
|
||||
//if let Some(Atom::Str(n)) = map.get(&Atom::Key(":name")) {
|
||||
//name = String::from(*n);
|
||||
//}
|
||||
//if let Some(Atom::Str(p)) = map.get(&Atom::Key(":path")) {
|
||||
//path = String::from(*p);
|
||||
//}
|
||||
//},
|
||||
//_ => panic!("unexpected in lv2 '{name}'"),
|
||||
//});
|
||||
//Plugin::new_lv2(jack, &name, &path)
|
||||
//});
|
||||
14
crates/device/src/plugin/vst2_tui.rs
Normal file
14
crates/device/src/plugin/vst2_tui.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
use crate::*;
|
||||
|
||||
impl<E: Engine> ::vst::host::Host for Plugin<E> {}
|
||||
|
||||
fn set_vst_plugin <E: Engine> (host: &Arc<Mutex<Plugin<E>>>, _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()?
|
||||
})
|
||||
}
|
||||
|
||||
2
crates/device/src/plugin/vst3_tui.rs
Normal file
2
crates/device/src/plugin/vst3_tui.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! TODO
|
||||
|
||||
36
crates/device/src/sampler.rs
Normal file
36
crates/device/src/sampler.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
#![feature(let_chains)]
|
||||
|
||||
pub(crate) use ::tek_jack::{*, jack::*};
|
||||
pub(crate) use ::tek_midi::{*, midly::{*, live::*, num::*}};
|
||||
pub(crate) use ::tengri::{dsl::*, input::*, output::*, tui::{*, ratatui::prelude::*}};
|
||||
pub(crate) use std::sync::{Arc, RwLock, atomic::{AtomicUsize, Ordering::Relaxed}};
|
||||
pub(crate) use std::fs::File;
|
||||
pub(crate) use std::path::PathBuf;
|
||||
pub(crate) use std::error::Error;
|
||||
pub(crate) use std::ffi::OsString;
|
||||
pub(crate) use symphonia::{
|
||||
core::{
|
||||
formats::Packet,
|
||||
codecs::{Decoder, CODEC_TYPE_NULL},
|
||||
//errors::Error as SymphoniaError,
|
||||
io::MediaSourceStream,
|
||||
probe::Hint,
|
||||
audio::SampleBuffer,
|
||||
},
|
||||
default::get_codecs,
|
||||
};
|
||||
pub(crate) use ratatui::{prelude::Rect, widgets::{Widget, canvas::{Canvas, Line}}};
|
||||
|
||||
mod sampler_api; pub use self::sampler_api::*;
|
||||
mod sampler_audio; pub use self::sampler_audio::*;
|
||||
mod sampler_browse; pub use self::sampler_browse::*;
|
||||
mod sampler_midi; pub use self::sampler_midi::*;
|
||||
mod sampler_model; pub use self::sampler_model::*;
|
||||
|
||||
mod sampler_data;
|
||||
mod sampler_view;
|
||||
|
||||
#[cfg(test)] #[test] fn test_sampler () {
|
||||
// TODO!
|
||||
let sample = Sample::new("test", 0, 0, vec![]);
|
||||
}
|
||||
72
crates/device/src/sampler/sampler_api.rs
Normal file
72
crates/device/src/sampler/sampler_api.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
use crate::*;
|
||||
|
||||
expose!([self: Sampler]
|
||||
([Arc<str>])
|
||||
([MaybeSample])
|
||||
([PathBuf])
|
||||
([f32])
|
||||
([u7]
|
||||
(":pitch" (self.note_pos() as u8).into()) // TODO
|
||||
(":sample" (self.note_pos() as u8).into()))
|
||||
([usize]
|
||||
(":sample-up" self.note_pos().min(119) + 8)
|
||||
(":sample-down" self.note_pos().max(8) - 8)
|
||||
(":sample-left" self.note_pos().min(126) + 1)
|
||||
(":sample-right" self.note_pos().max(1) - 1)));
|
||||
|
||||
impose!([state: Sampler]
|
||||
(FileBrowserCommand:
|
||||
("begin" [] Some(Self::Begin))
|
||||
("cancel" [] Some(Self::Cancel))
|
||||
("confirm" [] Some(Self::Confirm))
|
||||
("select" [i: usize] Some(Self::Select(i.expect("no index"))))
|
||||
("chdir" [p: PathBuf] Some(Self::Chdir(p.expect("no path"))))
|
||||
("filter" [f: Arc<str>] Some(Self::Filter(f.expect("no filter")))))
|
||||
(SamplerCommand:
|
||||
("import" [,..a]
|
||||
FileBrowserCommand::try_from_expr(state, a).map(Self::Import))
|
||||
("select" [i: usize]
|
||||
Some(Self::Select(i.expect("no index"))))
|
||||
("record/begin" [i: u7]
|
||||
Some(Self::RecordBegin(i.expect("no index"))))
|
||||
("record/cancel" []
|
||||
Some(Self::RecordCancel))
|
||||
("record/finish" []
|
||||
Some(Self::RecordFinish))
|
||||
("set/sample" [i: u7, s: MaybeSample]
|
||||
Some(Self::SetSample(i.expect("no index"), s.expect("no sampler"))))
|
||||
("set/start" [i: u7, s: usize]
|
||||
Some(Self::SetStart(i.expect("no index"), s.expect("no start"))))
|
||||
("set/gain" [i: u7, g: f32]
|
||||
Some(Self::SetGain(i.expect("no index"), g.expect("no gain"))))
|
||||
("note/on" [p: u7, v: u7]
|
||||
Some(Self::NoteOn(p.expect("no pitch"), v.expect("no velocity"))))
|
||||
("note/off" [p: u7]
|
||||
Some(Self::NoteOff(p.expect("no pitch"))))));
|
||||
|
||||
macro_rules! cmd { ($cmd:expr) => {{ $cmd; None }}; }
|
||||
macro_rules! cmd_todo { ($msg:literal) => {{ println!($msg); None }}; }
|
||||
|
||||
defcom!([self, state: Sampler]
|
||||
(SamplerCommand
|
||||
(Select [i: usize] Some(Self::Select(state.set_note_pos(i))))
|
||||
(RecordBegin [p: u7] cmd!(state.begin_recording(p.as_int() as usize)))
|
||||
(RecordCancel [] cmd!(state.cancel_recording()))
|
||||
(RecordFinish [] cmd!(state.finish_recording()))
|
||||
(SetStart [p: u7, frame: usize] cmd_todo!("\n\rtodo: {self:?}"))
|
||||
(SetGain [p: u7, gain: f32] cmd_todo!("\n\rtodo: {self:?}"))
|
||||
(NoteOn [p: u7, velocity: u7] cmd_todo!("\n\rtodo: {self:?}"))
|
||||
(NoteOff [p: u7] cmd_todo!("\n\rtodo: {self:?}"))
|
||||
(SetSample [p: u7, s: MaybeSample] Some(Self::SetSample(p, state.set_sample(p, s))))
|
||||
(Import [c: FileBrowserCommand] match c {
|
||||
FileBrowserCommand::Begin => {
|
||||
//let voices = &state.state.voices;
|
||||
//let sample = Arc::new(RwLock::new(Sample::new("", 0, 0, vec![])));
|
||||
state.mode = Some(SamplerMode::Import(0, FileBrowser::new(None)?));
|
||||
None
|
||||
},
|
||||
_ => {
|
||||
println!("\n\rtodo: import: filebrowser: {c:?}");
|
||||
None
|
||||
}
|
||||
})));
|
||||
107
crates/device/src/sampler/sampler_audio.rs
Normal file
107
crates/device/src/sampler/sampler_audio.rs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
use crate::*;
|
||||
|
||||
pub struct SamplerAudio<'a>(pub &'a mut Sampler);
|
||||
|
||||
audio!(|self: SamplerAudio<'a>, _client, scope|{
|
||||
self.0.process_midi_in(scope);
|
||||
self.0.clear_output_buffer();
|
||||
self.0.process_audio_out(scope);
|
||||
self.0.write_output_buffer(scope);
|
||||
self.0.process_audio_in(scope);
|
||||
Control::Continue
|
||||
});
|
||||
|
||||
impl Sampler {
|
||||
|
||||
pub fn process_audio_in (&mut self, scope: &ProcessScope) {
|
||||
let Sampler { audio_ins, input_meter, recording, .. } = self;
|
||||
if audio_ins.len() != input_meter.len() {
|
||||
*input_meter = vec![0.0;audio_ins.len()];
|
||||
}
|
||||
if let Some((_, sample)) = recording {
|
||||
let mut sample = sample.write().unwrap();
|
||||
if sample.channels.len() != audio_ins.len() {
|
||||
panic!("channel count mismatch");
|
||||
}
|
||||
let iterator = audio_ins.iter().zip(input_meter).zip(sample.channels.iter_mut());
|
||||
let mut length = 0;
|
||||
for ((input, meter), channel) in iterator {
|
||||
let slice = input.port().as_slice(scope);
|
||||
length = length.max(slice.len());
|
||||
let total: f32 = slice.iter().map(|x|x.abs()).sum();
|
||||
let count = slice.len() as f32;
|
||||
*meter = 10. * (total / count).log10();
|
||||
channel.extend_from_slice(slice);
|
||||
}
|
||||
sample.end += length;
|
||||
} else {
|
||||
for (input, meter) in audio_ins.iter().zip(input_meter) {
|
||||
let slice = input.port().as_slice(scope);
|
||||
let total: f32 = slice.iter().map(|x|x.abs()).sum();
|
||||
let count = slice.len() as f32;
|
||||
*meter = 10. * (total / count).log10();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero the output buffer.
|
||||
pub 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.
|
||||
pub fn process_audio_out (&mut self, scope: &ProcessScope) {
|
||||
let Sampler { ref mut buffer, voices, output_gain, .. } = self;
|
||||
let channel_count = buffer.len();
|
||||
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
|
||||
//);
|
||||
buffer[channel % channel_count][index] += sample * *output_gain;
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// Write output buffer to output ports.
|
||||
pub fn write_output_buffer (&mut self, scope: &ProcessScope) {
|
||||
let Sampler { ref mut audio_outs, buffer, .. } = self;
|
||||
for (i, port) in audio_outs.iter_mut().enumerate() {
|
||||
let buffer = &buffer[i];
|
||||
for (i, value) in port.port_mut().as_mut_slice(scope).iter_mut().enumerate() {
|
||||
*value = *buffer.get(i).unwrap_or(&0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Iterator for Voice {
|
||||
type Item = [f32;2];
|
||||
fn next (&mut self) -> Option<Self::Item> {
|
||||
if self.after > 0 {
|
||||
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 += 1;
|
||||
return sample.channels[0].get(position).map(|_amplitude|[
|
||||
sample.channels[0][position] * self.velocity * sample.gain,
|
||||
sample.channels[0][position] * self.velocity * sample.gain,
|
||||
])
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
181
crates/device/src/sampler/sampler_browse.rs
Normal file
181
crates/device/src/sampler/sampler_browse.rs
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
use crate::*;
|
||||
|
||||
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>,
|
||||
}
|
||||
|
||||
impl AddSampleModal {
|
||||
fn exited (&self) -> bool {
|
||||
self.exited
|
||||
}
|
||||
fn exit (&mut self) {
|
||||
self.exited = 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)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_sample_data (_: &str) -> Usually<(usize, Vec<Vec<f32>>)> {
|
||||
todo!();
|
||||
}
|
||||
|
||||
fn scan (dir: &PathBuf) -> Usually<(Vec<OsString>, Vec<OsString>)> {
|
||||
let (mut subdirs, mut files) = std::fs::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 Content<TuiOut> for AddSampleModal {
|
||||
fn render (&self, to: &mut TuiOut) {
|
||||
todo!()
|
||||
//let area = to.area();
|
||||
//to.make_dim();
|
||||
//let area = center_box(
|
||||
//area,
|
||||
//64.max(area.w().saturating_sub(8)),
|
||||
//20.max(area.w().saturating_sub(8)),
|
||||
//);
|
||||
//to.fill_fg(area, Color::Reset);
|
||||
//to.fill_bg(area, Nord::bg_lo(true, true));
|
||||
//to.fill_char(area, ' ');
|
||||
//to.blit(&format!("{}", &self.dir.to_string_lossy()), area.x()+2, area.y()+1, Some(Style::default().bold()))?;
|
||||
//to.blit(&"Select sample:", 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.h() 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.w() as usize - 4)];
|
||||
//to.blit(&line, 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(to)
|
||||
}
|
||||
}
|
||||
87
crates/device/src/sampler/sampler_data.rs
Normal file
87
crates/device/src/sampler/sampler_data.rs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
use crate::*;
|
||||
|
||||
impl Sample {
|
||||
/// Read WAV from file
|
||||
pub fn read_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 fn from_file (path: &PathBuf) -> Usually<Self> {
|
||||
let name = path.file_name().unwrap().to_string_lossy().into();
|
||||
let mut sample = Self { name, ..Default::default() };
|
||||
// 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 params = &format.tracks().iter()
|
||||
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.expect("no tracks found")
|
||||
.codec_params;
|
||||
let mut decoder = get_codecs().make(params, &Default::default())?;
|
||||
loop {
|
||||
match format.next_packet() {
|
||||
Ok(packet) => sample.decode_packet(&mut decoder, packet)?,
|
||||
Err(symphonia::core::errors::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)
|
||||
}
|
||||
fn decode_packet (
|
||||
&mut self, decoder: &mut Box<dyn Decoder>, packet: Packet
|
||||
) -> Usually<()> {
|
||||
// Decode a packet
|
||||
let decoded = decoder
|
||||
.decode(&packet)
|
||||
.map_err(|e|Box::<dyn crate::Error>::from(e))?;
|
||||
// Determine sample rate
|
||||
let spec = *decoded.spec();
|
||||
if let Some(rate) = self.rate {
|
||||
if rate != spec.rate as usize {
|
||||
panic!("sample rate changed");
|
||||
}
|
||||
} else {
|
||||
self.rate = Some(spec.rate as usize);
|
||||
}
|
||||
// Determine channel count
|
||||
while self.channels.len() < spec.channels.count() {
|
||||
self.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() {
|
||||
self.channels[chan].push(*frame)
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
54
crates/device/src/sampler/sampler_midi.rs
Normal file
54
crates/device/src/sampler/sampler_midi.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
use crate::*;
|
||||
|
||||
pub type MidiSample = (Option<u7>, Arc<RwLock<crate::Sample>>);
|
||||
|
||||
impl Sampler {
|
||||
|
||||
/// Create [Voice]s from [Sample]s in response to MIDI input.
|
||||
pub fn process_midi_in (&mut self, scope: &ProcessScope) {
|
||||
let Sampler { midi_in, mapped, voices, .. } = self;
|
||||
if let Some(ref midi_in) = midi_in {
|
||||
for RawMidi { time, bytes } in midi_in.port().iter(scope) {
|
||||
if let LiveEvent::Midi { message, .. } = LiveEvent::parse(bytes).unwrap() {
|
||||
match message {
|
||||
MidiMessage::NoteOn { ref key, ref vel } => {
|
||||
if let Some(ref sample) = mapped[key.as_int() as usize] {
|
||||
voices.write().unwrap().push(Sample::play(sample, time as usize, vel));
|
||||
}
|
||||
},
|
||||
MidiMessage::Controller { controller, value } => {
|
||||
// TODO
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Sample {
|
||||
pub fn handle_cc (&mut self, controller: u7, value: u7) {
|
||||
let percentage = value.as_int() as f64 / 127.;
|
||||
match controller.as_int() {
|
||||
20 => {
|
||||
self.start = (percentage * self.end as f64) as usize;
|
||||
},
|
||||
21 => {
|
||||
let length = self.channels[0].len();
|
||||
self.end = length.min(
|
||||
self.start + (percentage * (length as f64 - self.start as f64)) as usize
|
||||
);
|
||||
},
|
||||
22 => { /*attack*/ },
|
||||
23 => { /*decay*/ },
|
||||
24 => {
|
||||
self.gain = percentage as f32 * 2.0;
|
||||
},
|
||||
26 => { /* pan */ }
|
||||
25 => { /* pitch */ }
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
191
crates/device/src/sampler/sampler_model.rs
Normal file
191
crates/device/src/sampler/sampler_model.rs
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
use crate::*;
|
||||
|
||||
pub type MaybeSample = Option<Arc<RwLock<Sample>>>;
|
||||
|
||||
/// The sampler device plays sounds in response to MIDI notes.
|
||||
#[derive(Debug)]
|
||||
pub struct Sampler {
|
||||
pub name: String,
|
||||
pub mapped: [MaybeSample;128],
|
||||
pub recording: Option<(usize, Arc<RwLock<Sample>>)>,
|
||||
pub unmapped: Vec<Arc<RwLock<Sample>>>,
|
||||
pub voices: Arc<RwLock<Vec<Voice>>>,
|
||||
pub midi_in: Option<JackMidiIn>,
|
||||
pub audio_ins: Vec<JackAudioIn>,
|
||||
pub input_meter: Vec<f32>,
|
||||
pub audio_outs: Vec<JackAudioOut>,
|
||||
pub buffer: Vec<Vec<f32>>,
|
||||
pub output_gain: f32,
|
||||
pub editing: MaybeSample,
|
||||
pub mode: Option<SamplerMode>,
|
||||
/// Size of actual notes area
|
||||
pub size: Measure<TuiOut>,
|
||||
/// Lowest note displayed
|
||||
pub note_lo: AtomicUsize,
|
||||
/// Selected note
|
||||
pub note_pt: AtomicUsize,
|
||||
/// Selected note as row/col
|
||||
pub cursor: (AtomicUsize, AtomicUsize),
|
||||
pub color: ItemTheme
|
||||
}
|
||||
|
||||
impl Default for Sampler {
|
||||
fn default () -> Self {
|
||||
Self {
|
||||
midi_in: None,
|
||||
audio_ins: vec![],
|
||||
input_meter: vec![0.0;2],
|
||||
audio_outs: vec![],
|
||||
name: "tek_sampler".to_string(),
|
||||
mapped: [const { None };128],
|
||||
unmapped: vec![],
|
||||
voices: Arc::new(RwLock::new(vec![])),
|
||||
buffer: vec![vec![0.0;16384];2],
|
||||
output_gain: 1.,
|
||||
recording: None,
|
||||
mode: None,
|
||||
editing: None,
|
||||
size: Default::default(),
|
||||
note_lo: 0.into(),
|
||||
note_pt: 0.into(),
|
||||
cursor: (0.into(), 0.into()),
|
||||
color: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sampler {
|
||||
pub fn new (
|
||||
jack: &Jack,
|
||||
name: impl AsRef<str>,
|
||||
midi_from: &[PortConnect],
|
||||
audio_from: &[&[PortConnect];2],
|
||||
audio_to: &[&[PortConnect];2],
|
||||
) -> Usually<Self> {
|
||||
let name = name.as_ref();
|
||||
Ok(Self {
|
||||
midi_in: Some(JackMidiIn::new(jack, format!("M/{name}"), midi_from)?),
|
||||
audio_ins: vec![
|
||||
JackAudioIn::new(jack, &format!("L/{name}"), audio_from[0])?,
|
||||
JackAudioIn::new(jack, &format!("R/{name}"), audio_from[1])?,
|
||||
],
|
||||
audio_outs: vec![
|
||||
JackAudioOut::new(jack, &format!("{name}/L"), audio_to[0])?,
|
||||
JackAudioOut::new(jack, &format!("{name}/R"), audio_to[1])?,
|
||||
],
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
pub fn cancel_recording (&mut self) {
|
||||
self.recording = None;
|
||||
}
|
||||
pub fn begin_recording (&mut self, index: usize) {
|
||||
self.recording = Some((
|
||||
index,
|
||||
Arc::new(RwLock::new(Sample::new("Sample", 0, 0, vec![vec![];self.audio_ins.len()])))
|
||||
));
|
||||
}
|
||||
pub fn finish_recording (&mut self) -> MaybeSample {
|
||||
let recording = self.recording.take();
|
||||
if let Some((index, sample)) = recording {
|
||||
let old = self.mapped[index].clone();
|
||||
self.mapped[index] = Some(sample);
|
||||
old
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// Immutable reference to sample at cursor.
|
||||
pub fn sample (&self) -> Option<&Arc<RwLock<Sample>>> {
|
||||
for (i, sample) in self.mapped.iter().enumerate() {
|
||||
if i == self.cursor().0 {
|
||||
return sample.as_ref()
|
||||
}
|
||||
}
|
||||
for (i, sample) in self.unmapped.iter().enumerate() {
|
||||
if i + self.mapped.len() == self.cursor().0 {
|
||||
return Some(sample)
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Value of cursor
|
||||
pub fn cursor (&self) -> (usize, usize) {
|
||||
(self.cursor.0.load(Relaxed), self.cursor.1.load(Relaxed))
|
||||
}
|
||||
/// Assign sample to pitch
|
||||
pub fn set_sample (&mut self, pitch: u7, sample: MaybeSample) -> MaybeSample {
|
||||
let i = pitch.as_int() as usize;
|
||||
let old = self.mapped[i].clone();
|
||||
self.mapped[i] = sample;
|
||||
old
|
||||
}
|
||||
}
|
||||
|
||||
impl NoteRange for Sampler {
|
||||
fn note_lo (&self) -> &AtomicUsize {
|
||||
&self.note_lo
|
||||
}
|
||||
fn note_axis (&self) -> &AtomicUsize {
|
||||
&self.size.y
|
||||
}
|
||||
}
|
||||
|
||||
impl NotePoint for Sampler {
|
||||
fn note_len (&self) -> usize {
|
||||
0 /*TODO?*/
|
||||
}
|
||||
fn set_note_len (&self, x: usize) -> usize {
|
||||
0 /*TODO?*/
|
||||
}
|
||||
fn note_pos (&self) -> usize {
|
||||
self.note_pt.load(Relaxed)
|
||||
}
|
||||
fn set_note_pos (&self, x: usize) -> usize {
|
||||
let old = self.note_pt.swap(x, Relaxed);
|
||||
self.cursor.0.store(x % 8, Relaxed);
|
||||
self.cursor.1.store(x / 8, Relaxed);
|
||||
old
|
||||
}
|
||||
}
|
||||
|
||||
/// A sound sample.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Sample {
|
||||
pub name: Arc<str>,
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub channels: Vec<Vec<f32>>,
|
||||
pub rate: Option<usize>,
|
||||
pub gain: f32,
|
||||
}
|
||||
|
||||
impl Sample {
|
||||
pub fn new (name: impl AsRef<str>, start: usize, end: usize, channels: Vec<Vec<f32>>) -> Self {
|
||||
Self { name: name.as_ref().into(), start, end, channels, rate: None, gain: 1.0 }
|
||||
}
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A currently playing instance of a sample.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct Voice {
|
||||
pub sample: Arc<RwLock<Sample>>,
|
||||
pub after: usize,
|
||||
pub position: usize,
|
||||
pub velocity: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SamplerMode {
|
||||
// Load sample from path
|
||||
Import(usize, FileBrowser),
|
||||
}
|
||||
|
||||
193
crates/device/src/sampler/sampler_view.rs
Normal file
193
crates/device/src/sampler/sampler_view.rs
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
use crate::*;
|
||||
|
||||
impl Sampler {
|
||||
|
||||
pub fn view_grid (&self) -> impl Content<TuiOut> + use<'_> {
|
||||
let cells_x = 8u16;
|
||||
let cells_y = 8u16;
|
||||
let cell_width = 10u16;
|
||||
let cell_height = 2u16;
|
||||
let width = cells_x * cell_width;
|
||||
let height = cells_y * cell_height;
|
||||
let cols = Map::east(
|
||||
cell_width,
|
||||
move||0..cells_x,
|
||||
move|x, _|Map::south(
|
||||
cell_height,
|
||||
move||0..cells_y,
|
||||
move|y, _|self.view_grid_cell("........", x, y, cell_width, cell_height)
|
||||
)
|
||||
);
|
||||
cols
|
||||
}
|
||||
|
||||
pub fn view_grid_cell <'a> (
|
||||
&'a self, name: &'a str, x: u16, y: u16, w: u16, h: u16
|
||||
) -> impl Content<TuiOut> + use<'a> {
|
||||
let cursor = self.cursor();
|
||||
let hi_fg = Color::Rgb(64, 64, 64);
|
||||
let hi_bg = if y == 0 { Color::Reset } else { Color::Rgb(64, 64, 64) /*prev*/ };
|
||||
let tx_fg = if let Some((index, _)) = self.recording
|
||||
&& index % 8 == x as usize
|
||||
&& index / 8 == y as usize
|
||||
{
|
||||
Color::Rgb(255, 64, 0)
|
||||
} else {
|
||||
Color::Rgb(255, 255, 255)
|
||||
};
|
||||
let tx_bg = if x as usize == cursor.0 && y as usize == cursor.1 {
|
||||
Color::Rgb(96, 96, 96)
|
||||
} else {
|
||||
Color::Rgb(64, 64, 64)
|
||||
};
|
||||
let lo_fg = Color::Rgb(64, 64, 64);
|
||||
let lo_bg = if y == 7 { Color::Reset } else { tx_bg };
|
||||
Fixed::xy(w, h, Bsp::s(
|
||||
Fixed::y(1, Tui::fg_bg(hi_fg, hi_bg, RepeatH(Phat::<()>::LO))),
|
||||
Bsp::n(
|
||||
Fixed::y(1, Tui::fg_bg(lo_fg, lo_bg, RepeatH(Phat::<()>::HI))),
|
||||
Fill::x(Fixed::y(1, Tui::fg_bg(tx_fg, tx_bg, name))),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
const _EMPTY: &[(f64, f64)] = &[(0., 0.), (1., 1.), (2., 2.), (0., 2.), (2., 0.)];
|
||||
|
||||
pub fn view_list <'a> (
|
||||
&'a self,
|
||||
compact: bool,
|
||||
editor: &MidiEditor
|
||||
) -> impl Content<TuiOut> + 'a {
|
||||
let note_lo = editor.note_lo().load(Relaxed);
|
||||
let note_pt = editor.note_pos();
|
||||
let note_hi = editor.note_hi();
|
||||
Fixed::x(12, Map::south(
|
||||
1,
|
||||
move||(note_lo..=note_hi).rev(),
|
||||
move|note, i| {
|
||||
//let offset = |a|Push::y(i as u16, Align::n(Fixed::y(1, Fill::x(a))));
|
||||
let mut bg = if note == note_pt { Tui::g(64) } else { Color::Reset };
|
||||
let mut fg = Tui::g(160);
|
||||
let mapped: &Option<Arc<RwLock<Sample>>> = &self.mapped[note];
|
||||
if mapped.is_some() {
|
||||
fg = Tui::g(224);
|
||||
bg = Color::Rgb(0, if note == note_pt { 96 } else { 64 }, 0);
|
||||
}
|
||||
if let Some((index, _)) = self.recording {
|
||||
if note == index {
|
||||
bg = if note == note_pt { Color::Rgb(96,24,0) } else { Color::Rgb(64,16,0) };
|
||||
fg = Color::Rgb(224,64,32)
|
||||
}
|
||||
}
|
||||
Tui::fg_bg(fg, bg, format!("{note:3} {}", self.view_list_item(note, compact)))
|
||||
}))
|
||||
}
|
||||
pub fn view_list_item (&self, note: usize, compact: bool) -> String {
|
||||
if compact {
|
||||
String::default()
|
||||
} else {
|
||||
draw_list_item(&self.mapped[note])
|
||||
}
|
||||
}
|
||||
pub fn view_sample (&self, note_pt: usize) -> impl Content<TuiOut> + use<'_> {
|
||||
Outer(true, Style::default().fg(Tui::g(96))).enclose(draw_viewer(if let Some((_, sample)) = &self.recording {
|
||||
Some(sample)
|
||||
} else if let Some(sample) = &self.mapped[note_pt] {
|
||||
Some(sample)
|
||||
} else {
|
||||
None
|
||||
}))
|
||||
}
|
||||
pub fn status (&self, index: usize) -> impl Content<TuiOut> {
|
||||
draw_status(self.mapped[index].as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_list_item (sample: &Option<Arc<RwLock<Sample>>>) -> String {
|
||||
if let Some(sample) = sample {
|
||||
let sample = sample.read().unwrap();
|
||||
format!("{:8} {:3} {:6}-{:6}/{:6}",
|
||||
sample.name,
|
||||
sample.gain,
|
||||
sample.start,
|
||||
sample.end,
|
||||
sample.channels[0].len()
|
||||
)
|
||||
} else {
|
||||
String::from("........")
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_viewer (sample: Option<&Arc<RwLock<Sample>>>) -> impl Content<TuiOut> + use<'_> {
|
||||
let min_db = -40.0;
|
||||
ThunkRender::new(move|to: &mut TuiOut|{
|
||||
let [x, y, width, height] = to.area();
|
||||
let area = Rect { x, y, width, height };
|
||||
let (x_bounds, y_bounds, lines): ([f64;2], [f64;2], Vec<Line>) =
|
||||
if let Some(sample) = &sample {
|
||||
let sample = sample.read().unwrap();
|
||||
let start = sample.start as f64;
|
||||
let end = sample.end as f64;
|
||||
let length = end - start;
|
||||
let step = length / width as f64;
|
||||
let mut t = start;
|
||||
let mut lines = vec![];
|
||||
while t < end {
|
||||
let chunk = &sample.channels[0][t as usize..((t + step) as usize).min(sample.end)];
|
||||
let total: f32 = chunk.iter().map(|x|x.abs()).sum();
|
||||
let count = chunk.len() as f32;
|
||||
let meter = 10. * (total / count).log10();
|
||||
let x = t as f64;
|
||||
let y = meter as f64;
|
||||
lines.push(Line::new(x, min_db, x, y, Color::Green));
|
||||
t += step / 2.;
|
||||
}
|
||||
(
|
||||
[sample.start as f64, sample.end as f64],
|
||||
[min_db, 0.],
|
||||
lines
|
||||
)
|
||||
} else {
|
||||
(
|
||||
[0.0, width as f64],
|
||||
[0.0, height as f64],
|
||||
vec![
|
||||
Line::new(0.0, 0.0, width as f64, height as f64, Color::Red),
|
||||
Line::new(width as f64, 0.0, 0.0, height as f64, Color::Red),
|
||||
]
|
||||
)
|
||||
};
|
||||
Canvas::default()
|
||||
.x_bounds(x_bounds)
|
||||
.y_bounds(y_bounds)
|
||||
.paint(|ctx| { for line in lines.iter() { ctx.draw(line) } })
|
||||
.render(area, &mut to.buffer);
|
||||
})
|
||||
}
|
||||
|
||||
fn draw_status (sample: Option<&Arc<RwLock<Sample>>>) -> impl Content<TuiOut> {
|
||||
Tui::bold(true, Tui::fg(Tui::g(224), sample
|
||||
.map(|sample|{
|
||||
let sample = sample.read().unwrap();
|
||||
format!("Sample {}-{}", sample.start, sample.end)
|
||||
})
|
||||
.unwrap_or_else(||"No sample".to_string())))
|
||||
}
|
||||
|
||||
fn draw_sample (
|
||||
to: &mut TuiOut, 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 {
|
||||
to.blit(&"🬴", 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);
|
||||
to.blit(&label1, x+2, y, Some(style.bold()));
|
||||
to.blit(&label2, x+3+label1.len()as u16, y, Some(style));
|
||||
Ok(label1.len() + label2.len() + 4)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue