mirror of
https://codeberg.org/unspeaker/tek.git
synced 2026-10-08 10:46:43 +02:00
more shuffling; fix initial state
This commit is contained in:
parent
47a6138215
commit
8c4419e6f5
11 changed files with 1965 additions and 1979 deletions
|
|
@ -1614,3 +1614,60 @@
|
||||||
//})?;
|
//})?;
|
||||||
//Ok(bind)
|
//Ok(bind)
|
||||||
//}
|
//}
|
||||||
|
|
||||||
|
//impl App {
|
||||||
|
///// Toggle MIDI editor.
|
||||||
|
/////
|
||||||
|
///// ```
|
||||||
|
///// tek::App::default().toggle_editor(None);
|
||||||
|
///// ```
|
||||||
|
//pub fn toggle_editor (&mut self, value: Option<bool>) {
|
||||||
|
////FIXME: self.editing.store(value.unwrap_or_else(||!self.is_editing()), Relaxed);
|
||||||
|
//if value.unwrap_or_else(||!self.editor().is_some()) {
|
||||||
|
//self.toggle_editor_on()
|
||||||
|
//} else {
|
||||||
|
//self.toggle_editor_off()
|
||||||
|
//}
|
||||||
|
//}
|
||||||
|
|
||||||
|
//fn toggle_editor_on (&mut self) {
|
||||||
|
//// Create new clip in pool when entering empty cell
|
||||||
|
//if let Selection::TrackClip { track: track_index, scene } = *self.selection()
|
||||||
|
//&& let Some(scene) = self.project.scenes.get_mut(scene)
|
||||||
|
//&& scene.clips.get(track_index).is_none()
|
||||||
|
//&& let Some(track) = self.project.tracks.get_mut(track_index)
|
||||||
|
//{
|
||||||
|
//let color = track.color.base.mix(scene.color.base, 0.5);
|
||||||
|
//let color = ItemColor::random_near(color, 0.2).into();
|
||||||
|
//let clip: MidiClip = MidiClip { color, ..Default::default() };
|
||||||
|
//let clip = self.project.clips.append(Some(clip));
|
||||||
|
//// autocolor: new clip colors from scene and track color
|
||||||
|
//if let Some(editor) = &mut self.project.editor {
|
||||||
|
//*editor.mode.clip.write() = clip.0.read().clone();
|
||||||
|
//editor.mode.color = clip.0.read().as_ref().map(|p|p.read().color)
|
||||||
|
//.unwrap_or(ItemTheme::G[64]);
|
||||||
|
//}
|
||||||
|
//*scene.clips.slot(track_index).write() = clip.0.read().clone();
|
||||||
|
////Some(clip)
|
||||||
|
//} else {
|
||||||
|
////None
|
||||||
|
//}
|
||||||
|
//}
|
||||||
|
|
||||||
|
//fn toggle_editor_off (&mut self) {
|
||||||
|
//if let Selection::TrackClip { track, scene } = *self.selection()
|
||||||
|
//&& let Some(scene) = self.project.scenes.get_mut(scene)
|
||||||
|
//{
|
||||||
|
//// Remove clip from arrangement when exiting empty clip editor
|
||||||
|
//let mut swapped = None;
|
||||||
|
//if let Some(count) = scene.clips.slot(track).read().as_ref().map(|c|c.read().count_midi_messages())
|
||||||
|
//&& count == 0
|
||||||
|
//{
|
||||||
|
//std::mem::swap(&mut swapped, &mut scene.clips.slot(track).write());
|
||||||
|
//}
|
||||||
|
//if let Some(clip) = swapped {
|
||||||
|
//self.project.clips.remove(&*clip.read());
|
||||||
|
//}
|
||||||
|
//}
|
||||||
|
//}
|
||||||
|
//}
|
||||||
|
|
|
||||||
|
|
@ -1434,3 +1434,45 @@ pub fn print_config_views (config: &Config) {
|
||||||
println!("{} {} {}", Green.paint("VIEW"), Green.bold().paint(format!("{k:<16}")), v.source);
|
println!("{} {} {}", Green.paint("VIEW"), Green.bold().paint(format!("{k:<16}")), v.source);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Project {
|
||||||
|
/// Width of display
|
||||||
|
pub fn w (&self) -> u16 {
|
||||||
|
self.size.w() as u16
|
||||||
|
}
|
||||||
|
/// Width allocated for sidebar.
|
||||||
|
pub fn w_sidebar (&self, is_editing: bool) -> u16 {
|
||||||
|
self.w() / if is_editing { 16 } else { 8 } as u16
|
||||||
|
}
|
||||||
|
/// Height of display
|
||||||
|
pub fn h (&self) -> u16 {
|
||||||
|
self.size.h() as u16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HasWidth {
|
||||||
|
const MIN_WIDTH: usize;
|
||||||
|
/// Increment track width.
|
||||||
|
fn width_inc (&mut self);
|
||||||
|
/// Decrement track width, down to a hardcoded minimum of [Self::MIN_WIDTH].
|
||||||
|
fn width_dec (&mut self);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HasClipsSize {
|
||||||
|
/// Size of clips area.
|
||||||
|
fn clips_size (&self) -> &Sizer;
|
||||||
|
/// Draw content annotated with value of [Self::clips_size].
|
||||||
|
fn with_clips_size (&self, show: bool, content: impl Draw<Tui>) -> impl Draw<Tui> {
|
||||||
|
let size = self.clips_size();
|
||||||
|
above(
|
||||||
|
when(show, fg(Green, east!(size.w() as usize, "x", size.h() as usize)).align_se()),
|
||||||
|
size.of(content.align_c().full_wh())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasClipsSize for App {
|
||||||
|
fn clips_size (&self) -> &Sizer {
|
||||||
|
&self.project.size_inner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,16 @@ impl App {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Has a chain of devices.
|
||||||
|
pub trait HasDevices: AsRef<Vec<Device>> + AsMut<Vec<Device>> {
|
||||||
|
fn devices (&self) -> &Vec<Device> {
|
||||||
|
self.as_ref()
|
||||||
|
}
|
||||||
|
fn devices_mut (&mut self) -> &mut Vec<Device> {
|
||||||
|
self.as_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tek_proc::command(Device)]
|
#[tek_proc::command(Device)]
|
||||||
#[tek_proc::keyword(Device)]
|
#[tek_proc::keyword(Device)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
|
|
||||||
738
src/gear/midi.rs
738
src/gear/midi.rs
|
|
@ -2,623 +2,6 @@ use crate::*;
|
||||||
use ::std::sync::Arc;
|
use ::std::sync::Arc;
|
||||||
use ::atomic_float::AtomicF64;
|
use ::atomic_float::AtomicF64;
|
||||||
|
|
||||||
impl App {
|
|
||||||
/// Update memoized render of clock values.
|
|
||||||
/// ```
|
|
||||||
/// tek::App::default().update_clock();
|
|
||||||
/// ```
|
|
||||||
pub fn update_clock (&self) {
|
|
||||||
ClockView::update_clock(
|
|
||||||
&self.project.clock.view_cache, self.clock(), self.size.w() > 80
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The source of time.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let clock = tek::Clock::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Default)] pub struct Clock {
|
|
||||||
/// JACK transport handle.
|
|
||||||
pub transport: Arc<Option<Transport>>,
|
|
||||||
/// Global temporal resolution (shared by [Moment] fields)
|
|
||||||
pub timebase: Arc<Timebase>,
|
|
||||||
/// Current global sample and usec (monotonic from JACK clock)
|
|
||||||
pub global: Arc<Moment>,
|
|
||||||
/// Global sample and usec at which playback started
|
|
||||||
pub started: Arc<RwLock<Option<Moment>>>,
|
|
||||||
/// Playback offset (when playing not from start)
|
|
||||||
pub offset: Arc<Moment>,
|
|
||||||
/// Current playhead position
|
|
||||||
pub playhead: Arc<Moment>,
|
|
||||||
/// Note quantization factor
|
|
||||||
pub quant: Arc<Quantize>,
|
|
||||||
/// Launch quantization factor
|
|
||||||
pub sync: Arc<LaunchSync>,
|
|
||||||
/// Size of buffer in samples
|
|
||||||
pub chunk: Arc<AtomicUsize>,
|
|
||||||
// Cache of formatted strings
|
|
||||||
pub view_cache: Arc<RwLock<ClockView>>,
|
|
||||||
/// For syncing the clock to an external source
|
|
||||||
#[cfg(feature = "port")] pub midi_in: Arc<RwLock<Option<MidiInput>>>,
|
|
||||||
/// For syncing other devices to this clock
|
|
||||||
#[cfg(feature = "port")] pub midi_out: Arc<RwLock<Option<MidiOutput>>>,
|
|
||||||
/// For emitting a metronome
|
|
||||||
#[cfg(feature = "port")] pub click_out: Arc<RwLock<Option<AudioOutput>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
//impl<T: HasClock> Act<T> for ClockCmd {
|
|
||||||
//fn act (&self, state: &mut T) -> Perhaps<Self> {
|
|
||||||
//self.act(state.clock_mut()) // awesome
|
|
||||||
//}
|
|
||||||
//}
|
|
||||||
|
|
||||||
/// Quantization setting for launching clips
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct LaunchSync (pub(crate) AtomicF64);
|
|
||||||
|
|
||||||
/// Quantization setting for notes
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct Quantize (pub(crate) AtomicF64);
|
|
||||||
|
|
||||||
/// A unit of time, represented as an atomic 64-bit float.
|
|
||||||
///
|
|
||||||
/// According to https://stackoverflow.com/a/873367, as per IEEE754,
|
|
||||||
/// every integer between 1 and 2^53 can be represented exactly.
|
|
||||||
/// This should mean that, even at 192kHz sampling rate, over 1 year of audio
|
|
||||||
/// can be clocked in microseconds with f64 without losing precision.
|
|
||||||
pub trait TimeUnit {}
|
|
||||||
|
|
||||||
pub const DEFAULT_PPQ: f64 = 96.0;
|
|
||||||
|
|
||||||
/// FIXME: remove this and use PPQ from timebase everywhere:
|
|
||||||
pub const PPQ: usize = 96;
|
|
||||||
|
|
||||||
/// (pulses, name), assuming 96 PPQ
|
|
||||||
pub const NOTE_DURATIONS: [(usize, &str);26] = [
|
|
||||||
(1, "1/384"), (2, "1/192"),
|
|
||||||
(3, "1/128"), (4, "1/96"),
|
|
||||||
(6, "1/64"), (8, "1/48"),
|
|
||||||
(12, "1/32"), (16, "1/24"),
|
|
||||||
(24, "1/16"), (32, "1/12"),
|
|
||||||
(48, "1/8"), (64, "1/6"),
|
|
||||||
(96, "1/4"), (128, "1/3"),
|
|
||||||
(192, "1/2"), (256, "2/3"),
|
|
||||||
(384, "1/1"), (512, "4/3"),
|
|
||||||
(576, "3/2"), (768, "2/1"),
|
|
||||||
(1152, "3/1"), (1536, "4/1"),
|
|
||||||
(2304, "6/1"), (3072, "8/1"),
|
|
||||||
(3456, "9/1"), (6144, "16/1"),
|
|
||||||
];
|
|
||||||
|
|
||||||
pub const NOTE_NAMES: [&str; 128] = [
|
|
||||||
"C0", "C#0", "D0", "D#0", "E0", "F0", "F#0", "G0", "G#0", "A0", "A#0", "B0",
|
|
||||||
"C1", "C#1", "D1", "D#1", "E1", "F1", "F#1", "G1", "G#1", "A1", "A#1", "B1",
|
|
||||||
"C2", "C#2", "D2", "D#2", "E2", "F2", "F#2", "G2", "G#2", "A2", "A#2", "B2",
|
|
||||||
"C3", "C#3", "D3", "D#3", "E3", "F3", "F#3", "G3", "G#3", "A3", "A#3", "B3",
|
|
||||||
"C4", "C#4", "D4", "D#4", "E4", "F4", "F#4", "G4", "G#4", "A4", "A#4", "B4",
|
|
||||||
"C5", "C#5", "D5", "D#5", "E5", "F5", "F#5", "G5", "G#5", "A5", "A#5", "B5",
|
|
||||||
"C6", "C#6", "D6", "D#6", "E6", "F6", "F#6", "G6", "G#6", "A6", "A#6", "B6",
|
|
||||||
"C7", "C#7", "D7", "D#7", "E7", "F7", "F#7", "G7", "G#7", "A7", "A#7", "B7",
|
|
||||||
"C8", "C#8", "D8", "D#8", "E8", "F8", "F#8", "G8", "G#8", "A8", "A#8", "B8",
|
|
||||||
"C9", "C#9", "D9", "D#9", "E9", "F9", "F#9", "G9", "G#9", "A9", "A#9", "B9",
|
|
||||||
"C10", "C#10", "D10", "D#10", "E10", "F10", "F#10", "G10",
|
|
||||||
];
|
|
||||||
|
|
||||||
impl LaunchSync {
|
|
||||||
pub fn next (&self) -> f64 {
|
|
||||||
note_duration_next(self.get() as usize) as f64
|
|
||||||
}
|
|
||||||
pub fn prev (&self) -> f64 {
|
|
||||||
note_duration_prev(self.get() as usize) as f64
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Quantize {
|
|
||||||
pub fn next (&self) -> f64 {
|
|
||||||
note_duration_next(self.get() as usize) as f64
|
|
||||||
}
|
|
||||||
pub fn prev (&self) -> f64 {
|
|
||||||
note_duration_prev(self.get() as usize) as f64
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Implement an arithmetic operation for a unit of time
|
|
||||||
#[macro_export] macro_rules! impl_op {
|
|
||||||
($T:ident, $Op:ident, $method:ident, |$a:ident,$b:ident|{$impl:expr}) => {
|
|
||||||
impl $Op<Self> for $T {
|
|
||||||
type Output = Self; #[inline] fn $method (self, other: Self) -> Self::Output {
|
|
||||||
let $a = self.get(); let $b = other.get(); Self($impl.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl $Op<usize> for $T {
|
|
||||||
type Output = Self; #[inline] fn $method (self, other: usize) -> Self::Output {
|
|
||||||
let $a = self.get(); let $b = other as f64; Self($impl.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl $Op<f64> for $T {
|
|
||||||
type Output = Self; #[inline] fn $method (self, other: f64) -> Self::Output {
|
|
||||||
let $a = self.get(); let $b = other; Self($impl.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for Clock {
|
|
||||||
fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
|
||||||
f.debug_struct("Clock")
|
|
||||||
.field("timebase", &self.timebase)
|
|
||||||
.field("chunk", &self.chunk)
|
|
||||||
.field("quant", &self.quant)
|
|
||||||
.field("sync", &self.sync)
|
|
||||||
.field("global", &self.global)
|
|
||||||
.field("playhead", &self.playhead)
|
|
||||||
.field("started", &self.started)
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Clock {
|
|
||||||
pub fn new (jack: &Jack<'static>, bpm: Option<f64>) -> Usually<Self> {
|
|
||||||
let (chunk, transport) = jack.with_client(|c|(c.buffer_size(), c.transport()));
|
|
||||||
let timebase = Arc::new(Timebase::default());
|
|
||||||
let clock = Self {
|
|
||||||
quant: Arc::new(24.into()),
|
|
||||||
sync: Arc::new(384.into()),
|
|
||||||
transport: Arc::new(Some(transport)),
|
|
||||||
chunk: Arc::new((chunk as usize).into()),
|
|
||||||
global: Arc::new(Moment::zero(&timebase)),
|
|
||||||
playhead: Arc::new(Moment::zero(&timebase)),
|
|
||||||
offset: Arc::new(Moment::zero(&timebase)),
|
|
||||||
started: RwLock::new(None).into(),
|
|
||||||
timebase,
|
|
||||||
midi_in: Arc::new(RwLock::new(Some(MidiInput::new(jack, &"M/clock", &[])?))),
|
|
||||||
midi_out: Arc::new(RwLock::new(Some(MidiOutput::new(jack, &"clock/M", &[])?))),
|
|
||||||
click_out: Arc::new(RwLock::new(Some(AudioOutput::new(jack, &"click", &[])?))),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
if let Some(bpm) = bpm {
|
|
||||||
clock.timebase.bpm.set(bpm);
|
|
||||||
}
|
|
||||||
Ok(clock)
|
|
||||||
}
|
|
||||||
pub fn timebase (&self) -> &Arc<Timebase> {
|
|
||||||
&self.timebase
|
|
||||||
}
|
|
||||||
/// Current sample rate
|
|
||||||
pub fn sr (&self) -> &SampleRate {
|
|
||||||
&self.timebase.sr
|
|
||||||
}
|
|
||||||
/// Current tempo
|
|
||||||
pub fn bpm (&self) -> &Bpm {
|
|
||||||
&self.timebase.bpm
|
|
||||||
}
|
|
||||||
/// Current MIDI resolution
|
|
||||||
pub fn ppq (&self) -> &Ppq {
|
|
||||||
&self.timebase.ppq
|
|
||||||
}
|
|
||||||
/// Next pulse that matches launch sync (for phrase switchover)
|
|
||||||
pub fn next_launch_pulse (&self) -> usize {
|
|
||||||
let sync = self.sync.get() as usize;
|
|
||||||
let pulse = self.playhead.pulse.get() as usize;
|
|
||||||
if pulse % sync == 0 {
|
|
||||||
pulse
|
|
||||||
} else {
|
|
||||||
(pulse / sync + 1) * sync
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// Start playing, optionally seeking to a given location beforehand
|
|
||||||
pub fn play_from (&self, start: Option<u32>) -> Usually<()> {
|
|
||||||
if let Some(transport) = self.transport.as_ref() {
|
|
||||||
if let Some(start) = start {
|
|
||||||
transport.locate(start)?;
|
|
||||||
}
|
|
||||||
transport.start()?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
/// Pause, optionally seeking to a given location afterwards
|
|
||||||
pub fn pause_at (&self, pause: Option<u32>) -> Usually<()> {
|
|
||||||
if let Some(transport) = self.transport.as_ref() {
|
|
||||||
transport.stop()?;
|
|
||||||
if let Some(pause) = pause {
|
|
||||||
transport.locate(pause)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
/// Is currently paused?
|
|
||||||
pub fn is_stopped (&self) -> bool {
|
|
||||||
self.started.try_read().unwrap().is_none()
|
|
||||||
}
|
|
||||||
/// Is currently playing?
|
|
||||||
pub fn is_rolling (&self) -> bool {
|
|
||||||
self.started.try_read().unwrap().is_some()
|
|
||||||
}
|
|
||||||
/// Update chunk size
|
|
||||||
pub fn set_chunk (&self, n_frames: usize) {
|
|
||||||
self.chunk.store(n_frames, Relaxed);
|
|
||||||
}
|
|
||||||
pub fn update_from_scope (&self, scope: &ProcessScope) -> Usually<()> {
|
|
||||||
// Store buffer length
|
|
||||||
self.set_chunk(scope.n_frames() as usize);
|
|
||||||
|
|
||||||
// Store reported global frame and usec
|
|
||||||
let CycleTimes { current_frames, current_usecs, .. } = scope.cycle_times()?;
|
|
||||||
self.global.sample.set(current_frames as f64);
|
|
||||||
self.global.usec.set(current_usecs as f64);
|
|
||||||
|
|
||||||
let mut started = self.started.try_write().unwrap();
|
|
||||||
|
|
||||||
// If transport has just started or just stopped,
|
|
||||||
// update starting point:
|
|
||||||
if let Some(transport) = self.transport.as_ref() {
|
|
||||||
match (transport.query_state()?, started.as_ref()) {
|
|
||||||
(TransportState::Rolling, None) => {
|
|
||||||
let moment = Moment::zero(&self.timebase);
|
|
||||||
moment.sample.set(current_frames as f64);
|
|
||||||
moment.usec.set(current_usecs as f64);
|
|
||||||
*started = Some(moment);
|
|
||||||
},
|
|
||||||
(TransportState::Stopped, Some(_)) => {
|
|
||||||
*started = None;
|
|
||||||
},
|
|
||||||
_ => {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
self.playhead.update_from_sample(started.as_ref()
|
|
||||||
.map(|started|current_frames as f64 - started.sample.get())
|
|
||||||
.unwrap_or(0.));
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn bbt (&self) -> PositionBBT {
|
|
||||||
let pulse = self.playhead.pulse.get() as i32;
|
|
||||||
let ppq = self.timebase.ppq.get() as i32;
|
|
||||||
let bpm = self.timebase.bpm.get();
|
|
||||||
let bar = (pulse / ppq) / 4;
|
|
||||||
PositionBBT {
|
|
||||||
bar: 1 + bar,
|
|
||||||
beat: 1 + (pulse / ppq) % 4,
|
|
||||||
tick: (pulse % ppq),
|
|
||||||
bar_start_tick: (bar * 4 * ppq) as f64,
|
|
||||||
beat_type: 4.,
|
|
||||||
beats_per_bar: 4.,
|
|
||||||
beats_per_minute: bpm,
|
|
||||||
ticks_per_beat: ppq as f64
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn next_launch_instant (&self) -> Moment {
|
|
||||||
Moment::from_pulse(self.timebase(), self.next_launch_pulse() as f64)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get index of first sample to populate.
|
|
||||||
///
|
|
||||||
/// Greater than 0 means that the first pulse of the clip
|
|
||||||
/// falls somewhere in the middle of the chunk.
|
|
||||||
pub fn get_sample_offset (&self, scope: &ProcessScope, started: &Moment) -> usize{
|
|
||||||
(scope.last_frame_time() as usize).saturating_sub(
|
|
||||||
started.sample.get() as usize +
|
|
||||||
self.started.try_read().unwrap().as_ref().unwrap().sample.get() as usize
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get iterator that emits sample paired with pulse.
|
|
||||||
//
|
|
||||||
// * Sample: index into output buffer at which to write MIDI event
|
|
||||||
// * Pulse: index into clip from which to take the MIDI event
|
|
||||||
//
|
|
||||||
// Emitted for each sample of the output buffer that corresponds to a MIDI pulse.
|
|
||||||
pub fn get_pulses (&self, scope: &ProcessScope, offset: usize) -> Ticker {
|
|
||||||
self.timebase().pulses_between_samples(offset, offset + scope.n_frames() as usize)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Temporal resolutions: sample rate, tempo, MIDI pulses per quaver (beat)
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let _ = tek::Timebase::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Clone)] pub struct Timebase {
|
|
||||||
/// Audio samples per second
|
|
||||||
pub sr: SampleRate,
|
|
||||||
/// MIDI beats per minute
|
|
||||||
pub bpm: Bpm,
|
|
||||||
/// MIDI ticks per beat
|
|
||||||
pub ppq: Ppq,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Audio sample rate in Hz (samples per second)
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct SampleRate (pub(crate) AtomicF64);
|
|
||||||
|
|
||||||
/// Tempo in beats per minute
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct Bpm (pub(crate) AtomicF64);
|
|
||||||
|
|
||||||
/// MIDI resolution in PPQ (pulses per quarter note)
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct Ppq (pub(crate) AtomicF64);
|
|
||||||
|
|
||||||
impl Timebase {
|
|
||||||
/// Specify sample rate, BPM and PPQ
|
|
||||||
pub fn new (
|
|
||||||
s: impl Into<SampleRate>,
|
|
||||||
b: impl Into<Bpm>,
|
|
||||||
p: impl Into<Ppq>
|
|
||||||
) -> Self {
|
|
||||||
Self { sr: s.into(), bpm: b.into(), ppq: p.into() }
|
|
||||||
}
|
|
||||||
/// Iterate over ticks between start and end.
|
|
||||||
#[inline] pub fn pulses_between_samples (&self, start: usize, end: usize) -> Ticker {
|
|
||||||
Ticker { spp: self.samples_per_pulse(), sample: start, start, end }
|
|
||||||
}
|
|
||||||
/// Return the duration fo a beat in microseconds
|
|
||||||
#[inline] pub fn usec_per_beat (&self) -> f64 { 60_000_000f64 / self.bpm.get() }
|
|
||||||
/// Return the number of beats in a second
|
|
||||||
#[inline] pub fn beat_per_second (&self) -> f64 { self.bpm.get() / 60f64 }
|
|
||||||
/// Return the number of microseconds corresponding to a note of the given duration
|
|
||||||
#[inline] pub fn note_to_usec (&self, (num, den): (f64, f64)) -> f64 {
|
|
||||||
4.0 * self.usec_per_beat() * num / den
|
|
||||||
}
|
|
||||||
/// Return duration of a pulse in microseconds (BPM-dependent)
|
|
||||||
#[inline] pub fn pulse_per_usec (&self) -> f64 { self.ppq.get() / self.usec_per_beat() }
|
|
||||||
/// Return duration of a pulse in microseconds (BPM-dependent)
|
|
||||||
#[inline] pub fn usec_per_pulse (&self) -> f64 { self.usec_per_beat() / self.ppq.get() }
|
|
||||||
/// Return number of pulses to which a number of microseconds corresponds (BPM-dependent)
|
|
||||||
#[inline] pub fn usecs_to_pulse (&self, usec: f64) -> f64 { usec * self.pulse_per_usec() }
|
|
||||||
/// Convert a number of pulses to a sample number (SR- and BPM-dependent)
|
|
||||||
#[inline] pub fn pulses_to_usec (&self, pulse: f64) -> f64 { pulse / self.usec_per_pulse() }
|
|
||||||
/// Return number of pulses in a second (BPM-dependent)
|
|
||||||
#[inline] pub fn pulses_per_second (&self) -> f64 { self.beat_per_second() * self.ppq.get() }
|
|
||||||
/// Return fraction of a pulse to which a sample corresponds (SR- and BPM-dependent)
|
|
||||||
#[inline] pub fn pulses_per_sample (&self) -> f64 {
|
|
||||||
self.usec_per_pulse() / self.sr.usec_per_sample()
|
|
||||||
}
|
|
||||||
/// Return number of samples in a pulse (SR- and BPM-dependent)
|
|
||||||
#[inline] pub fn samples_per_pulse (&self) -> f64 {
|
|
||||||
self.sr.get() / self.pulses_per_second()
|
|
||||||
}
|
|
||||||
/// Convert a number of pulses to a sample number (SR- and BPM-dependent)
|
|
||||||
#[inline] pub fn pulses_to_sample (&self, p: f64) -> f64 {
|
|
||||||
self.pulses_per_sample() * p
|
|
||||||
}
|
|
||||||
/// Convert a number of samples to a pulse number (SR- and BPM-dependent)
|
|
||||||
#[inline] pub fn samples_to_pulse (&self, s: f64) -> f64 {
|
|
||||||
s / self.pulses_per_sample()
|
|
||||||
}
|
|
||||||
/// Return the number of samples corresponding to a note of the given duration
|
|
||||||
#[inline] pub fn note_to_samples (&self, note: (f64, f64)) -> f64 {
|
|
||||||
self.usec_to_sample(self.note_to_usec(note))
|
|
||||||
}
|
|
||||||
/// Return the number of samples corresponding to the given number of microseconds
|
|
||||||
#[inline] pub fn usec_to_sample (&self, usec: f64) -> f64 {
|
|
||||||
usec * self.sr.get() / 1000f64
|
|
||||||
}
|
|
||||||
/// Return the quantized position of a moment in time given a step
|
|
||||||
#[inline] pub fn quantize (&self, step: (f64, f64), time: f64) -> (f64, f64) {
|
|
||||||
let step = self.note_to_usec(step);
|
|
||||||
(time / step, time % step)
|
|
||||||
}
|
|
||||||
/// Quantize a collection of events
|
|
||||||
#[inline] pub fn quantize_into <E: Iterator<Item=(f64, f64)> + Sized, T> (
|
|
||||||
&self, step: (f64, f64), events: E
|
|
||||||
) -> Vec<(f64, f64)> {
|
|
||||||
events.map(|(time, event)|(self.quantize(step, time).0, event)).collect()
|
|
||||||
}
|
|
||||||
/// Format a number of pulses into Beat.Bar.Pulse starting from 0
|
|
||||||
#[inline] pub fn format_beats_0 (&self, pulse: f64) -> Arc<str> {
|
|
||||||
let pulse = pulse as usize;
|
|
||||||
let ppq = self.ppq.get() as usize;
|
|
||||||
let (beats, pulses) = if ppq > 0 { (pulse / ppq, pulse % ppq) } else { (0, 0) };
|
|
||||||
format!("{}.{}.{pulses:02}", beats / 4, beats % 4).into()
|
|
||||||
}
|
|
||||||
/// Format a number of pulses into Beat.Bar starting from 0
|
|
||||||
#[inline] pub fn format_beats_0_short (&self, pulse: f64) -> Arc<str> {
|
|
||||||
let pulse = pulse as usize;
|
|
||||||
let ppq = self.ppq.get() as usize;
|
|
||||||
let beats = if ppq > 0 { pulse / ppq } else { 0 };
|
|
||||||
format!("{}.{}", beats / 4, beats % 4).into()
|
|
||||||
}
|
|
||||||
/// Format a number of pulses into Beat.Bar.Pulse starting from 1
|
|
||||||
#[inline] pub fn format_beats_1 (&self, pulse: f64) -> Arc<str> {
|
|
||||||
let mut string = String::with_capacity(16);
|
|
||||||
self.format_beats_1_to(&mut string, pulse).expect("failed to format {pulse} into beat");
|
|
||||||
string.into()
|
|
||||||
}
|
|
||||||
/// Format a number of pulses into Beat.Bar.Pulse starting from 1
|
|
||||||
#[inline] pub fn format_beats_1_to (&self, w: &mut impl std::fmt::Write, pulse: f64) -> Result<(), std::fmt::Error> {
|
|
||||||
let pulse = pulse as usize;
|
|
||||||
let ppq = self.ppq.get() as usize;
|
|
||||||
let (beats, pulses) = if ppq > 0 { (pulse / ppq, pulse % ppq) } else { (0, 0) };
|
|
||||||
write!(w, "{}.{}.{pulses:02}", beats / 4 + 1, beats % 4 + 1)
|
|
||||||
}
|
|
||||||
/// Format a number of pulses into Beat.Bar.Pulse starting from 1
|
|
||||||
#[inline] pub fn format_beats_1_short (&self, pulse: f64) -> Arc<str> {
|
|
||||||
let pulse = pulse as usize;
|
|
||||||
let ppq = self.ppq.get() as usize;
|
|
||||||
let beats = if ppq > 0 { pulse / ppq } else { 0 };
|
|
||||||
format!("{}.{}", beats / 4 + 1, beats % 4 + 1).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SampleRate {
|
|
||||||
/// Return the duration of a sample in microseconds (floating)
|
|
||||||
#[inline] pub fn usec_per_sample (&self) -> f64 {
|
|
||||||
1_000_000f64 / self.get()
|
|
||||||
}
|
|
||||||
/// Return the duration of a sample in microseconds (floating)
|
|
||||||
#[inline] pub fn sample_per_usec (&self) -> f64 {
|
|
||||||
self.get() / 1_000_000f64
|
|
||||||
}
|
|
||||||
/// Convert a number of samples to microseconds (floating)
|
|
||||||
#[inline] pub fn samples_to_usec (&self, samples: f64) -> f64 {
|
|
||||||
self.usec_per_sample() * samples
|
|
||||||
}
|
|
||||||
/// Convert a number of microseconds to samples (floating)
|
|
||||||
#[inline] pub fn usecs_to_sample (&self, usecs: f64) -> f64 {
|
|
||||||
self.sample_per_usec() * usecs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A point in time in all time scales (microsecond, sample, MIDI pulse)
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let _ = tek::Moment::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default, Clone)] pub struct Moment {
|
|
||||||
pub timebase: Arc<Timebase>,
|
|
||||||
/// Current time in microseconds
|
|
||||||
pub usec: Microsecond,
|
|
||||||
/// Current time in audio samples
|
|
||||||
pub sample: SampleCount,
|
|
||||||
/// Current time in MIDI pulses
|
|
||||||
pub pulse: Pulse,
|
|
||||||
}
|
|
||||||
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let _ = tek::Moment2::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Clone, Default)] pub enum Moment2 {
|
|
||||||
#[default] None,
|
|
||||||
Zero,
|
|
||||||
Usec(Microsecond),
|
|
||||||
Sample(SampleCount),
|
|
||||||
Pulse(Pulse),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Timestamp in microseconds
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let _ = tek::Microsecond(0.0.into());
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct Microsecond (pub AtomicF64);
|
|
||||||
|
|
||||||
/// Timestamp in audio samples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let _ = tek::SampleCount(0.0.into());
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct SampleCount (pub AtomicF64);
|
|
||||||
|
|
||||||
/// Timestamp in MIDI pulses
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let _ = tek::Pulse(0.0.into());
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct Pulse (pub AtomicF64);
|
|
||||||
|
|
||||||
impl Moment {
|
|
||||||
pub fn zero (timebase: &Arc<Timebase>) -> Self {
|
|
||||||
Self { usec: 0.into(), sample: 0.into(), pulse: 0.into(), timebase: timebase.clone() }
|
|
||||||
}
|
|
||||||
pub fn from_usec (timebase: &Arc<Timebase>, usec: f64) -> Self {
|
|
||||||
Self {
|
|
||||||
usec: usec.into(),
|
|
||||||
sample: timebase.sr.usecs_to_sample(usec).into(),
|
|
||||||
pulse: timebase.usecs_to_pulse(usec).into(),
|
|
||||||
timebase: timebase.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn from_sample (timebase: &Arc<Timebase>, sample: f64) -> Self {
|
|
||||||
Self {
|
|
||||||
sample: sample.into(),
|
|
||||||
usec: timebase.sr.samples_to_usec(sample).into(),
|
|
||||||
pulse: timebase.samples_to_pulse(sample).into(),
|
|
||||||
timebase: timebase.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn from_pulse (timebase: &Arc<Timebase>, pulse: f64) -> Self {
|
|
||||||
Self {
|
|
||||||
pulse: pulse.into(),
|
|
||||||
sample: timebase.pulses_to_sample(pulse).into(),
|
|
||||||
usec: timebase.pulses_to_usec(pulse).into(),
|
|
||||||
timebase: timebase.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[inline] pub fn update_from_usec (&self, usec: f64) {
|
|
||||||
self.usec.set(usec);
|
|
||||||
self.pulse.set(self.timebase.usecs_to_pulse(usec));
|
|
||||||
self.sample.set(self.timebase.sr.usecs_to_sample(usec));
|
|
||||||
}
|
|
||||||
#[inline] pub fn update_from_sample (&self, sample: f64) {
|
|
||||||
self.usec.set(self.timebase.sr.samples_to_usec(sample));
|
|
||||||
self.pulse.set(self.timebase.samples_to_pulse(sample));
|
|
||||||
self.sample.set(sample);
|
|
||||||
}
|
|
||||||
#[inline] pub fn update_from_pulse (&self, pulse: f64) {
|
|
||||||
self.usec.set(self.timebase.pulses_to_usec(pulse));
|
|
||||||
self.pulse.set(pulse);
|
|
||||||
self.sample.set(self.timebase.pulses_to_sample(pulse));
|
|
||||||
}
|
|
||||||
#[inline] pub fn format_beat (&self) -> Arc<str> {
|
|
||||||
self.timebase.format_beats_1(self.pulse.get()).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Microsecond {
|
|
||||||
#[inline] pub fn format_msu (&self) -> Arc<str> {
|
|
||||||
let usecs = self.get() as usize;
|
|
||||||
let (seconds, msecs) = (usecs / 1000000, usecs / 1000 % 1000);
|
|
||||||
let (minutes, seconds) = (seconds / 60, seconds % 60);
|
|
||||||
format!("{minutes}:{seconds:02}:{msecs:03}").into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterator that emits subsequent ticks within a range.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let iter = tek::Ticker::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Debug, Default)] pub struct Ticker {
|
|
||||||
pub spp: f64,
|
|
||||||
pub sample: usize,
|
|
||||||
pub start: usize,
|
|
||||||
pub end: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Iterator for Ticker {
|
|
||||||
type Item = (usize, usize);
|
|
||||||
fn next (&mut self) -> Option<Self::Item> {
|
|
||||||
loop {
|
|
||||||
if self.sample > self.end { return None }
|
|
||||||
let spp = self.spp;
|
|
||||||
let sample = self.sample as f64;
|
|
||||||
let start = self.start;
|
|
||||||
let end = self.end;
|
|
||||||
self.sample += 1;
|
|
||||||
//println!("{spp} {sample} {start} {end}");
|
|
||||||
let jitter = sample.rem_euclid(spp); // ramps
|
|
||||||
let next_jitter = (sample + 1.0).rem_euclid(spp);
|
|
||||||
if jitter > next_jitter { // at crossing:
|
|
||||||
let time = (sample as usize) % (end as usize-start as usize);
|
|
||||||
let tick = (sample / spp) as usize;
|
|
||||||
return Some((time, tick))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Contains state for playing a clip
|
/// Contains state for playing a clip
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
|
@ -1752,59 +1135,72 @@ impl std::fmt::Debug for PianoHorizontal {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//impl App {
|
/// Has a MIDI editor.
|
||||||
///// Toggle MIDI editor.
|
///
|
||||||
/////
|
/// ```
|
||||||
///// ```
|
/// use tek::{*, tengri::*};
|
||||||
///// tek::App::default().toggle_editor(None);
|
///
|
||||||
///// ```
|
/// struct Test(Option<MidiEditor>);
|
||||||
//pub fn toggle_editor (&mut self, value: Option<bool>) {
|
/// impl_as_ref!(Option<MidiEditor>: |self: Test|&self.0);
|
||||||
////FIXME: self.editing.store(value.unwrap_or_else(||!self.is_editing()), Relaxed);
|
/// impl_as_mut!(Option<MidiEditor>: |self: Test|&mut self.0);
|
||||||
//if value.unwrap_or_else(||!self.editor().is_some()) {
|
///
|
||||||
//self.toggle_editor_on()
|
/// let mut host = Test(Some(MidiEditor::default()));
|
||||||
//} else {
|
/// let _ = host.editor();
|
||||||
//self.toggle_editor_off()
|
/// let _ = host.editor_mut();
|
||||||
//}
|
/// let _ = host.is_editing();
|
||||||
//}
|
/// let _ = host.editor_w();
|
||||||
|
/// let _ = host.editor_h();
|
||||||
|
/// ```
|
||||||
|
impl<T> HasEditor for T where T:
|
||||||
|
AsRef<Option<MidiEditor>> + AsMut<Option<MidiEditor>> {}
|
||||||
|
pub trait HasEditor:
|
||||||
|
AsRef<Option<MidiEditor>> + AsMut<Option<MidiEditor>>
|
||||||
|
{
|
||||||
|
fn editor (&self) -> &Option<MidiEditor> {
|
||||||
|
self.as_ref()
|
||||||
|
}
|
||||||
|
fn editor_mut (&mut self) -> &mut Option<MidiEditor> {
|
||||||
|
self.as_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//fn toggle_editor_on (&mut self) {
|
/// Has a pair of buffers for MIDI IO.
|
||||||
//// Create new clip in pool when entering empty cell
|
pub trait HasMidiBuffers {
|
||||||
//if let Selection::TrackClip { track: track_index, scene } = *self.selection()
|
fn note_buf_mut (&mut self) -> &mut Vec<u8>;
|
||||||
//&& let Some(scene) = self.project.scenes.get_mut(scene)
|
fn midi_buf_mut (&mut self) -> &mut Vec<Vec<Vec<u8>>>;
|
||||||
//&& scene.clips.get(track_index).is_none()
|
}
|
||||||
//&& let Some(track) = self.project.tracks.get_mut(track_index)
|
|
||||||
//{
|
|
||||||
//let color = track.color.base.mix(scene.color.base, 0.5);
|
|
||||||
//let color = ItemColor::random_near(color, 0.2).into();
|
|
||||||
//let clip: MidiClip = MidiClip { color, ..Default::default() };
|
|
||||||
//let clip = self.project.clips.append(Some(clip));
|
|
||||||
//// autocolor: new clip colors from scene and track color
|
|
||||||
//if let Some(editor) = &mut self.project.editor {
|
|
||||||
//*editor.mode.clip.write() = clip.0.read().clone();
|
|
||||||
//editor.mode.color = clip.0.read().as_ref().map(|p|p.read().color)
|
|
||||||
//.unwrap_or(ItemTheme::G[64]);
|
|
||||||
//}
|
|
||||||
//*scene.clips.slot(track_index).write() = clip.0.read().clone();
|
|
||||||
////Some(clip)
|
|
||||||
//} else {
|
|
||||||
////None
|
|
||||||
//}
|
|
||||||
//}
|
|
||||||
|
|
||||||
//fn toggle_editor_off (&mut self) {
|
/// Can have a currently playing clip.
|
||||||
//if let Selection::TrackClip { track, scene } = *self.selection()
|
pub trait HasPlayClip: HasClock {
|
||||||
//&& let Some(scene) = self.project.scenes.get_mut(scene)
|
fn reset (&self) -> bool;
|
||||||
//{
|
fn reset_mut (&mut self) -> &mut bool;
|
||||||
//// Remove clip from arrangement when exiting empty clip editor
|
fn play_clip (&self) -> &Option<(Moment, Option<Arc<RwLock<MidiClip>>>)>;
|
||||||
//let mut swapped = None;
|
fn play_clip_mut (&mut self) -> &mut Option<(Moment, Option<Arc<RwLock<MidiClip>>>)>;
|
||||||
//if let Some(count) = scene.clips.slot(track).read().as_ref().map(|c|c.read().count_midi_messages())
|
fn next_clip (&self) -> &Option<(Moment, Option<Arc<RwLock<MidiClip>>>)>;
|
||||||
//&& count == 0
|
fn next_clip_mut (&mut self) -> &mut Option<(Moment, Option<Arc<RwLock<MidiClip>>>)>;
|
||||||
//{
|
}
|
||||||
//std::mem::swap(&mut swapped, &mut scene.clips.slot(track).write());
|
|
||||||
//}
|
/// Has a MIDI sequencer.
|
||||||
//if let Some(clip) = swapped {
|
impl <T> HasSequencer for T where T: AsRef<Sequencer> + AsMut<Sequencer> {}
|
||||||
//self.project.clips.remove(&*clip.read());
|
pub trait HasSequencer: AsRef<Sequencer> + AsMut<Sequencer> {
|
||||||
//}
|
fn sequencer (&self) -> &Sequencer {
|
||||||
//}
|
self.as_ref()
|
||||||
//}
|
}
|
||||||
//}
|
fn sequencer_mut (&mut self) -> &mut Sequencer {
|
||||||
|
self.as_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub trait HasClip {
|
||||||
|
fn clip_slot (&self) -> Option<Slot<MidiClip>>;
|
||||||
|
fn clip (&self) -> Option<ArcRwLockReadGuard<RawRwLock, Option<Arc<RwLock<MidiClip>>>>> {
|
||||||
|
self.clip_slot().map(|slot|slot.read())
|
||||||
|
}
|
||||||
|
fn clip_mut (&self) -> Option<ArcRwLockWriteGuard<RawRwLock, Option<Arc<RwLock<MidiClip>>>>> {
|
||||||
|
self.clip_slot().map(|slot|slot.write())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl HasClip for App {
|
||||||
|
fn clip_slot (&self) -> Option<Slot<MidiClip>> {
|
||||||
|
self.project.clip_slot()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
111
src/proj/scene.rs
Normal file
111
src/proj/scene.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
use crate::*;
|
||||||
|
|
||||||
|
/// A scene consists of a set of clips to play together.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let scene: tek::Scene = Default::default();
|
||||||
|
/// let _ = scene.pulses();
|
||||||
|
/// let _ = scene.is_playing(&[]);
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Scene {
|
||||||
|
/// Name of scene
|
||||||
|
pub name: Arc<str>,
|
||||||
|
/// Identifying color of scene
|
||||||
|
pub color: ItemTheme,
|
||||||
|
/// Clips in scene, one per track
|
||||||
|
pub clips: Pool<MidiClip>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scene {
|
||||||
|
pub const DEFAULT_HEIGHT: usize = 2;
|
||||||
|
/// Get pulse length of the longest clip in the scene
|
||||||
|
pub fn pulses (&self) -> usize {
|
||||||
|
self.clips.read().iter().fold(0, |a, p|{
|
||||||
|
a.max(p.read().as_ref().map(|q|q.read().length).unwrap_or(0))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// True if all clips in scene are currently playing on given tracks.
|
||||||
|
pub fn is_playing (&self, tracks: &[Track]) -> bool {
|
||||||
|
// Not "playing" if there are no clips
|
||||||
|
if !self.clips.read().iter().any(|clip|clip.read().is_some()) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Playing if at least 1 clip is playing
|
||||||
|
self.clips.read().iter().enumerate().all(|(track_index, clip)|match &*clip.read() {
|
||||||
|
Some(c) => tracks
|
||||||
|
.get(track_index)
|
||||||
|
.map(|track|{
|
||||||
|
if let Some((_, Some(clip))) = track.sequencer().play_clip() {
|
||||||
|
*clip.read() == *c.read()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or(false),
|
||||||
|
None => true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HasScenes {
|
||||||
|
fn scenes (&self) -> &Vec<Scene>;
|
||||||
|
fn scenes_mut (&mut self) -> &mut Vec<Scene>;
|
||||||
|
fn scenes_scroll (&self) -> usize {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl HasScenes for Project {
|
||||||
|
fn scenes_scroll (&self) -> usize {
|
||||||
|
self.scenes_scroll
|
||||||
|
}
|
||||||
|
fn scenes (&self) -> &Vec<Scene> {
|
||||||
|
&self.scenes
|
||||||
|
}
|
||||||
|
fn scenes_mut (&mut self) -> &mut Vec<Scene> {
|
||||||
|
&mut self.scenes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl HasScenes for App {
|
||||||
|
fn scenes_scroll (&self) -> usize {
|
||||||
|
self.project.scenes_scroll()
|
||||||
|
}
|
||||||
|
fn scenes (&self) -> &Vec<Scene> {
|
||||||
|
self.project.scenes()
|
||||||
|
}
|
||||||
|
fn scenes_mut (&mut self) -> &mut Vec<Scene> {
|
||||||
|
self.project.scenes_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HasScene: AsRefOpt<Scene> + AsMutOpt<Scene> {
|
||||||
|
fn scene (&self) -> Option<&Scene> {
|
||||||
|
self.as_ref_opt()
|
||||||
|
}
|
||||||
|
fn scene_mut (&mut self) -> Option<&mut Scene> {
|
||||||
|
self.as_mut_opt()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> HasScene for T where T: AsRefOpt<Scene> + AsMutOpt<Scene> + Send + Sync {}
|
||||||
|
|
||||||
|
impl ScenesView for App {
|
||||||
|
fn w_mid (&self) -> u16 {
|
||||||
|
(self.size.w() as u16).saturating_sub(self.w_side())
|
||||||
|
}
|
||||||
|
fn w_side (&self) -> u16 {
|
||||||
|
20
|
||||||
|
}
|
||||||
|
fn h_scenes (&self) -> u16 {
|
||||||
|
(self.size.h() as u16).saturating_sub(20)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl ScenesView for Project {
|
||||||
|
fn h_scenes (&self) -> u16 {
|
||||||
|
(self.size.h() as u16).saturating_sub(20)
|
||||||
|
}
|
||||||
|
fn w_side (&self) -> u16 {
|
||||||
|
(self.size.w() as u16 * 2 / 10).max(20)
|
||||||
|
}
|
||||||
|
fn w_mid (&self) -> u16 {
|
||||||
|
(self.size.w() as u16).saturating_sub(2 * self.w_side()).max(40)
|
||||||
|
}
|
||||||
|
}
|
||||||
183
src/proj/select.rs
Normal file
183
src/proj/select.rs
Normal file
|
|
@ -0,0 +1,183 @@
|
||||||
|
use crate::*;
|
||||||
|
|
||||||
|
impl<T> HasSelection for T where T: AsRef<Selection> + AsMut<Selection> {}
|
||||||
|
pub trait HasSelection: AsRef<Selection> + AsMut<Selection> {
|
||||||
|
fn selection (&self) -> &Selection {
|
||||||
|
self.as_ref()
|
||||||
|
}
|
||||||
|
fn selection_mut (&mut self) -> &mut Selection {
|
||||||
|
self.as_mut()
|
||||||
|
}
|
||||||
|
/// Get the active track
|
||||||
|
#[cfg(feature = "track")] fn selected_track (&self) -> Option<&Track> where Self: HasTracks {
|
||||||
|
let index = self.selection().track()?;
|
||||||
|
self.tracks().get(index)
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the active track
|
||||||
|
#[cfg(feature = "track")] fn selected_track_mut (&mut self) -> Option<&mut Track> where Self: HasTracks {
|
||||||
|
let index = self.selection().track()?;
|
||||||
|
self.tracks_mut().get_mut(index)
|
||||||
|
}
|
||||||
|
/// Get the active scene
|
||||||
|
#[cfg(feature = "scene")] fn selected_scene (&self) -> Option<&Scene> where Self: HasScenes {
|
||||||
|
let index = self.selection().scene()?;
|
||||||
|
self.scenes().get(index)
|
||||||
|
}
|
||||||
|
/// Get a mutable reference to the active scene
|
||||||
|
#[cfg(feature = "scene")] fn selected_scene_mut (&mut self) -> Option<&mut Scene> where Self: HasScenes {
|
||||||
|
let index = self.selection().scene()?;
|
||||||
|
self.scenes_mut().get_mut(index)
|
||||||
|
}
|
||||||
|
/// Get the active clip
|
||||||
|
#[cfg(feature = "clip")] fn selected_clip (&self) -> Option<Slot<MidiClip>> where Self: HasScenes + HasTracks {
|
||||||
|
self.selected_scene()?.clips.read().get(self.selection().track()?).cloned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the current user selection in the arranger
|
||||||
|
#[derive(PartialEq, Clone, Copy, Debug, Default)]
|
||||||
|
pub enum Selection {
|
||||||
|
#[default]
|
||||||
|
/// Nothing is selected
|
||||||
|
Nothing,
|
||||||
|
/// The whole mix is selected
|
||||||
|
Mix,
|
||||||
|
/// A MIDI input is selected.
|
||||||
|
Input(usize),
|
||||||
|
/// A MIDI output is selected.
|
||||||
|
Output(usize),
|
||||||
|
/// A clip is selected.
|
||||||
|
Clip(usize),
|
||||||
|
/// A sample is selected.
|
||||||
|
Sample(usize),
|
||||||
|
/// A scene is selected.
|
||||||
|
#[cfg(feature = "scene")] Scene(usize),
|
||||||
|
/// A track is selected.
|
||||||
|
#[cfg(feature = "track")] Track(usize),
|
||||||
|
/// A clip slot (track × scene) is selected.
|
||||||
|
#[cfg(feature = "track")] TrackClip { track: usize, scene: usize },
|
||||||
|
/// A track's MIDI input connection is selected.
|
||||||
|
#[cfg(feature = "track")] TrackInput { track: usize, port: usize },
|
||||||
|
/// A track's MIDI output connection is selected.
|
||||||
|
#[cfg(feature = "track")] TrackOutput { track: usize, port: usize },
|
||||||
|
/// A track device slot is selected.
|
||||||
|
#[cfg(feature = "track")] TrackDevice { track: usize, device: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Selection {
|
||||||
|
|
||||||
|
pub fn describe (
|
||||||
|
&self,
|
||||||
|
#[cfg(feature = "track")] tracks: &[Track],
|
||||||
|
#[cfg(feature = "scene")] scenes: &[Scene],
|
||||||
|
) -> Arc<str> {
|
||||||
|
use Selection::*;
|
||||||
|
format!("{}", match self {
|
||||||
|
Mix => "Everything".to_string(),
|
||||||
|
#[cfg(feature = "scene")] Scene(s) =>
|
||||||
|
scenes.get(*s).map(|scene|format!("S{s}: {}", &scene.name)).unwrap_or_else(||"S??".into()),
|
||||||
|
#[cfg(feature = "track")] Track(t) =>
|
||||||
|
tracks.get(*t).map(|track|format!("T{t}: {}", &track.name)).unwrap_or_else(||"T??".into()),
|
||||||
|
TrackClip { track, scene } => match (tracks.get(*track), scenes.get(*scene)) {
|
||||||
|
(Some(_), Some(s)) => match &s.clips.get(*track) {
|
||||||
|
None => format!("T{track} S{scene}: Empty"),
|
||||||
|
Some(clip) => format!("T{track} S{scene} C{}",
|
||||||
|
clip.as_ref().map(|clip|clip.read().name.clone()).unwrap_or_default()),
|
||||||
|
},
|
||||||
|
_ => format!("T{track} S{scene}: Empty"),
|
||||||
|
},
|
||||||
|
_ => todo!()
|
||||||
|
}).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "scene")]
|
||||||
|
pub fn scene (&self) -> Option<usize> {
|
||||||
|
use Selection::*;
|
||||||
|
match self { Scene(scene) | TrackClip { scene, .. } => Some(*scene), _ => None }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "scene")]
|
||||||
|
pub fn select_scene (&self, scene_count: usize) -> Self {
|
||||||
|
use Selection::*;
|
||||||
|
match self {
|
||||||
|
Mix | Track(_) => Scene(0),
|
||||||
|
Scene(s) => Scene((s + 1) % scene_count),
|
||||||
|
TrackClip { scene, .. } => Track(*scene),
|
||||||
|
_ => todo!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "scene")]
|
||||||
|
pub fn select_scene_next (&self, len: usize) -> Self {
|
||||||
|
use Selection::*;
|
||||||
|
match self {
|
||||||
|
Mix => Scene(0),
|
||||||
|
Track(t) => TrackClip { track: *t, scene: 0 },
|
||||||
|
Scene(s) => if s + 1 < len { Scene(s + 1) } else { Mix },
|
||||||
|
TrackClip { track, scene } => if scene + 1 < len { TrackClip { track: *track, scene: scene + 1 } } else { Track(*track) },
|
||||||
|
_ => todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "scene")]
|
||||||
|
pub fn select_scene_prev (&self) -> Self {
|
||||||
|
use Selection::*;
|
||||||
|
match self {
|
||||||
|
Mix | Scene(0) => Mix,
|
||||||
|
Scene(s) => Scene(s - 1),
|
||||||
|
Track(t) => Track(*t),
|
||||||
|
TrackClip { track, scene: 0 } => Track(*track),
|
||||||
|
TrackClip { track, scene } => TrackClip { track: *track, scene: scene - 1 },
|
||||||
|
_ => todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "track")]
|
||||||
|
pub fn track (&self) -> Option<usize> {
|
||||||
|
use Selection::*;
|
||||||
|
if let Track(track)|TrackClip{track,..}|TrackInput{track,..}|TrackOutput{track,..}|TrackDevice{track,..} = self {
|
||||||
|
Some(*track)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "track")]
|
||||||
|
pub fn select_track (&self, track_count: usize) -> Self {
|
||||||
|
use Selection::*;
|
||||||
|
match self {
|
||||||
|
Mix => Track(0),
|
||||||
|
Scene(_) => Mix,
|
||||||
|
Track(t) => Track((t + 1) % track_count),
|
||||||
|
TrackClip { track, .. } => Track(*track),
|
||||||
|
_ => todo!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "track")]
|
||||||
|
pub fn select_track_next (&self, len: usize) -> Self {
|
||||||
|
use Selection::*;
|
||||||
|
match self {
|
||||||
|
Mix => Track(0),
|
||||||
|
Scene(s) => TrackClip { track: 0, scene: *s },
|
||||||
|
Track(t) => if t + 1 < len { Track(t + 1) } else { Mix },
|
||||||
|
TrackClip {track, scene} => if track + 1 < len { TrackClip { track: track + 1, scene: *scene } } else { Scene(*scene) },
|
||||||
|
_ => todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "track")]
|
||||||
|
pub fn select_track_prev (&self) -> Self {
|
||||||
|
use Selection::*;
|
||||||
|
match self {
|
||||||
|
Mix => Mix,
|
||||||
|
Scene(s) => Scene(*s),
|
||||||
|
Track(0) => Mix,
|
||||||
|
Track(t) => Track(t - 1),
|
||||||
|
TrackClip { track: 0, scene } => Scene(*scene),
|
||||||
|
TrackClip { track: t, scene } => TrackClip { track: t - 1, scene: *scene },
|
||||||
|
_ => todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
670
src/proj/time.rs
Normal file
670
src/proj/time.rs
Normal file
|
|
@ -0,0 +1,670 @@
|
||||||
|
use crate::*;
|
||||||
|
|
||||||
|
impl_has!(Clock: |self: App| self.project.clock);
|
||||||
|
impl_has!(Clock: |self: Project| self.clock);
|
||||||
|
impl_has!(Clock: |self: Track| self.sequencer.clock);
|
||||||
|
|
||||||
|
impl<T> HasClock for T where T: AsRef<Clock> + AsMut<Clock> {}
|
||||||
|
|
||||||
|
/// Has a clock.
|
||||||
|
pub trait HasClock: AsRef<Clock> + AsMut<Clock> {
|
||||||
|
fn clock (&self) -> &Clock {
|
||||||
|
self.as_ref()
|
||||||
|
}
|
||||||
|
fn clock_mut (&mut self) -> &mut Clock {
|
||||||
|
self.as_mut()
|
||||||
|
}
|
||||||
|
/// Update memoized render of clock values.
|
||||||
|
/// ```
|
||||||
|
/// # use tek::*;
|
||||||
|
/// App::default().clock_update();
|
||||||
|
/// ```
|
||||||
|
fn clock_update (&self) where Self: AsRef<Sizer> {
|
||||||
|
let clock = self.clock();
|
||||||
|
let sizer: &Sizer = self.as_ref();
|
||||||
|
ClockView::update_clock(&clock.view_cache, clock, sizer.w() > 80)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The source of time.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let clock = tek::Clock::default();
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Default)] pub struct Clock {
|
||||||
|
/// JACK transport handle.
|
||||||
|
pub transport: Arc<Option<Transport>>,
|
||||||
|
/// Global temporal resolution (shared by [Moment] fields)
|
||||||
|
pub timebase: Arc<Timebase>,
|
||||||
|
/// Current global sample and usec (monotonic from JACK clock)
|
||||||
|
pub global: Arc<Moment>,
|
||||||
|
/// Global sample and usec at which playback started
|
||||||
|
pub started: Arc<RwLock<Option<Moment>>>,
|
||||||
|
/// Playback offset (when playing not from start)
|
||||||
|
pub offset: Arc<Moment>,
|
||||||
|
/// Current playhead position
|
||||||
|
pub playhead: Arc<Moment>,
|
||||||
|
/// Note quantization factor
|
||||||
|
pub quant: Arc<Quantize>,
|
||||||
|
/// Launch quantization factor
|
||||||
|
pub sync: Arc<LaunchSync>,
|
||||||
|
/// Size of buffer in samples
|
||||||
|
pub chunk: Arc<AtomicUsize>,
|
||||||
|
// Cache of formatted strings
|
||||||
|
pub view_cache: Arc<RwLock<ClockView>>,
|
||||||
|
/// For syncing the clock to an external source
|
||||||
|
#[cfg(feature = "port")] pub midi_in: Arc<RwLock<Option<MidiInput>>>,
|
||||||
|
/// For syncing other devices to this clock
|
||||||
|
#[cfg(feature = "port")] pub midi_out: Arc<RwLock<Option<MidiOutput>>>,
|
||||||
|
/// For emitting a metronome
|
||||||
|
#[cfg(feature = "port")] pub click_out: Arc<RwLock<Option<AudioOutput>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
//impl<T: HasClock> Act<T> for ClockCmd {
|
||||||
|
//fn act (&self, state: &mut T) -> Perhaps<Self> {
|
||||||
|
//self.act(state.clock_mut()) // awesome
|
||||||
|
//}
|
||||||
|
//}
|
||||||
|
|
||||||
|
/// Quantization setting for launching clips
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct LaunchSync (pub(crate) AtomicF64);
|
||||||
|
|
||||||
|
/// Quantization setting for notes
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Quantize (pub(crate) AtomicF64);
|
||||||
|
|
||||||
|
/// A unit of time, represented as an atomic 64-bit float.
|
||||||
|
///
|
||||||
|
/// According to https://stackoverflow.com/a/873367, as per IEEE754,
|
||||||
|
/// every integer between 1 and 2^53 can be represented exactly.
|
||||||
|
/// This should mean that, even at 192kHz sampling rate, over 1 year of audio
|
||||||
|
/// can be clocked in microseconds with f64 without losing precision.
|
||||||
|
pub trait TimeUnit {}
|
||||||
|
|
||||||
|
pub const DEFAULT_PPQ: f64 = 96.0;
|
||||||
|
|
||||||
|
/// FIXME: remove this and use PPQ from timebase everywhere:
|
||||||
|
pub const PPQ: usize = 96;
|
||||||
|
|
||||||
|
/// (pulses, name), assuming 96 PPQ
|
||||||
|
pub const NOTE_DURATIONS: [(usize, &str);26] = [
|
||||||
|
(1, "1/384"), (2, "1/192"),
|
||||||
|
(3, "1/128"), (4, "1/96"),
|
||||||
|
(6, "1/64"), (8, "1/48"),
|
||||||
|
(12, "1/32"), (16, "1/24"),
|
||||||
|
(24, "1/16"), (32, "1/12"),
|
||||||
|
(48, "1/8"), (64, "1/6"),
|
||||||
|
(96, "1/4"), (128, "1/3"),
|
||||||
|
(192, "1/2"), (256, "2/3"),
|
||||||
|
(384, "1/1"), (512, "4/3"),
|
||||||
|
(576, "3/2"), (768, "2/1"),
|
||||||
|
(1152, "3/1"), (1536, "4/1"),
|
||||||
|
(2304, "6/1"), (3072, "8/1"),
|
||||||
|
(3456, "9/1"), (6144, "16/1"),
|
||||||
|
];
|
||||||
|
|
||||||
|
pub const NOTE_NAMES: [&str; 128] = [
|
||||||
|
"C0", "C#0", "D0", "D#0", "E0", "F0", "F#0", "G0", "G#0", "A0", "A#0", "B0",
|
||||||
|
"C1", "C#1", "D1", "D#1", "E1", "F1", "F#1", "G1", "G#1", "A1", "A#1", "B1",
|
||||||
|
"C2", "C#2", "D2", "D#2", "E2", "F2", "F#2", "G2", "G#2", "A2", "A#2", "B2",
|
||||||
|
"C3", "C#3", "D3", "D#3", "E3", "F3", "F#3", "G3", "G#3", "A3", "A#3", "B3",
|
||||||
|
"C4", "C#4", "D4", "D#4", "E4", "F4", "F#4", "G4", "G#4", "A4", "A#4", "B4",
|
||||||
|
"C5", "C#5", "D5", "D#5", "E5", "F5", "F#5", "G5", "G#5", "A5", "A#5", "B5",
|
||||||
|
"C6", "C#6", "D6", "D#6", "E6", "F6", "F#6", "G6", "G#6", "A6", "A#6", "B6",
|
||||||
|
"C7", "C#7", "D7", "D#7", "E7", "F7", "F#7", "G7", "G#7", "A7", "A#7", "B7",
|
||||||
|
"C8", "C#8", "D8", "D#8", "E8", "F8", "F#8", "G8", "G#8", "A8", "A#8", "B8",
|
||||||
|
"C9", "C#9", "D9", "D#9", "E9", "F9", "F#9", "G9", "G#9", "A9", "A#9", "B9",
|
||||||
|
"C10", "C#10", "D10", "D#10", "E10", "F10", "F#10", "G10",
|
||||||
|
];
|
||||||
|
|
||||||
|
impl LaunchSync {
|
||||||
|
pub fn next (&self) -> f64 {
|
||||||
|
note_duration_next(self.get() as usize) as f64
|
||||||
|
}
|
||||||
|
pub fn prev (&self) -> f64 {
|
||||||
|
note_duration_prev(self.get() as usize) as f64
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Quantize {
|
||||||
|
pub fn next (&self) -> f64 {
|
||||||
|
note_duration_next(self.get() as usize) as f64
|
||||||
|
}
|
||||||
|
pub fn prev (&self) -> f64 {
|
||||||
|
note_duration_prev(self.get() as usize) as f64
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implement an arithmetic operation for a unit of time
|
||||||
|
#[macro_export] macro_rules! impl_op {
|
||||||
|
($T:ident, $Op:ident, $method:ident, |$a:ident,$b:ident|{$impl:expr}) => {
|
||||||
|
impl $Op<Self> for $T {
|
||||||
|
type Output = Self; #[inline] fn $method (self, other: Self) -> Self::Output {
|
||||||
|
let $a = self.get(); let $b = other.get(); Self($impl.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl $Op<usize> for $T {
|
||||||
|
type Output = Self; #[inline] fn $method (self, other: usize) -> Self::Output {
|
||||||
|
let $a = self.get(); let $b = other as f64; Self($impl.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl $Op<f64> for $T {
|
||||||
|
type Output = Self; #[inline] fn $method (self, other: f64) -> Self::Output {
|
||||||
|
let $a = self.get(); let $b = other; Self($impl.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Clock {
|
||||||
|
fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||||
|
f.debug_struct("Clock")
|
||||||
|
.field("timebase", &self.timebase)
|
||||||
|
.field("chunk", &self.chunk)
|
||||||
|
.field("quant", &self.quant)
|
||||||
|
.field("sync", &self.sync)
|
||||||
|
.field("global", &self.global)
|
||||||
|
.field("playhead", &self.playhead)
|
||||||
|
.field("started", &self.started)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clock {
|
||||||
|
pub fn new (jack: &Jack<'static>, bpm: Option<f64>) -> Usually<Self> {
|
||||||
|
let (chunk, transport) = jack.with_client(|c|(c.buffer_size(), c.transport()));
|
||||||
|
let timebase = Arc::new(Timebase::default());
|
||||||
|
let clock = Self {
|
||||||
|
quant: Arc::new(24.into()),
|
||||||
|
sync: Arc::new(384.into()),
|
||||||
|
transport: Arc::new(Some(transport)),
|
||||||
|
chunk: Arc::new((chunk as usize).into()),
|
||||||
|
global: Arc::new(Moment::zero(&timebase)),
|
||||||
|
playhead: Arc::new(Moment::zero(&timebase)),
|
||||||
|
offset: Arc::new(Moment::zero(&timebase)),
|
||||||
|
started: RwLock::new(None).into(),
|
||||||
|
timebase,
|
||||||
|
midi_in: Arc::new(RwLock::new(Some(MidiInput::new(jack, &"M/clock", &[])?))),
|
||||||
|
midi_out: Arc::new(RwLock::new(Some(MidiOutput::new(jack, &"clock/M", &[])?))),
|
||||||
|
click_out: Arc::new(RwLock::new(Some(AudioOutput::new(jack, &"click", &[])?))),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
if let Some(bpm) = bpm {
|
||||||
|
clock.timebase.bpm.set(bpm);
|
||||||
|
}
|
||||||
|
Ok(clock)
|
||||||
|
}
|
||||||
|
pub fn timebase (&self) -> &Arc<Timebase> {
|
||||||
|
&self.timebase
|
||||||
|
}
|
||||||
|
/// Current sample rate
|
||||||
|
pub fn sr (&self) -> &SampleRate {
|
||||||
|
&self.timebase.sr
|
||||||
|
}
|
||||||
|
/// Current tempo
|
||||||
|
pub fn bpm (&self) -> &Bpm {
|
||||||
|
&self.timebase.bpm
|
||||||
|
}
|
||||||
|
/// Current MIDI resolution
|
||||||
|
pub fn ppq (&self) -> &Ppq {
|
||||||
|
&self.timebase.ppq
|
||||||
|
}
|
||||||
|
/// Next pulse that matches launch sync (for phrase switchover)
|
||||||
|
pub fn next_launch_pulse (&self) -> usize {
|
||||||
|
let sync = self.sync.get() as usize;
|
||||||
|
let pulse = self.playhead.pulse.get() as usize;
|
||||||
|
if pulse % sync == 0 {
|
||||||
|
pulse
|
||||||
|
} else {
|
||||||
|
(pulse / sync + 1) * sync
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Start playing, optionally seeking to a given location beforehand
|
||||||
|
pub fn play_from (&self, start: Option<u32>) -> Usually<()> {
|
||||||
|
if let Some(transport) = self.transport.as_ref() {
|
||||||
|
if let Some(start) = start {
|
||||||
|
transport.locate(start)?;
|
||||||
|
}
|
||||||
|
transport.start()?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
/// Pause, optionally seeking to a given location afterwards
|
||||||
|
pub fn pause_at (&self, pause: Option<u32>) -> Usually<()> {
|
||||||
|
if let Some(transport) = self.transport.as_ref() {
|
||||||
|
transport.stop()?;
|
||||||
|
if let Some(pause) = pause {
|
||||||
|
transport.locate(pause)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
/// Is currently paused?
|
||||||
|
pub fn is_stopped (&self) -> bool {
|
||||||
|
self.started.try_read().unwrap().is_none()
|
||||||
|
}
|
||||||
|
/// Is currently playing?
|
||||||
|
pub fn is_rolling (&self) -> bool {
|
||||||
|
self.started.try_read().unwrap().is_some()
|
||||||
|
}
|
||||||
|
/// Update chunk size
|
||||||
|
pub fn set_chunk (&self, n_frames: usize) {
|
||||||
|
self.chunk.store(n_frames, Relaxed);
|
||||||
|
}
|
||||||
|
pub fn update_from_scope (&self, scope: &ProcessScope) -> Usually<()> {
|
||||||
|
// Store buffer length
|
||||||
|
self.set_chunk(scope.n_frames() as usize);
|
||||||
|
|
||||||
|
// Store reported global frame and usec
|
||||||
|
let CycleTimes { current_frames, current_usecs, .. } = scope.cycle_times()?;
|
||||||
|
self.global.sample.set(current_frames as f64);
|
||||||
|
self.global.usec.set(current_usecs as f64);
|
||||||
|
|
||||||
|
let mut started = self.started.try_write().unwrap();
|
||||||
|
|
||||||
|
// If transport has just started or just stopped,
|
||||||
|
// update starting point:
|
||||||
|
if let Some(transport) = self.transport.as_ref() {
|
||||||
|
match (transport.query_state()?, started.as_ref()) {
|
||||||
|
(TransportState::Rolling, None) => {
|
||||||
|
let moment = Moment::zero(&self.timebase);
|
||||||
|
moment.sample.set(current_frames as f64);
|
||||||
|
moment.usec.set(current_usecs as f64);
|
||||||
|
*started = Some(moment);
|
||||||
|
},
|
||||||
|
(TransportState::Stopped, Some(_)) => {
|
||||||
|
*started = None;
|
||||||
|
},
|
||||||
|
_ => {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
self.playhead.update_from_sample(started.as_ref()
|
||||||
|
.map(|started|current_frames as f64 - started.sample.get())
|
||||||
|
.unwrap_or(0.));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bbt (&self) -> PositionBBT {
|
||||||
|
let pulse = self.playhead.pulse.get() as i32;
|
||||||
|
let ppq = self.timebase.ppq.get() as i32;
|
||||||
|
let bpm = self.timebase.bpm.get();
|
||||||
|
let bar = (pulse / ppq) / 4;
|
||||||
|
PositionBBT {
|
||||||
|
bar: 1 + bar,
|
||||||
|
beat: 1 + (pulse / ppq) % 4,
|
||||||
|
tick: (pulse % ppq),
|
||||||
|
bar_start_tick: (bar * 4 * ppq) as f64,
|
||||||
|
beat_type: 4.,
|
||||||
|
beats_per_bar: 4.,
|
||||||
|
beats_per_minute: bpm,
|
||||||
|
ticks_per_beat: ppq as f64
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next_launch_instant (&self) -> Moment {
|
||||||
|
Moment::from_pulse(self.timebase(), self.next_launch_pulse() as f64)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get index of first sample to populate.
|
||||||
|
///
|
||||||
|
/// Greater than 0 means that the first pulse of the clip
|
||||||
|
/// falls somewhere in the middle of the chunk.
|
||||||
|
pub fn get_sample_offset (&self, scope: &ProcessScope, started: &Moment) -> usize{
|
||||||
|
(scope.last_frame_time() as usize).saturating_sub(
|
||||||
|
started.sample.get() as usize +
|
||||||
|
self.started.try_read().unwrap().as_ref().unwrap().sample.get() as usize
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get iterator that emits sample paired with pulse.
|
||||||
|
//
|
||||||
|
// * Sample: index into output buffer at which to write MIDI event
|
||||||
|
// * Pulse: index into clip from which to take the MIDI event
|
||||||
|
//
|
||||||
|
// Emitted for each sample of the output buffer that corresponds to a MIDI pulse.
|
||||||
|
pub fn get_pulses (&self, scope: &ProcessScope, offset: usize) -> Ticker {
|
||||||
|
self.timebase().pulses_between_samples(offset, offset + scope.n_frames() as usize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Temporal resolutions: sample rate, tempo, MIDI pulses per quaver (beat)
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let _ = tek::Timebase::default();
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Clone)] pub struct Timebase {
|
||||||
|
/// Audio samples per second
|
||||||
|
pub sr: SampleRate,
|
||||||
|
/// MIDI beats per minute
|
||||||
|
pub bpm: Bpm,
|
||||||
|
/// MIDI ticks per beat
|
||||||
|
pub ppq: Ppq,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Audio sample rate in Hz (samples per second)
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct SampleRate (pub(crate) AtomicF64);
|
||||||
|
|
||||||
|
/// Tempo in beats per minute
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Bpm (pub(crate) AtomicF64);
|
||||||
|
|
||||||
|
/// MIDI resolution in PPQ (pulses per quarter note)
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Ppq (pub(crate) AtomicF64);
|
||||||
|
|
||||||
|
impl Timebase {
|
||||||
|
/// Specify sample rate, BPM and PPQ
|
||||||
|
pub fn new (
|
||||||
|
s: impl Into<SampleRate>,
|
||||||
|
b: impl Into<Bpm>,
|
||||||
|
p: impl Into<Ppq>
|
||||||
|
) -> Self {
|
||||||
|
Self { sr: s.into(), bpm: b.into(), ppq: p.into() }
|
||||||
|
}
|
||||||
|
/// Iterate over ticks between start and end.
|
||||||
|
#[inline] pub fn pulses_between_samples (&self, start: usize, end: usize) -> Ticker {
|
||||||
|
Ticker { spp: self.samples_per_pulse(), sample: start, start, end }
|
||||||
|
}
|
||||||
|
/// Return the duration fo a beat in microseconds
|
||||||
|
#[inline] pub fn usec_per_beat (&self) -> f64 { 60_000_000f64 / self.bpm.get() }
|
||||||
|
/// Return the number of beats in a second
|
||||||
|
#[inline] pub fn beat_per_second (&self) -> f64 { self.bpm.get() / 60f64 }
|
||||||
|
/// Return the number of microseconds corresponding to a note of the given duration
|
||||||
|
#[inline] pub fn note_to_usec (&self, (num, den): (f64, f64)) -> f64 {
|
||||||
|
4.0 * self.usec_per_beat() * num / den
|
||||||
|
}
|
||||||
|
/// Return duration of a pulse in microseconds (BPM-dependent)
|
||||||
|
#[inline] pub fn pulse_per_usec (&self) -> f64 { self.ppq.get() / self.usec_per_beat() }
|
||||||
|
/// Return duration of a pulse in microseconds (BPM-dependent)
|
||||||
|
#[inline] pub fn usec_per_pulse (&self) -> f64 { self.usec_per_beat() / self.ppq.get() }
|
||||||
|
/// Return number of pulses to which a number of microseconds corresponds (BPM-dependent)
|
||||||
|
#[inline] pub fn usecs_to_pulse (&self, usec: f64) -> f64 { usec * self.pulse_per_usec() }
|
||||||
|
/// Convert a number of pulses to a sample number (SR- and BPM-dependent)
|
||||||
|
#[inline] pub fn pulses_to_usec (&self, pulse: f64) -> f64 { pulse / self.usec_per_pulse() }
|
||||||
|
/// Return number of pulses in a second (BPM-dependent)
|
||||||
|
#[inline] pub fn pulses_per_second (&self) -> f64 { self.beat_per_second() * self.ppq.get() }
|
||||||
|
/// Return fraction of a pulse to which a sample corresponds (SR- and BPM-dependent)
|
||||||
|
#[inline] pub fn pulses_per_sample (&self) -> f64 {
|
||||||
|
self.usec_per_pulse() / self.sr.usec_per_sample()
|
||||||
|
}
|
||||||
|
/// Return number of samples in a pulse (SR- and BPM-dependent)
|
||||||
|
#[inline] pub fn samples_per_pulse (&self) -> f64 {
|
||||||
|
self.sr.get() / self.pulses_per_second()
|
||||||
|
}
|
||||||
|
/// Convert a number of pulses to a sample number (SR- and BPM-dependent)
|
||||||
|
#[inline] pub fn pulses_to_sample (&self, p: f64) -> f64 {
|
||||||
|
self.pulses_per_sample() * p
|
||||||
|
}
|
||||||
|
/// Convert a number of samples to a pulse number (SR- and BPM-dependent)
|
||||||
|
#[inline] pub fn samples_to_pulse (&self, s: f64) -> f64 {
|
||||||
|
s / self.pulses_per_sample()
|
||||||
|
}
|
||||||
|
/// Return the number of samples corresponding to a note of the given duration
|
||||||
|
#[inline] pub fn note_to_samples (&self, note: (f64, f64)) -> f64 {
|
||||||
|
self.usec_to_sample(self.note_to_usec(note))
|
||||||
|
}
|
||||||
|
/// Return the number of samples corresponding to the given number of microseconds
|
||||||
|
#[inline] pub fn usec_to_sample (&self, usec: f64) -> f64 {
|
||||||
|
usec * self.sr.get() / 1000f64
|
||||||
|
}
|
||||||
|
/// Return the quantized position of a moment in time given a step
|
||||||
|
#[inline] pub fn quantize (&self, step: (f64, f64), time: f64) -> (f64, f64) {
|
||||||
|
let step = self.note_to_usec(step);
|
||||||
|
(time / step, time % step)
|
||||||
|
}
|
||||||
|
/// Quantize a collection of events
|
||||||
|
#[inline] pub fn quantize_into <E: Iterator<Item=(f64, f64)> + Sized, T> (
|
||||||
|
&self, step: (f64, f64), events: E
|
||||||
|
) -> Vec<(f64, f64)> {
|
||||||
|
events.map(|(time, event)|(self.quantize(step, time).0, event)).collect()
|
||||||
|
}
|
||||||
|
/// Format a number of pulses into Beat.Bar.Pulse starting from 0
|
||||||
|
#[inline] pub fn format_beats_0 (&self, pulse: f64) -> Arc<str> {
|
||||||
|
let pulse = pulse as usize;
|
||||||
|
let ppq = self.ppq.get() as usize;
|
||||||
|
let (beats, pulses) = if ppq > 0 { (pulse / ppq, pulse % ppq) } else { (0, 0) };
|
||||||
|
format!("{}.{}.{pulses:02}", beats / 4, beats % 4).into()
|
||||||
|
}
|
||||||
|
/// Format a number of pulses into Beat.Bar starting from 0
|
||||||
|
#[inline] pub fn format_beats_0_short (&self, pulse: f64) -> Arc<str> {
|
||||||
|
let pulse = pulse as usize;
|
||||||
|
let ppq = self.ppq.get() as usize;
|
||||||
|
let beats = if ppq > 0 { pulse / ppq } else { 0 };
|
||||||
|
format!("{}.{}", beats / 4, beats % 4).into()
|
||||||
|
}
|
||||||
|
/// Format a number of pulses into Beat.Bar.Pulse starting from 1
|
||||||
|
#[inline] pub fn format_beats_1 (&self, pulse: f64) -> Arc<str> {
|
||||||
|
let mut string = String::with_capacity(16);
|
||||||
|
self.format_beats_1_to(&mut string, pulse).expect("failed to format {pulse} into beat");
|
||||||
|
string.into()
|
||||||
|
}
|
||||||
|
/// Format a number of pulses into Beat.Bar.Pulse starting from 1
|
||||||
|
#[inline] pub fn format_beats_1_to (&self, w: &mut impl std::fmt::Write, pulse: f64) -> Result<(), std::fmt::Error> {
|
||||||
|
let pulse = pulse as usize;
|
||||||
|
let ppq = self.ppq.get() as usize;
|
||||||
|
let (beats, pulses) = if ppq > 0 { (pulse / ppq, pulse % ppq) } else { (0, 0) };
|
||||||
|
write!(w, "{}.{}.{pulses:02}", beats / 4 + 1, beats % 4 + 1)
|
||||||
|
}
|
||||||
|
/// Format a number of pulses into Beat.Bar.Pulse starting from 1
|
||||||
|
#[inline] pub fn format_beats_1_short (&self, pulse: f64) -> Arc<str> {
|
||||||
|
let pulse = pulse as usize;
|
||||||
|
let ppq = self.ppq.get() as usize;
|
||||||
|
let beats = if ppq > 0 { pulse / ppq } else { 0 };
|
||||||
|
format!("{}.{}", beats / 4 + 1, beats % 4 + 1).into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SampleRate {
|
||||||
|
/// Return the duration of a sample in microseconds (floating)
|
||||||
|
#[inline] pub fn usec_per_sample (&self) -> f64 {
|
||||||
|
1_000_000f64 / self.get()
|
||||||
|
}
|
||||||
|
/// Return the duration of a sample in microseconds (floating)
|
||||||
|
#[inline] pub fn sample_per_usec (&self) -> f64 {
|
||||||
|
self.get() / 1_000_000f64
|
||||||
|
}
|
||||||
|
/// Convert a number of samples to microseconds (floating)
|
||||||
|
#[inline] pub fn samples_to_usec (&self, samples: f64) -> f64 {
|
||||||
|
self.usec_per_sample() * samples
|
||||||
|
}
|
||||||
|
/// Convert a number of microseconds to samples (floating)
|
||||||
|
#[inline] pub fn usecs_to_sample (&self, usecs: f64) -> f64 {
|
||||||
|
self.sample_per_usec() * usecs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A point in time in all time scales (microsecond, sample, MIDI pulse)
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let _ = tek::Moment::default();
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default, Clone)] pub struct Moment {
|
||||||
|
pub timebase: Arc<Timebase>,
|
||||||
|
/// Current time in microseconds
|
||||||
|
pub usec: Microsecond,
|
||||||
|
/// Current time in audio samples
|
||||||
|
pub sample: SampleCount,
|
||||||
|
/// Current time in MIDI pulses
|
||||||
|
pub pulse: Pulse,
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let _ = tek::Moment2::default();
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Clone, Default)] pub enum Moment2 {
|
||||||
|
#[default] None,
|
||||||
|
Zero,
|
||||||
|
Usec(Microsecond),
|
||||||
|
Sample(SampleCount),
|
||||||
|
Pulse(Pulse),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Timestamp in microseconds
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let _ = tek::Microsecond(0.0.into());
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Microsecond (pub AtomicF64);
|
||||||
|
|
||||||
|
/// Timestamp in audio samples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let _ = tek::SampleCount(0.0.into());
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct SampleCount (pub AtomicF64);
|
||||||
|
|
||||||
|
/// Timestamp in MIDI pulses
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let _ = tek::Pulse(0.0.into());
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Pulse (pub AtomicF64);
|
||||||
|
|
||||||
|
impl Moment {
|
||||||
|
pub fn zero (timebase: &Arc<Timebase>) -> Self {
|
||||||
|
Self { usec: 0.into(), sample: 0.into(), pulse: 0.into(), timebase: timebase.clone() }
|
||||||
|
}
|
||||||
|
pub fn from_usec (timebase: &Arc<Timebase>, usec: f64) -> Self {
|
||||||
|
Self {
|
||||||
|
usec: usec.into(),
|
||||||
|
sample: timebase.sr.usecs_to_sample(usec).into(),
|
||||||
|
pulse: timebase.usecs_to_pulse(usec).into(),
|
||||||
|
timebase: timebase.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn from_sample (timebase: &Arc<Timebase>, sample: f64) -> Self {
|
||||||
|
Self {
|
||||||
|
sample: sample.into(),
|
||||||
|
usec: timebase.sr.samples_to_usec(sample).into(),
|
||||||
|
pulse: timebase.samples_to_pulse(sample).into(),
|
||||||
|
timebase: timebase.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn from_pulse (timebase: &Arc<Timebase>, pulse: f64) -> Self {
|
||||||
|
Self {
|
||||||
|
pulse: pulse.into(),
|
||||||
|
sample: timebase.pulses_to_sample(pulse).into(),
|
||||||
|
usec: timebase.pulses_to_usec(pulse).into(),
|
||||||
|
timebase: timebase.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[inline] pub fn update_from_usec (&self, usec: f64) {
|
||||||
|
self.usec.set(usec);
|
||||||
|
self.pulse.set(self.timebase.usecs_to_pulse(usec));
|
||||||
|
self.sample.set(self.timebase.sr.usecs_to_sample(usec));
|
||||||
|
}
|
||||||
|
#[inline] pub fn update_from_sample (&self, sample: f64) {
|
||||||
|
self.usec.set(self.timebase.sr.samples_to_usec(sample));
|
||||||
|
self.pulse.set(self.timebase.samples_to_pulse(sample));
|
||||||
|
self.sample.set(sample);
|
||||||
|
}
|
||||||
|
#[inline] pub fn update_from_pulse (&self, pulse: f64) {
|
||||||
|
self.usec.set(self.timebase.pulses_to_usec(pulse));
|
||||||
|
self.pulse.set(pulse);
|
||||||
|
self.sample.set(self.timebase.pulses_to_sample(pulse));
|
||||||
|
}
|
||||||
|
#[inline] pub fn format_beat (&self) -> Arc<str> {
|
||||||
|
self.timebase.format_beats_1(self.pulse.get()).into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Microsecond {
|
||||||
|
#[inline] pub fn format_msu (&self) -> Arc<str> {
|
||||||
|
let usecs = self.get() as usize;
|
||||||
|
let (seconds, msecs) = (usecs / 1000000, usecs / 1000 % 1000);
|
||||||
|
let (minutes, seconds) = (seconds / 60, seconds % 60);
|
||||||
|
format!("{minutes}:{seconds:02}:{msecs:03}").into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterator that emits subsequent ticks within a range.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let iter = tek::Ticker::default();
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Default)] pub struct Ticker {
|
||||||
|
pub spp: f64,
|
||||||
|
pub sample: usize,
|
||||||
|
pub start: usize,
|
||||||
|
pub end: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Iterator for Ticker {
|
||||||
|
type Item = (usize, usize);
|
||||||
|
fn next (&mut self) -> Option<Self::Item> {
|
||||||
|
loop {
|
||||||
|
if self.sample > self.end { return None }
|
||||||
|
let spp = self.spp;
|
||||||
|
let sample = self.sample as f64;
|
||||||
|
let start = self.start;
|
||||||
|
let end = self.end;
|
||||||
|
self.sample += 1;
|
||||||
|
//println!("{spp} {sample} {start} {end}");
|
||||||
|
let jitter = sample.rem_euclid(spp); // ramps
|
||||||
|
let next_jitter = (sample + 1.0).rem_euclid(spp);
|
||||||
|
if jitter > next_jitter { // at crossing:
|
||||||
|
let time = (sample as usize) % (end as usize-start as usize);
|
||||||
|
let tick = (sample / spp) as usize;
|
||||||
|
return Some((time, tick))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Define and implement a unit of time
|
||||||
|
macro_rules! impl_time_unit {
|
||||||
|
($T:ident) => {
|
||||||
|
impl TimeUnit for $T {}
|
||||||
|
impl_op!($T, Add, add, |a, b|{a + b});
|
||||||
|
impl_op!($T, Sub, sub, |a, b|{a - b});
|
||||||
|
impl_op!($T, Mul, mul, |a, b|{a * b});
|
||||||
|
impl_op!($T, Div, div, |a, b|{a / b});
|
||||||
|
impl_op!($T, Rem, rem, |a, b|{a % b});
|
||||||
|
impl_from!($T: |value: f64| { Self(value.into()) });
|
||||||
|
impl_from!($T: |value: usize| { Self((value as f64).into()) });
|
||||||
|
impl From<$T> for f64 { fn from (value: $T) -> Self { value.get() } }
|
||||||
|
impl From<&$T> for f64 { fn from (value: &$T) -> Self { value.get() } }
|
||||||
|
impl From<$T> for usize { fn from (value: $T) -> Self { value.get() as usize } }
|
||||||
|
impl From<&$T> for usize { fn from (value: &$T) -> Self { value.get() as usize } }
|
||||||
|
impl Clone for $T { fn clone (&self) -> Self { Self(self.get().into()) } }
|
||||||
|
impl $T {
|
||||||
|
pub fn get (&self) -> f64 {
|
||||||
|
self.0.load(Relaxed)
|
||||||
|
}
|
||||||
|
pub fn set (&self, value: f64) -> f64 {
|
||||||
|
let old = self.get();
|
||||||
|
self.0.store(value, Relaxed);
|
||||||
|
old
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_time_unit!(SampleCount);
|
||||||
|
impl_time_unit!(SampleRate);
|
||||||
|
impl_time_unit!(Microsecond);
|
||||||
|
impl_time_unit!(Quantize);
|
||||||
|
impl_time_unit!(Ppq);
|
||||||
|
impl_time_unit!(Pulse);
|
||||||
|
impl_time_unit!(Bpm);
|
||||||
|
impl_time_unit!(LaunchSync);
|
||||||
|
|
@ -79,3 +79,69 @@ impl HasWidth for Track {
|
||||||
if self.width > Track::MIN_WIDTH { self.width -= 1; }
|
if self.width > Track::MIN_WIDTH { self.width -= 1; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T> HasTrack for T where T: AsRefOpt<Track> + AsMutOpt<Track> {}
|
||||||
|
|
||||||
|
pub trait HasTrack: AsRefOpt<Track> + AsMutOpt<Track> {
|
||||||
|
fn track (&self) -> Option<&Track> {
|
||||||
|
self.as_ref_opt()
|
||||||
|
}
|
||||||
|
fn track_mut (&mut self) -> Option<&mut Track> {
|
||||||
|
self.as_mut_opt()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> HasTracks for T where T: AsRef<Vec<Track>> + AsMut<Vec<Track>> + HasClock + HasTrackScroll {}
|
||||||
|
|
||||||
|
pub trait HasTracks: AsRef<Vec<Track>> + AsMut<Vec<Track>> + HasClock + HasTrackScroll {
|
||||||
|
/// Read-only reference to collection of [Track]s.
|
||||||
|
fn tracks (&self) -> &Vec<Track> {
|
||||||
|
self.as_ref()
|
||||||
|
}
|
||||||
|
/// Mutable reference to collection of [Track]s.
|
||||||
|
fn tracks_mut (&mut self) -> &mut Vec<Track> {
|
||||||
|
self.as_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait HasTrackScroll {
|
||||||
|
fn track_scroll (&self) -> usize;
|
||||||
|
fn tracks_last (&self) -> usize;
|
||||||
|
fn tracks_last_mut (&mut self) -> &mut usize;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasTrackScroll for &mut Project {
|
||||||
|
fn track_scroll (&self) -> usize {
|
||||||
|
self.track_scroll
|
||||||
|
}
|
||||||
|
fn tracks_last (&self) -> usize {
|
||||||
|
self.track_last
|
||||||
|
}
|
||||||
|
fn tracks_last_mut (&mut self) -> &mut usize {
|
||||||
|
&mut self.track_last
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasTrackScroll for App {
|
||||||
|
fn track_scroll (&self) -> usize {
|
||||||
|
self.project.track_scroll()
|
||||||
|
}
|
||||||
|
fn tracks_last (&self) -> usize {
|
||||||
|
self.project.track_last
|
||||||
|
}
|
||||||
|
fn tracks_last_mut (&mut self) -> &mut usize {
|
||||||
|
&mut self.project.track_last
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasTrackScroll for Project {
|
||||||
|
fn track_scroll (&self) -> usize {
|
||||||
|
self.track_scroll
|
||||||
|
}
|
||||||
|
fn tracks_last (&self) -> usize {
|
||||||
|
self.track_last
|
||||||
|
}
|
||||||
|
fn tracks_last_mut (&mut self) -> &mut usize {
|
||||||
|
&mut self.track_last
|
||||||
|
}
|
||||||
|
}
|
||||||
2065
src/tek.rs
2065
src/tek.rs
File diff suppressed because it is too large
Load diff
2
tengri
2
tengri
|
|
@ -1 +1 @@
|
||||||
Subproject commit 65f7948e9c0b5ed535d13c354ef5f4150a801f01
|
Subproject commit 3e845dbe83f679d11e431a236cc75f2e03792c7f
|
||||||
Loading…
Add table
Add a link
Reference in a new issue