mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-08 20:56:43 +01:00
modularize core
This commit is contained in:
parent
a4061535b5
commit
2837ffff4a
43 changed files with 629 additions and 770 deletions
90
src/core/device.rs
Normal file
90
src/core/device.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// A UI component that may have presence on the JACK grap.
|
||||
pub trait Device: Render + Handle + PortList + Send + Sync {
|
||||
fn boxed (self) -> Box<dyn Device> where Self: Sized + 'static {
|
||||
Box::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// All things that implement the required traits can be treated as `Device`.
|
||||
impl<T: Render + Handle + PortList + Send + Sync> Device for T {}
|
||||
|
||||
/// A device dynamicammy composed of state and handlers.
|
||||
pub struct DynamicDevice<T> {
|
||||
pub state: Arc<Mutex<T>>,
|
||||
pub render: Mutex<Box<dyn FnMut(&T, &mut Buffer, Rect)->Usually<Rect> + Send>>,
|
||||
pub handle: Arc<Mutex<Box<dyn FnMut(&mut T, &AppEvent)->Usually<bool> + Send>>>,
|
||||
pub process: Arc<Mutex<Box<dyn FnMut(&mut T, &Client, &ProcessScope)->Control + Send>>>,
|
||||
pub client: Option<DynamicAsyncClient>
|
||||
}
|
||||
|
||||
impl<T> Handle for DynamicDevice<T> {
|
||||
fn handle (&mut self, event: &AppEvent) -> Usually<bool> {
|
||||
self.handle.lock().unwrap()(&mut *self.state.lock().unwrap(), event)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Render for DynamicDevice<T> {
|
||||
fn render (&self, buf: &mut Buffer, area: Rect) -> Usually<Rect> {
|
||||
self.render.lock().unwrap()(&*self.state.lock().unwrap(), buf, area)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PortList + Send + Sync + 'static> PortList for DynamicDevice<T> {
|
||||
fn audio_ins (&self) -> Usually<Vec<String>> {
|
||||
self.state().audio_ins()
|
||||
}
|
||||
fn audio_outs (&self) -> Usually<Vec<String>> {
|
||||
self.state().audio_outs()
|
||||
}
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
self.state().midi_ins()
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
self.state().midi_outs()
|
||||
}
|
||||
}
|
||||
|
||||
type DynamicAsyncClient = AsyncClient<DynamicNotifications, DynamicProcessHandler>;
|
||||
type DynamicNotifications = Notifications<Box<dyn Fn(AppEvent) + Send + Sync>>;
|
||||
type DynamicProcessHandler = ClosureProcessHandler<BoxedProcessHandler>;
|
||||
|
||||
impl<T: Send + Sync + 'static> DynamicDevice<T> {
|
||||
pub fn new <'a, R, H, P> (render: R, handle: H, process: P, state: T) -> Self where
|
||||
R: FnMut(&T, &mut Buffer, Rect) -> Usually<Rect> + Send + 'static,
|
||||
H: FnMut(&mut T, &AppEvent) -> Usually<bool> + Send + 'static,
|
||||
P: FnMut(&mut T, &Client, &ProcessScope) -> Control + Send + 'static,
|
||||
{
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(state)),
|
||||
render: Mutex::new(Box::new(render)),
|
||||
handle: Arc::new(Mutex::new(Box::new(handle))),
|
||||
process: Arc::new(Mutex::new(Box::new(process))),
|
||||
client: None,
|
||||
}
|
||||
}
|
||||
pub fn state (&self) -> std::sync::MutexGuard<'_, T> {
|
||||
self.state.lock().unwrap()
|
||||
}
|
||||
pub fn activate (mut self, client: Client) -> Usually<Self> {
|
||||
self.client = Some(client.activate_async(Notifications(Box::new({
|
||||
let state = self.state.clone();
|
||||
let handle = self.handle.clone();
|
||||
move|event|{
|
||||
let mut state = state.lock().unwrap();
|
||||
let mut handle = handle.lock().unwrap();
|
||||
handle(&mut state, &event).unwrap();
|
||||
}
|
||||
}) as Box<dyn Fn(AppEvent) + Send + Sync>), ClosureProcessHandler::new(Box::new({
|
||||
let state = self.state.clone();
|
||||
let process = self.process.clone();
|
||||
move|client: &Client, scope: &ProcessScope|{
|
||||
let mut state = state.lock().unwrap();
|
||||
let mut process = process.lock().unwrap();
|
||||
(process)(&mut state, client, scope)
|
||||
}
|
||||
}) as BoxedProcessHandler))?);
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
89
src/core/handle.rs
Normal file
89
src/core/handle.rs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// Trait for things that handle input events.
|
||||
pub trait Handle {
|
||||
/// Handle an input event.
|
||||
/// Returns Ok(true) if the device handled the event.
|
||||
/// This is the mechanism which allows nesting of components;.
|
||||
fn handle (&mut self, _e: &AppEvent) -> Usually<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppEvent {
|
||||
/// Terminal input
|
||||
Input(::crossterm::event::Event),
|
||||
/// Update values but not the whole form.
|
||||
Update,
|
||||
/// Update the whole form.
|
||||
Redraw,
|
||||
/// Device gains focus
|
||||
Focus,
|
||||
/// Device loses focus
|
||||
Blur,
|
||||
/// JACK notification
|
||||
Jack(JackEvent)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum JackEvent {
|
||||
ThreadInit,
|
||||
Shutdown(ClientStatus, String),
|
||||
Freewheel(bool),
|
||||
SampleRate(Frames),
|
||||
ClientRegistration(String, bool),
|
||||
PortRegistration(PortId, bool),
|
||||
PortRename(PortId, String, String),
|
||||
PortsConnected(PortId, PortId, bool),
|
||||
GraphReorder,
|
||||
XRun,
|
||||
}
|
||||
|
||||
pub struct Notifications<T: Fn(AppEvent) + Send>(pub T);
|
||||
|
||||
impl<T: Fn(AppEvent) + Send> NotificationHandler for Notifications<T> {
|
||||
fn thread_init (&self, _: &Client) {
|
||||
self.0(AppEvent::Jack(JackEvent::ThreadInit));
|
||||
}
|
||||
|
||||
fn shutdown (&mut self, status: ClientStatus, reason: &str) {
|
||||
self.0(AppEvent::Jack(JackEvent::Shutdown(status, reason.into())));
|
||||
}
|
||||
|
||||
fn freewheel (&mut self, _: &Client, enabled: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::Freewheel(enabled)));
|
||||
}
|
||||
|
||||
fn sample_rate (&mut self, _: &Client, frames: Frames) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::SampleRate(frames)));
|
||||
Control::Quit
|
||||
}
|
||||
|
||||
fn client_registration (&mut self, _: &Client, name: &str, reg: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::ClientRegistration(name.into(), reg)));
|
||||
}
|
||||
|
||||
fn port_registration (&mut self, _: &Client, id: PortId, reg: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::PortRegistration(id, reg)));
|
||||
}
|
||||
|
||||
fn port_rename (&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::PortRename(id, old.into(), new.into())));
|
||||
Control::Continue
|
||||
}
|
||||
|
||||
fn ports_connected (&mut self, _: &Client, a: PortId, b: PortId, are: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::PortsConnected(a, b, are)));
|
||||
}
|
||||
|
||||
fn graph_reorder (&mut self, _: &Client) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::GraphReorder));
|
||||
Control::Continue
|
||||
}
|
||||
|
||||
fn xrun (&mut self, _: &Client) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::XRun));
|
||||
Control::Continue
|
||||
}
|
||||
}
|
||||
35
src/core/jack.rs
Normal file
35
src/core/jack.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
use crate::core::*;
|
||||
|
||||
pub type BoxedNotificationHandler =
|
||||
Box<dyn Fn(AppEvent) + Send>;
|
||||
|
||||
pub type BoxedProcessHandler =
|
||||
Box<dyn FnMut(&Client, &ProcessScope)-> Control + Send>;
|
||||
|
||||
pub type Jack<N> =
|
||||
AsyncClient<N, ClosureProcessHandler<BoxedProcessHandler>>;
|
||||
|
||||
pub use ::jack::{
|
||||
AsyncClient,
|
||||
AudioIn,
|
||||
AudioOut,
|
||||
Client,
|
||||
ClientOptions,
|
||||
ClientStatus,
|
||||
ClosureProcessHandler,
|
||||
Control,
|
||||
Frames,
|
||||
MidiIn,
|
||||
MidiOut,
|
||||
NotificationHandler,
|
||||
Port,
|
||||
PortFlags,
|
||||
PortId,
|
||||
PortSpec,
|
||||
ProcessHandler,
|
||||
ProcessScope,
|
||||
RawMidi,
|
||||
Transport,
|
||||
TransportState,
|
||||
TransportStatePosition
|
||||
};
|
||||
39
src/core/keymap.rs
Normal file
39
src/core/keymap.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
use crate::core::*;
|
||||
|
||||
pub type KeyHandler<T> = &'static dyn Fn(&mut T)->Usually<bool>;
|
||||
|
||||
pub type KeyBinding<T> = (
|
||||
KeyCode, KeyModifiers, &'static str, &'static str, KeyHandler<T>
|
||||
);
|
||||
|
||||
pub type KeyMap<T> = [KeyBinding<T>];
|
||||
|
||||
pub fn handle_keymap <T> (
|
||||
state: &mut T, event: &AppEvent, keymap: &KeyMap<T>,
|
||||
) -> Usually<bool> {
|
||||
match event {
|
||||
AppEvent::Input(Event::Key(event)) => {
|
||||
for (code, modifiers, _, _, command) in keymap.iter() {
|
||||
if *code == event.code && modifiers.bits() == event.modifiers.bits() {
|
||||
return command(state)
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
};
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! key {
|
||||
($k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr) => {
|
||||
(KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! keymap {
|
||||
($T:ty { $([$k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr]),* $(,)? }) => {
|
||||
&[
|
||||
$((KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f as KeyHandler<$T>)),*
|
||||
] as &'static [KeyBinding<$T>]
|
||||
}
|
||||
}
|
||||
121
src/core/mod.rs
Normal file
121
src/core/mod.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
pub type Usually<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
macro_rules! submod {
|
||||
($($name:ident)*) => { $(mod $name; pub use self::$name::*;)* };
|
||||
}
|
||||
|
||||
submod!( device handle jack keymap note port process render time );
|
||||
|
||||
pub use std::error::Error;
|
||||
pub use std::io::{stdout, Stdout, Write};
|
||||
pub use std::thread::{spawn, JoinHandle};
|
||||
pub use std::time::Duration;
|
||||
pub use std::collections::BTreeMap;
|
||||
pub use std::sync::{
|
||||
Arc,
|
||||
Mutex, MutexGuard,
|
||||
atomic::{
|
||||
Ordering,
|
||||
AtomicBool,
|
||||
AtomicUsize
|
||||
},
|
||||
mpsc::{self, channel, Sender, Receiver}
|
||||
};
|
||||
|
||||
pub use ::crossterm::{
|
||||
ExecutableCommand, QueueableCommand,
|
||||
event::{Event, KeyEvent, KeyCode, KeyModifiers},
|
||||
terminal::{
|
||||
self,
|
||||
Clear, ClearType,
|
||||
EnterAlternateScreen, LeaveAlternateScreen,
|
||||
enable_raw_mode, disable_raw_mode
|
||||
},
|
||||
};
|
||||
|
||||
pub use ::ratatui::{
|
||||
prelude::{
|
||||
Buffer, Rect, Style, Color, CrosstermBackend, Layout, Stylize, Direction,
|
||||
Line, Constraint
|
||||
},
|
||||
widgets::{Widget, WidgetRef},
|
||||
//style::Stylize,
|
||||
};
|
||||
|
||||
pub use ::midly::{
|
||||
MidiMessage,
|
||||
live::LiveEvent,
|
||||
num::u7
|
||||
};
|
||||
|
||||
pub use crate::{key, keymap};
|
||||
|
||||
/// Run a device as the root of the app.
|
||||
pub fn run (device: impl Device + Send + Sync + 'static) -> Result<(), Box<dyn Error>> {
|
||||
let device = Arc::new(Mutex::new(device));
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
|
||||
// Spawn input (handle) thread
|
||||
let _input_thread = {
|
||||
let poll = std::time::Duration::from_millis(100);
|
||||
let exited = exited.clone();
|
||||
let device = device.clone();
|
||||
spawn(move || loop {
|
||||
// Exit if flag is set
|
||||
if exited.fetch_and(true, Ordering::Relaxed) {
|
||||
break
|
||||
}
|
||||
// Listen for events and send them to the main thread
|
||||
if ::crossterm::event::poll(poll).is_ok() {
|
||||
let event = ::crossterm::event::read().unwrap();
|
||||
match event {
|
||||
Event::Key(KeyEvent {
|
||||
code: KeyCode::Char('c'),
|
||||
modifiers: KeyModifiers::CONTROL,
|
||||
..
|
||||
}) => {
|
||||
exited.store(true, Ordering::Relaxed);
|
||||
},
|
||||
_ => if device.lock().unwrap().handle(&AppEvent::Input(event)).is_err() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
// Set up terminal
|
||||
stdout().execute(EnterAlternateScreen)?;
|
||||
enable_raw_mode()?;
|
||||
let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
|
||||
// Set up panic hook
|
||||
let better_panic_handler = better_panic::Settings::auto()
|
||||
.verbosity(better_panic::Verbosity::Full)
|
||||
.create_panic_handler();
|
||||
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo|{
|
||||
stdout().execute(LeaveAlternateScreen).unwrap();
|
||||
crossterm::terminal::disable_raw_mode().unwrap();
|
||||
better_panic_handler(info);
|
||||
}));
|
||||
|
||||
// Main (render) loop
|
||||
let sleep = std::time::Duration::from_millis(16);
|
||||
loop {
|
||||
terminal.draw(|frame|{
|
||||
let area = frame.size();
|
||||
let buffer = frame.buffer_mut();
|
||||
device.lock().unwrap().render(buffer, area).expect("Failed to render content.");
|
||||
}).expect("Failed to render frame");
|
||||
if exited.fetch_and(true, Ordering::Relaxed) {
|
||||
break
|
||||
}
|
||||
std::thread::sleep(sleep);
|
||||
};
|
||||
|
||||
// Cleanup
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
crossterm::terminal::disable_raw_mode()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
0
src/core/note.rs
Normal file
0
src/core/note.rs
Normal file
50
src/core/port.rs
Normal file
50
src/core/port.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// Trait for things that may expose JACK ports.
|
||||
pub trait PortList {
|
||||
fn audio_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn audio_outs (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn connect (&mut self, _connect: bool, _source: &str, _target: &str)
|
||||
-> Usually<()>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
fn connect_all (&mut self, connections: &[(bool, &str, &str)])
|
||||
-> Usually<()>
|
||||
{
|
||||
for (connect, source, target) in connections.iter() {
|
||||
self.connect(*connect, source, target)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DevicePort<T: PortSpec> {
|
||||
pub name: String,
|
||||
pub port: Port<T>,
|
||||
pub connect: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T: PortSpec + Default> DevicePort<T> {
|
||||
pub fn new (client: &Client, name: &str, connect: &[&str]) -> Usually<Self> {
|
||||
let mut connects = vec![];
|
||||
for port in connect.iter() {
|
||||
connects.push(port.to_string());
|
||||
}
|
||||
Ok(Self {
|
||||
name: name.to_string(),
|
||||
port: client.register_port(name, T::default())?,
|
||||
connect: connects,
|
||||
})
|
||||
}
|
||||
}
|
||||
0
src/core/process.rs
Normal file
0
src/core/process.rs
Normal file
54
src/core/render.rs
Normal file
54
src/core/render.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// Trait for things that render to the display.
|
||||
pub trait Render {
|
||||
// Render something to an area of the buffer.
|
||||
// Returns area used by component.
|
||||
// This is insufficient but for the most basic dynamic layout algorithms.
|
||||
fn render (&self, _b: &mut Buffer, _a: Rect) -> Usually<Rect> {
|
||||
Ok(Rect { x: 0, y: 0, width: 0, height: 0 })
|
||||
}
|
||||
fn min_width (&self) -> u16 {
|
||||
0
|
||||
}
|
||||
fn max_width (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
fn min_height (&self) -> u16 {
|
||||
0
|
||||
}
|
||||
fn max_height (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Box<dyn Device> {
|
||||
fn render (&self, b: &mut Buffer, a: Rect) -> Usually<Rect> {
|
||||
(**self).render(b, a)
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for &dyn Render {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
Render::render(*self, buf, area).expect("Failed to render device.");
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for dyn Render {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
Render::render(self, buf, area).expect("Failed to render device.");
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Blit {
|
||||
// Render something to X, Y coordinates in a buffer, ignoring width/height.
|
||||
fn blit (&self, buf: &mut Buffer, x: u16, y: u16, style: Option<Style>);
|
||||
}
|
||||
|
||||
impl<T: AsRef<str>> Blit for T {
|
||||
fn blit (&self, buf: &mut Buffer, x: u16, y: u16, style: Option<Style>) {
|
||||
if x < buf.area.width && y < buf.area.height {
|
||||
buf.set_string(x, y, self.as_ref(), style.unwrap_or(Style::default()))
|
||||
}
|
||||
}
|
||||
}
|
||||
147
src/core/time.rs
Normal file
147
src/core/time.rs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
use crate::core::*;
|
||||
|
||||
pub struct Timebase {
|
||||
/// Frames per second
|
||||
pub rate: AtomicUsize,
|
||||
/// Beats per minute
|
||||
pub tempo: AtomicUsize,
|
||||
/// Ticks per beat
|
||||
pub ppq: AtomicUsize,
|
||||
}
|
||||
|
||||
enum QuantizeMode {
|
||||
Forward,
|
||||
Backward,
|
||||
Nearest,
|
||||
}
|
||||
|
||||
struct Loop<T> {
|
||||
repeat: bool,
|
||||
pre_start: T,
|
||||
start: T,
|
||||
end: T,
|
||||
post_end: T,
|
||||
}
|
||||
|
||||
/// NoteDuration in musical terms. Has definite usec value
|
||||
/// for given bpm and sample rate.
|
||||
pub enum NoteDuration {
|
||||
Nth(usize, usize),
|
||||
Dotted(Box<Self>),
|
||||
Tuplet(usize, Box<Self>),
|
||||
}
|
||||
|
||||
impl Timebase {
|
||||
#[inline] pub fn rate (&self) -> usize {
|
||||
self.rate.load(Ordering::Relaxed)
|
||||
}
|
||||
#[inline] pub fn tempo (&self) -> usize {
|
||||
self.tempo.load(Ordering::Relaxed)
|
||||
}
|
||||
#[inline] pub fn ppq (&self) -> usize {
|
||||
self.ppq.load(Ordering::Relaxed)
|
||||
}
|
||||
#[inline] fn beats_per_second (&self) -> f64 {
|
||||
self.tempo() as f64 / 60000.0
|
||||
}
|
||||
#[inline] fn frames_per_second (&self) -> usize {
|
||||
self.rate()
|
||||
}
|
||||
#[inline] pub fn frames_per_beat (&self) -> f64 {
|
||||
self.frames_per_second() as f64 / self.beats_per_second()
|
||||
}
|
||||
#[inline] pub fn frames_per_tick (&self) -> f64 {
|
||||
self.frames_per_second() as f64 / self.ticks_per_second()
|
||||
}
|
||||
#[inline] fn frames_per_loop (&self, steps: f64, steps_per_beat: f64) -> f64 {
|
||||
self.frames_per_beat() * steps / steps_per_beat
|
||||
}
|
||||
#[inline] fn ticks_per_beat (&self) -> f64 {
|
||||
self.ppq.load(Ordering::Relaxed) as f64
|
||||
}
|
||||
#[inline] fn ticks_per_second (&self) -> f64 {
|
||||
self.beats_per_second() * self.ticks_per_beat()
|
||||
}
|
||||
#[inline] pub fn frame_to_usec (&self, frame: usize) -> usize {
|
||||
frame * 1000000 / self.rate()
|
||||
}
|
||||
#[inline] pub fn usec_to_frame (&self, usec: usize) -> usize {
|
||||
usec * self.rate() / 1000
|
||||
}
|
||||
#[inline] pub fn usec_per_bar (&self, beats_per_bar: usize) -> usize {
|
||||
self.usec_per_beat() * beats_per_bar
|
||||
}
|
||||
#[inline] pub fn usec_per_beat (&self) -> usize {
|
||||
60_000_000_000 / self.tempo()
|
||||
}
|
||||
#[inline] pub fn usec_per_step (&self, divisor: usize) -> usize {
|
||||
self.usec_per_beat() / divisor
|
||||
}
|
||||
#[inline] pub fn usec_per_tick (&self) -> usize {
|
||||
self.usec_per_beat() / self.ppq()
|
||||
}
|
||||
#[inline] pub fn note_to_usec (&self, note: &NoteDuration) -> usize {
|
||||
match note {
|
||||
NoteDuration::Nth(time, flies) =>
|
||||
self.usec_per_beat() * *time / *flies,
|
||||
NoteDuration::Dotted(note) =>
|
||||
self.note_to_usec(note) * 3 / 2,
|
||||
NoteDuration::Tuplet(n, note) =>
|
||||
self.note_to_usec(note) * 2 / *n,
|
||||
}
|
||||
}
|
||||
#[inline] pub fn note_to_frame (&self, note: &NoteDuration) -> usize {
|
||||
self.usec_to_frame(self.note_to_usec(note))
|
||||
}
|
||||
pub fn frames_to_ticks (&self, start: usize, end: usize, fpl: usize) -> Vec<(usize, usize)> {
|
||||
let start_frame = start % fpl;
|
||||
let end_frame = end % fpl;
|
||||
let fpt = self.frames_per_tick();
|
||||
let mut ticks = vec![];
|
||||
let mut add_frame = |frame: f64|{
|
||||
let jitter = frame.rem_euclid(fpt);
|
||||
let last_jitter = (frame - 1.0).max(0.0) % fpt;
|
||||
let next_jitter = frame + 1.0 % fpt;
|
||||
if jitter <= last_jitter && jitter <= next_jitter {
|
||||
ticks.push((frame as usize % (end-start), (frame / fpt) as usize));
|
||||
};
|
||||
};
|
||||
if start_frame < end_frame {
|
||||
for frame in start_frame..end_frame {
|
||||
add_frame(frame as f64);
|
||||
}
|
||||
} else {
|
||||
let mut frame = start_frame;
|
||||
loop {
|
||||
add_frame(frame as f64);
|
||||
frame = frame + 1;
|
||||
if frame >= fpl {
|
||||
frame = 0;
|
||||
loop {
|
||||
add_frame(frame as f64);
|
||||
frame = frame + 1;
|
||||
if frame >= end_frame.saturating_sub(1) {
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
ticks
|
||||
}
|
||||
pub fn quantize (&self, step: &NoteDuration, time: usize) -> (usize, usize) {
|
||||
let step = self.note_to_usec(step);
|
||||
let time = time / step;
|
||||
let offset = time % step;
|
||||
(time, offset)
|
||||
}
|
||||
pub fn quantize_into <T, U> (&self, step: &NoteDuration, events: U) -> Vec<(usize, T)>
|
||||
where U: std::iter::Iterator<Item=(usize, T)> + Sized
|
||||
{
|
||||
events
|
||||
.map(|(time, event)|(self.quantize(step, time).0, event))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue