mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-07 12:16:42 +01:00
wip: refactor into crates
This commit is contained in:
parent
96e17e7f7c
commit
5ae99b4ada
87 changed files with 2281 additions and 2217 deletions
9
crates/tek_timer/Cargo.toml
Normal file
9
crates/tek_timer/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "tek_timer"
|
||||
edition = "2021"
|
||||
version = "0.1.0"
|
||||
|
||||
[dependencies]
|
||||
tek_core = { path = "../tek_core" }
|
||||
tek_jack = { path = "../tek_jack" }
|
||||
atomic_float = "1.0.0"
|
||||
3
crates/tek_timer/README.md
Normal file
3
crates/tek_timer/README.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# `tek_timer`
|
||||
|
||||
This crate implements time sync and JACK transport control.
|
||||
5
crates/tek_timer/src/bin/mod.rs
Normal file
5
crates/tek_timer/src/bin/mod.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
/// Application entrypoint.
|
||||
pub fn main () -> Usually<()> {
|
||||
run(Arc::new(RwLock::new(TransportToolbar::standalone())))?;
|
||||
Ok(())
|
||||
}
|
||||
72
crates/tek_timer/src/lib.rs
Normal file
72
crates/tek_timer/src/lib.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
pub(crate) use tek_core::*;
|
||||
pub(crate) use tek_core::ratatui::prelude::*;
|
||||
pub(crate) use tek_core::crossterm::event::{KeyCode, KeyModifiers};
|
||||
pub(crate) use tek_jack::jack::*;
|
||||
pub(crate) use std::sync::{Arc, atomic::Ordering};
|
||||
pub(crate) use atomic_float::AtomicF64;
|
||||
submod! {
|
||||
timebase
|
||||
ticks
|
||||
transport
|
||||
transport_focus
|
||||
}
|
||||
|
||||
/// (pulses, name)
|
||||
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"),
|
||||
];
|
||||
|
||||
/// Returns the next shorter length
|
||||
pub fn prev_note_length (ppq: usize) -> usize {
|
||||
for i in 1..=16 {
|
||||
let length = NOTE_DURATIONS[16-i].0;
|
||||
if length < ppq {
|
||||
return length
|
||||
}
|
||||
}
|
||||
ppq
|
||||
}
|
||||
|
||||
/// Returns the next longer length
|
||||
pub fn next_note_length (ppq: usize) -> usize {
|
||||
for (length, _) in &NOTE_DURATIONS {
|
||||
if *length > ppq {
|
||||
return *length
|
||||
}
|
||||
}
|
||||
ppq
|
||||
}
|
||||
|
||||
pub fn ppq_to_name (ppq: usize) -> &'static str {
|
||||
for (length, name) in &NOTE_DURATIONS {
|
||||
if *length == ppq {
|
||||
return name
|
||||
}
|
||||
}
|
||||
""
|
||||
}
|
||||
50
crates/tek_timer/src/ticks.rs
Normal file
50
crates/tek_timer/src/ticks.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
use crate::*;
|
||||
|
||||
/// Defines frames per tick.
|
||||
pub struct Ticks(pub f64);
|
||||
|
||||
impl Ticks {
|
||||
/// Iterate over ticks between start and end.
|
||||
pub fn between_frames (&self, start: usize, end: usize) -> TicksIterator {
|
||||
TicksIterator(self.0, start, start, end)
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator that emits subsequent ticks within a range.
|
||||
pub struct TicksIterator(f64, usize, usize, usize);
|
||||
|
||||
impl Iterator for TicksIterator {
|
||||
type Item = (usize, usize);
|
||||
fn next (&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
if self.1 > self.3 {
|
||||
return None
|
||||
}
|
||||
let fpt = self.0;
|
||||
let frame = self.1 as f64;
|
||||
let start = self.2;
|
||||
let end = self.3;
|
||||
self.1 = self.1 + 1;
|
||||
//println!("{fpt} {frame} {start} {end}");
|
||||
let jitter = frame.rem_euclid(fpt); // ramps
|
||||
let next_jitter = (frame + 1.0).rem_euclid(fpt);
|
||||
if jitter > next_jitter { // at crossing:
|
||||
let time = (frame as usize) % (end as usize-start as usize);
|
||||
let tick = (frame / fpt) as usize;
|
||||
return Some((time, tick))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_frames_to_ticks () {
|
||||
let ticks = Ticks(12.3).between_frames(0, 100).collect::<Vec<_>>();
|
||||
println!("{ticks:?}");
|
||||
}
|
||||
|
||||
}
|
||||
103
crates/tek_timer/src/timebase.rs
Normal file
103
crates/tek_timer/src/timebase.rs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
use crate::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Keeps track of global time units.
|
||||
pub struct Timebase {
|
||||
/// Frames per second
|
||||
pub rate: AtomicF64,
|
||||
/// Beats per minute
|
||||
pub bpm: AtomicF64,
|
||||
/// Ticks per beat
|
||||
pub ppq: AtomicF64,
|
||||
}
|
||||
impl Default for Timebase {
|
||||
fn default () -> Self {
|
||||
Self {
|
||||
rate: 48000f64.into(),
|
||||
bpm: 150f64.into(),
|
||||
ppq: 96f64.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Timebase {
|
||||
pub fn new (rate: f64, bpm: f64, ppq: f64) -> Self {
|
||||
Self { rate: rate.into(), bpm: bpm.into(), ppq: ppq.into() }
|
||||
}
|
||||
|
||||
/// Frames per second
|
||||
#[inline] fn rate (&self) -> f64 {
|
||||
self.rate.load(Ordering::Relaxed)
|
||||
}
|
||||
#[inline] fn usec_per_frame (&self) -> f64 {
|
||||
1_000_000 as f64 / self.rate() as f64
|
||||
}
|
||||
#[inline] pub fn frame_to_usec (&self, frame: f64) -> f64 {
|
||||
frame * self.usec_per_frame()
|
||||
}
|
||||
|
||||
/// Beats per minute
|
||||
#[inline] pub fn bpm (&self) -> f64 {
|
||||
self.bpm.load(Ordering::Relaxed)
|
||||
}
|
||||
#[inline] pub fn set_bpm (&self, bpm: f64) {
|
||||
self.bpm.store(bpm, Ordering::Relaxed)
|
||||
}
|
||||
#[inline] fn usec_per_beat (&self) -> f64 {
|
||||
60_000_000f64 / self.bpm() as f64
|
||||
}
|
||||
#[inline] fn beat_per_second (&self) -> f64 {
|
||||
self.bpm() as f64 / 60000000.0
|
||||
}
|
||||
|
||||
/// Pulses per beat
|
||||
#[inline] pub fn ppq (&self) -> f64 {
|
||||
self.ppq.load(Ordering::Relaxed)
|
||||
}
|
||||
#[inline] pub fn pulse_per_frame (&self) -> f64 {
|
||||
self.usec_per_pulse() / self.usec_per_frame() as f64
|
||||
}
|
||||
#[inline] pub fn usec_per_pulse (&self) -> f64 {
|
||||
self.usec_per_beat() / self.ppq() as f64
|
||||
}
|
||||
#[inline] pub fn pulse_to_frame (&self, pulses: f64) -> f64 {
|
||||
self.pulse_per_frame() * pulses
|
||||
}
|
||||
#[inline] pub fn frame_to_pulse (&self, frames: f64) -> f64 {
|
||||
frames / self.pulse_per_frame()
|
||||
}
|
||||
#[inline] pub fn note_to_usec (&self, (num, den): (f64, f64)) -> f64 {
|
||||
4.0 * self.usec_per_beat() * num / den
|
||||
}
|
||||
#[inline] pub fn frames_per_pulse (&self) -> f64 {
|
||||
self.rate() as f64 / self.pulses_per_second()
|
||||
}
|
||||
#[inline] fn pulses_per_second (&self) -> f64 {
|
||||
self.beat_per_second() * self.ppq() as f64
|
||||
}
|
||||
|
||||
#[inline] pub fn note_to_frame (&self, note: (f64, f64)) -> f64 {
|
||||
self.usec_to_frame(self.note_to_usec(note))
|
||||
}
|
||||
#[inline] fn usec_to_frame (&self, usec: f64) -> f64 {
|
||||
usec * self.rate() / 1000.0
|
||||
}
|
||||
|
||||
#[inline] pub fn quantize (
|
||||
&self, step: (f64, f64), time: f64
|
||||
) -> (f64, f64) {
|
||||
let step = self.note_to_usec(step);
|
||||
(time / step, time % step)
|
||||
}
|
||||
|
||||
#[inline] pub fn quantize_into <E, T> (
|
||||
&self, step: (f64, f64), events: E
|
||||
) -> Vec<(f64, T)>
|
||||
where E: std::iter::Iterator<Item=(f64, T)> + Sized
|
||||
{
|
||||
let step = (step.0.into(), step.1.into());
|
||||
events
|
||||
.map(|(time, event)|(self.quantize(step, time).0, event))
|
||||
.collect()
|
||||
}
|
||||
|
||||
}
|
||||
234
crates/tek_timer/src/transport.rs
Normal file
234
crates/tek_timer/src/transport.rs
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
use crate::*;
|
||||
|
||||
/// Stores and displays time-related state.
|
||||
pub struct TransportToolbar {
|
||||
/// Enable metronome?
|
||||
pub metronome: bool,
|
||||
pub focused: bool,
|
||||
pub entered: bool,
|
||||
pub selected: TransportFocus,
|
||||
/// Current sample rate, tempo, and PPQ.
|
||||
pub timebase: Arc<Timebase>,
|
||||
/// JACK transport handle.
|
||||
transport: Option<Transport>,
|
||||
/// Quantization factor
|
||||
pub quant: usize,
|
||||
/// Global sync quant
|
||||
pub sync: usize,
|
||||
/// Current transport state
|
||||
pub playing: Option<TransportState>,
|
||||
/// Current position according to transport
|
||||
playhead: usize,
|
||||
/// Global frame and usec at which playback started
|
||||
pub started: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl TransportToolbar {
|
||||
pub fn standalone () -> Self {
|
||||
Self::new(None)
|
||||
}
|
||||
pub fn new (transport: Option<Transport>) -> Self {
|
||||
let timebase = Arc::new(Timebase::default());
|
||||
Self {
|
||||
selected: TransportFocus::BPM,
|
||||
metronome: false,
|
||||
focused: false,
|
||||
entered: false,
|
||||
playhead: 0,
|
||||
playing: Some(TransportState::Stopped),
|
||||
started: None,
|
||||
quant: 24,
|
||||
sync: timebase.ppq() as usize * 4,
|
||||
transport,
|
||||
timebase,
|
||||
}
|
||||
}
|
||||
pub fn toggle_play (&mut self) -> Usually<()> {
|
||||
self.playing = match self.playing.expect("1st frame has not been processed yet") {
|
||||
TransportState::Stopped => {
|
||||
self.transport.as_ref().unwrap().start()?;
|
||||
Some(TransportState::Starting)
|
||||
},
|
||||
_ => {
|
||||
self.transport.as_ref().unwrap().stop()?;
|
||||
self.transport.as_ref().unwrap().locate(0)?;
|
||||
Some(TransportState::Stopped)
|
||||
},
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
pub fn update (&mut self, scope: &ProcessScope) -> (bool, usize, usize, usize, usize, f64) {
|
||||
let CycleTimes {
|
||||
current_frames,
|
||||
current_usecs,
|
||||
next_usecs,
|
||||
period_usecs
|
||||
} = scope.cycle_times().unwrap();
|
||||
let chunk_size = scope.n_frames() as usize;
|
||||
let transport = self.transport.as_ref().unwrap().query().unwrap();
|
||||
self.playhead = transport.pos.frame() as usize;
|
||||
let mut reset = false;
|
||||
if self.playing != Some(transport.state) {
|
||||
match transport.state {
|
||||
TransportState::Rolling => {
|
||||
self.started = Some((
|
||||
current_frames as usize,
|
||||
current_usecs as usize,
|
||||
));
|
||||
},
|
||||
TransportState::Stopped => {
|
||||
self.started = None;
|
||||
reset = true;
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.playing = Some(transport.state);
|
||||
(
|
||||
reset,
|
||||
current_frames as usize,
|
||||
chunk_size as usize,
|
||||
current_usecs as usize,
|
||||
next_usecs as usize,
|
||||
period_usecs as f64
|
||||
)
|
||||
}
|
||||
pub fn bpm (&self) -> usize {
|
||||
self.timebase.bpm() as usize
|
||||
}
|
||||
pub fn ppq (&self) -> usize {
|
||||
self.timebase.ppq() as usize
|
||||
}
|
||||
pub fn pulse (&self) -> usize {
|
||||
self.timebase.frame_to_pulse(self.playhead as f64) as usize
|
||||
}
|
||||
pub fn usecs (&self) -> usize {
|
||||
self.timebase.frame_to_usec(self.playhead as f64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
render!(TransportToolbar |self, buf, area| {
|
||||
let mut area = area;
|
||||
area.height = 2;
|
||||
let gray = Style::default().gray();
|
||||
let not_dim = Style::default().not_dim();
|
||||
let not_dim_bold = not_dim.bold();
|
||||
let corners = Corners(Style::default().green().not_dim());
|
||||
let ppq = self.ppq();
|
||||
let bpm = self.bpm();
|
||||
let pulse = self.pulse();
|
||||
let usecs = self.usecs();
|
||||
let Self { quant, sync, focused, entered, .. } = self;
|
||||
fill_bg(buf, area, Nord::bg_lo(*focused, *entered));
|
||||
Split::right([
|
||||
|
||||
// Play/Pause button
|
||||
&|buf: &mut Buffer, Rect { x, y, .. }: Rect|{
|
||||
let style = Some(match self.playing {
|
||||
Some(TransportState::Stopped) => gray.dim().bold(),
|
||||
Some(TransportState::Starting) => gray.not_dim().bold(),
|
||||
Some(TransportState::Rolling) => gray.not_dim().white().bold(),
|
||||
_ => unreachable!(),
|
||||
});
|
||||
let label = match self.playing {
|
||||
Some(TransportState::Rolling) => "▶ PLAYING",
|
||||
Some(TransportState::Starting) => "READY ...",
|
||||
Some(TransportState::Stopped) => "⏹ STOPPED",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let mut result = label.blit(buf, x + 1, y, style)?;
|
||||
result.width = result.width + 1;
|
||||
Ok(result)
|
||||
},
|
||||
|
||||
// Beats per minute
|
||||
&|buf: &mut Buffer, Rect { x, y, .. }: Rect|{
|
||||
"BPM".blit(buf, x, y, Some(not_dim))?;
|
||||
let width = format!("{}.{:03}", bpm, bpm % 1).blit(buf, x, y + 1, Some(not_dim_bold))?.width;
|
||||
let area = Rect { x, y, width: (width + 2).max(10), height: 2 };
|
||||
if self.focused && self.entered && self.selected == TransportFocus::BPM {
|
||||
corners.draw(buf, Rect { x: area.x - 1, ..area })?;
|
||||
}
|
||||
Ok(area)
|
||||
},
|
||||
|
||||
// Quantization
|
||||
&|buf: &mut Buffer, Rect { x, y, .. }: Rect|{
|
||||
"QUANT".blit(buf, x, y, Some(not_dim))?;
|
||||
let width = ppq_to_name(*quant as usize).blit(buf, x, y + 1, Some(not_dim_bold))?.width;
|
||||
let area = Rect { x, y, width: (width + 2).max(10), height: 2 };
|
||||
if self.focused && self.entered && self.selected == TransportFocus::Quant {
|
||||
corners.draw(buf, Rect { x: area.x - 1, ..area })?;
|
||||
}
|
||||
Ok(area)
|
||||
},
|
||||
|
||||
// Clip launch sync
|
||||
&|buf: &mut Buffer, Rect { x, y, .. }: Rect|{
|
||||
"SYNC".blit(buf, x, y, Some(not_dim))?;
|
||||
let width = ppq_to_name(*sync as usize).blit(buf, x, y + 1, Some(not_dim_bold))?.width;
|
||||
let area = Rect { x, y, width: (width + 2).max(10), height: 2 };
|
||||
if self.focused && self.entered && self.selected == TransportFocus::Sync {
|
||||
corners.draw(buf, Rect { x: area.x - 1, ..area })?;
|
||||
}
|
||||
Ok(area)
|
||||
},
|
||||
|
||||
// Clock
|
||||
&|buf: &mut Buffer, Rect { x, y, width, .. }: Rect|{
|
||||
let (beats, pulses) = (pulse / ppq, pulse % ppq);
|
||||
let (bars, beats) = ((beats / 4) + 1, (beats % 4) + 1);
|
||||
let (seconds, msecs) = (usecs / 1000000, usecs / 1000 % 1000);
|
||||
let (minutes, seconds) = (seconds / 60, seconds % 60);
|
||||
let timer = format!("{minutes}:{seconds:02}:{msecs:03} {bars}.{beats}.{pulses:02}");
|
||||
timer.blit(buf, x + width - timer.len() as u16 - 1, y, Some(not_dim))
|
||||
}
|
||||
|
||||
]).render(buf, area)
|
||||
});
|
||||
|
||||
/// Key bindings for transport toolbar.
|
||||
pub const KEYMAP_TRANSPORT: &'static [KeyBinding<TransportToolbar>] = keymap!(TransportToolbar {
|
||||
[Left, NONE, "transport_prev", "select previous control", |transport: &mut TransportToolbar| Ok({
|
||||
transport.selected.prev();
|
||||
true
|
||||
})],
|
||||
[Right, NONE, "transport_next", "select next control", |transport: &mut TransportToolbar| Ok({
|
||||
transport.selected.next();
|
||||
true
|
||||
})],
|
||||
[Char('.'), NONE, "transport_increment", "increment value at cursor", |transport: &mut TransportToolbar| {
|
||||
match transport.selected {
|
||||
TransportFocus::BPM => {
|
||||
transport.timebase.bpm.fetch_add(1.0, Ordering::Relaxed);
|
||||
},
|
||||
TransportFocus::Quant => {
|
||||
transport.quant = next_note_length(transport.quant)
|
||||
},
|
||||
TransportFocus::Sync => {
|
||||
transport.sync = next_note_length(transport.sync)
|
||||
},
|
||||
};
|
||||
Ok(true)
|
||||
}],
|
||||
[Char(','), NONE, "transport_decrement", "decrement value at cursor", |transport: &mut TransportToolbar| {
|
||||
match transport.selected {
|
||||
TransportFocus::BPM => {
|
||||
transport.timebase.bpm.fetch_sub(1.0, Ordering::Relaxed);
|
||||
},
|
||||
TransportFocus::Quant => {
|
||||
transport.quant = prev_note_length(transport.quant);
|
||||
},
|
||||
TransportFocus::Sync => {
|
||||
transport.sync = prev_note_length(transport.sync);
|
||||
},
|
||||
};
|
||||
Ok(true)
|
||||
}],
|
||||
});
|
||||
|
||||
handle!{
|
||||
TransportToolbar |self, e| {
|
||||
handle_keymap(self, e, KEYMAP_TRANSPORT)
|
||||
}
|
||||
}
|
||||
23
crates/tek_timer/src/transport_focus.rs
Normal file
23
crates/tek_timer/src/transport_focus.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
use crate::*;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
/// Which section of the transport is focused
|
||||
pub enum TransportFocus { BPM, Quant, Sync }
|
||||
|
||||
impl TransportFocus {
|
||||
pub fn prev (&mut self) {
|
||||
*self = match self {
|
||||
Self::BPM => Self::Sync,
|
||||
Self::Quant => Self::BPM,
|
||||
Self::Sync => Self::Quant,
|
||||
}
|
||||
}
|
||||
pub fn next (&mut self) {
|
||||
*self = match self {
|
||||
Self::BPM => Self::Quant,
|
||||
Self::Quant => Self::Sync,
|
||||
Self::Sync => Self::BPM,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue