tabula rasa

This commit is contained in:
🪞👃🪞 2024-05-23 21:18:56 +03:00
commit 11a9f3ba50
33 changed files with 1937 additions and 0 deletions

2
src/engine.rs Normal file
View file

@ -0,0 +1,2 @@
//pub mod jack;
//pub mod tui;

178
src/engine/jack.rs Normal file
View file

@ -0,0 +1,178 @@
use std::error::Error;
use std::thread;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use crate::Cli;
use jack::{
Control,
AsyncClient,
Client,
ClientStatus,
ClientOptions,
ClosureProcessHandler,
NotificationHandler,
ProcessScope,
ProcessHandler,
Frames,
Port,
PortId,
AudioIn,
AudioOut,
MidiIn,
MidiOut,
Transport
};
pub struct Jack {
client: Option<AsyncClient<
Notifications,
ClosureProcessHandler<Box<dyn FnMut(&Client, &ProcessScope)->Control + Send>>
>>,
pub transport: Option<Transport>,
audio_ins: BTreeMap<String, Port<AudioIn>>,
audio_outs: BTreeMap<String, Port<AudioOut>>,
midi_ins: BTreeMap<String, Port<MidiIn>>,
midi_outs: BTreeMap<String, Port<MidiOut>>,
}
impl Jack {
pub fn init_from_cli (options: &Cli)
-> Result<Arc<Mutex<Self>>, Box<dyn Error>>
{
let jack = Self::init(&options.jack_client_name)?;
{
let jack = jack.clone();
let mut jack = jack.lock().unwrap();
for port in options.jack_audio_ins.iter() {
jack.add_audio_in(port)?;
}
for port in options.jack_audio_outs.iter() {
jack.add_audio_out(port)?;
}
for port in options.jack_midi_ins.iter() {
jack.add_midi_in(port)?;
}
for port in options.jack_midi_outs.iter() {
jack.add_midi_out(port)?;
}
}
Ok(jack.clone())
}
fn init (name: &str)
-> Result<Arc<Mutex<Self>>, Box<dyn Error>>
{
let jack = Arc::new(Mutex::new(Self {
client: None,
transport: None,
audio_ins: BTreeMap::new(),
audio_outs: BTreeMap::new(),
midi_ins: BTreeMap::new(),
midi_outs: BTreeMap::new(),
}));
let (client, status) = Client::new(name, ClientOptions::NO_START_SERVER)?;
println!("Client status: {status:?}");
let jack1 = jack.clone();
let mut jack1 = jack1.lock().unwrap();
let jack2 = jack.clone();
jack1.transport = Some(client.transport());
jack1.client = Some(client.activate_async(
Notifications, ClosureProcessHandler::new(Box::new(
move |_client: &Client, _ps: &ProcessScope| -> Control {
let jack = jack2.lock().expect("Failed to lock jack mutex");
jack.read_inputs();
jack.write_outputs();
Control::Continue
}
) as Box<dyn FnMut(&Client, &ProcessScope)->Control + Send>)
)?);
Ok(jack)
}
fn start (&self) {
}
fn process (&self, _: &Client, ps: &ProcessScope) -> Control {
Control::Continue
}
fn add_audio_in (&mut self, name: &str) -> Result<&mut Self, Box<dyn Error>> {
let port = self.client
.as_ref()
.expect("Not initialized.")
.as_client()
.register_port(name, AudioIn::default())?;
self.audio_ins.insert(name.into(), port);
Ok(self)
}
fn add_audio_out (&mut self, name: &str) -> Result<&mut Self, Box<dyn Error>> {
let port = self.client
.as_ref()
.expect("Not initialized.")
.as_client()
.register_port(name, AudioOut::default())?;
self.audio_outs.insert(name.into(), port);
Ok(self)
}
fn add_midi_in (&mut self, name: &str) -> Result<&mut Self, Box<dyn Error>> {
let port = self.client
.as_ref()
.expect("Not initialized.")
.as_client()
.register_port(name, MidiIn::default())?;
self.midi_ins.insert(name.into(), port);
Ok(self)
}
fn add_midi_out (&mut self, name: &str) -> Result<&mut Self, Box<dyn Error>> {
let port = self.client
.as_ref()
.expect("Not initialized.")
.as_client()
.register_port(name, MidiOut::default())?;
self.midi_outs.insert(name.into(), port);
Ok(self)
}
fn read_inputs (&self) {
// read input buffers
//println!("read");
}
fn write_outputs (&self) {
// clear output buffers
// write output buffers
//println!("write");
}
}
struct Notifications;
impl NotificationHandler for Notifications {
fn thread_init (&self, _: &Client) {
}
fn shutdown (&mut self, status: ClientStatus, reason: &str) {
}
fn freewheel (&mut self, _: &Client, is_enabled: bool) {
}
fn sample_rate (&mut self, _: &Client, _: Frames) -> Control {
Control::Quit
}
fn client_registration (&mut self, _: &Client, name: &str, is_reg: bool) {
}
fn port_registration (&mut self, _: &Client, port_id: PortId, is_reg: bool) {
}
fn port_rename (&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control {
Control::Continue
}
fn ports_connected (&mut self, _: &Client, id_a: PortId, id_b: PortId, are: bool) {
}
fn graph_reorder (&mut self, _: &Client) -> Control {
Control::Continue
}
fn xrun (&mut self, _: &Client) -> Control {
Control::Continue
}
}

54
src/engine/tui.rs Normal file
View file

@ -0,0 +1,54 @@
use std::error::Error;
use std::io::{stdout, Write};
use std::thread::spawn;
use std::time::Duration;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{channel, Sender, Receiver}
};
pub struct Tui {
/// Exit flag. Setting this to true terminates the main loop.
exited: Arc<AtomicBool>,
/// Receives input events from input thread.
input: Receiver<crossterm::event::Event>,
/// Currently handled input event
pub event: Option<crossterm::event::Event>,
/// Output. Terminal commands are written to this.
pub output: Box<dyn Write>,
/// Currently available screen area.
pub area: [u16; 4]
}
impl Tui {
pub fn new () -> Result<Self, Box<dyn Error>> {
let output = stdout();
crossterm::terminal::enable_raw_mode()?;
let (tx, input) = channel::<crossterm::event::Event>();
let exited = Arc::new(AtomicBool::new(false));
// Spawn the input thread
let exit_input_thread = exited.clone();
spawn(move || {
loop {
// Exit if flag is set
if exit_input_thread.fetch_and(true, Ordering::Relaxed) {
break
}
// Listen for events and send them to the main thread
if crossterm::event::poll(Duration::from_millis(100)).is_ok() {
if tx.send(crossterm::event::read().unwrap()).is_err() {
break
}
}
}
});
Ok(Self {
exited,
input,
event: None,
output: Box::new(output),
area: [0, 0, 0, 0]
})
}
}

54
src/looper.rs Normal file
View file

@ -0,0 +1,54 @@
use std::error::Error;
use std::io::Write;
pub struct Looper {
cols: u16,
rows: u16,
}
impl Looper {
pub fn run_tui () -> Result<(), Box<dyn Error>> {
let mut app = Self { cols: 0, rows: 0 };
let sleep = std::time::Duration::from_millis(16);
let mut stdout = std::io::stdout();
loop {
app.render(&mut stdout)?;
std::thread::sleep(sleep);
}
}
fn render (&mut self, stdout: &mut std::io::Stdout) -> Result<(), Box<dyn Error>> {
use crossterm::{*, style::{*, Stylize}};
let (cols, rows) = terminal::size()?;
if cols != self.cols || rows != self.rows {
self.cols = cols;
self.rows = rows;
stdout
.queue(terminal::Clear(terminal::ClearType::All))?
.queue(cursor::Hide)?
.queue(cursor::MoveTo(1, 0))?
.queue(PrintStyledContent("[Up/Down]".yellow().bold()))?
.queue(cursor::MoveTo(1, 1))?
.queue(PrintStyledContent("Select sequence".yellow()))?
.queue(cursor::MoveTo(18, 0))?
.queue(PrintStyledContent("[Left/Right]".yellow().bold()))?
.queue(cursor::MoveTo(18, 1))?
.queue(PrintStyledContent("Select parameter".yellow()))?
.queue(cursor::MoveTo(36, 0))?
.queue(PrintStyledContent("[Insert/Delete]".yellow().bold()))?
.queue(cursor::MoveTo(36, 1))?
.queue(PrintStyledContent("Add/remove sequence".yellow()))?
.queue(cursor::MoveTo(0, 3))?.queue(Print(" Name Input Length Route"))?
.queue(cursor::MoveTo(0, 4))?.queue(PrintStyledContent(" Metronome [ ] ████ Track 1".bold()))?
.queue(cursor::MoveTo(0, 5))?.queue(PrintStyledContent(" Loop 1 [ ] ████ Track 1".bold()))?
.queue(cursor::MoveTo(0, 6))?.queue(PrintStyledContent(" Loop 2 [ ] ████████ Track 2".bold()))?
.queue(cursor::MoveTo(0, 7))?.queue(PrintStyledContent(" Loop 3 [ ] ████████ Track 3".bold()))?
.flush()?;
}
Ok(())
}
}

41
src/main.rs Normal file
View file

@ -0,0 +1,41 @@
extern crate clap;
extern crate jack;
extern crate crossterm;
use clap::{Parser, Subcommand};
use std::error::Error;
//pub mod sequence;
pub mod engine;
pub mod transport;
pub mod mixer;
pub mod looper;
fn main () -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
match cli.command {
Command::Transport =>
crate::transport::Transport::run_tui(),
Command::Mixer =>
crate::mixer::Mixer::run_tui(),
Command::Looper =>
crate::looper::Looper::run_tui(),
}
}
#[derive(Debug, Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
command: Command
}
#[derive(Debug, Clone, Subcommand)]
pub enum Command {
/// Control the master transport
Transport,
/// Control the mixer
Mixer,
/// Control the looper
Looper,
}

209
src/main_.rs Normal file
View file

@ -0,0 +1,209 @@
extern crate clap;
extern crate jack;
extern crate crossterm;
pub mod engine;
pub mod sequence;
use clap::Parser;
use std::error::Error;
use std::sync::{Arc, Mutex};
use std::io::Write;
use crossterm::QueueableCommand;
use crossterm::style::Stylize;
use crate::engine::jack::Jack;
use crate::sequence::Time;
use crate::sequence::midi::{PPQ, MIDISequence, MIDIEvent};
// bloop \
// --jack-client-name blooper
// --jack-audio-out L=system/playback_1 \
// --jack-audio-out R=system/playback_2 \
// --jack-midi-in 1="nanoKEY Studio [20] (capture): nanoKEY Studio nanoKEY Studio _"
fn main () -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
let app = App::init(&cli)?;
let sleep = std::time::Duration::from_millis(16);
let mut stdout = std::io::stdout();
loop {
app.render(&mut stdout)?;
std::thread::sleep(sleep);
};
Ok(())
}
struct App {
jack: Arc<Mutex<Jack>>,
time: u64,
root: MIDISequence,
stdout: std::io::Stdout,
}
impl App {
fn init (options: &Cli) -> Result<Self, Box<dyn Error>> {
let mut root = MIDISequence::new("/", 4 * PPQ);
root.add(00 * PPQ, MIDIEvent::NoteOn(36, 100))
.add(01 * PPQ, MIDIEvent::NoteOn(40, 100))
.add(02 * PPQ - PPQ / 2, MIDIEvent::NoteOn(36, 100))
.add(02 * PPQ + PPQ / 2, MIDIEvent::NoteOn(36, 100))
.add(03 * PPQ, MIDIEvent::NoteOn(40, 100))
.add(00 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(01 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(02 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(03 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(04 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(06 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(07 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(09 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(10 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(11 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(13 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(14 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(15 * PPQ / 4, MIDIEvent::NoteOn(44, 100));
Ok(Self {
jack: Jack::init_from_cli(&options)?,
time: 0,
root,
stdout: std::io::stdout(),
})
}
fn render (&self, stdout: &mut std::io::Stdout) -> Result<(), Box<dyn Error>> {
use crossterm::*;
let zoom = 8;
let (cols, rows) = terminal::size()?;
let transport = self.jack
.lock()
.expect("Failed to lock engine")
.transport.as_ref()
.expect("Failed to get transport")
.query()
.expect("Failed to query transport");
let state = transport.state;
let frame = transport.pos.frame();
let rate = transport.pos.frame_rate();
let time_string = if let Some(rate) = rate {
let second = (frame as f64) / (rate as f64);
let seconds = second.floor();
let msec = ((second - seconds) * 1000f64) as u64;
let seconds = second as u64 % 60;
let minutes = second as u64 / 60;
format!("{minutes}:{seconds:02}.{msec:03}")
} else {
"".to_string()
};
let mut x_offset = cols / 2 - 10;
let beat_string = if let Some(rate) = rate {
let second = (frame as f64) / (rate as f64);
let minute = second / 60f64;
let bpm = 120f64;
let div = 4;
let beats = minute * bpm;
let bars = beats as u64 / div as u64;
let beat = beats as u64 % div as u64 + 1;
x_offset -= ((beats as f64 % div as f64) * 8.0) as u16;
format!("{bars} {beat}/{div}")
} else {
"".to_string()
};
stdout
.queue(terminal::Clear(terminal::ClearType::All))?
.queue(cursor::Hide)?
.queue(cursor::MoveTo(1, 0))?
.queue(style::PrintStyledContent("bloop!".yellow()))?
.queue(cursor::MoveTo(1, 1))?
.queue(style::PrintStyledContent("v0.0.1".white()))?
.queue(cursor::MoveTo(10, 0))?
.queue(style::PrintStyledContent("rate".yellow()))?
.queue(cursor::MoveTo(10, 1))?
.queue(style::PrintStyledContent(format!("{}", rate.unwrap_or(0)).white()))?
.queue(cursor::MoveTo(18, 0))?
.queue(style::PrintStyledContent("state".yellow()))?
.queue(cursor::MoveTo(18, 1))?
.queue(style::PrintStyledContent(format!("{state:?}").white()))?
.queue(cursor::MoveTo(28, 0))?
.queue(style::PrintStyledContent("time".yellow()))?
.queue(cursor::MoveTo(28, 1))?
.queue(style::PrintStyledContent(format!("{time_string}").white()))?
.queue(cursor::MoveTo(40, 0))?
.queue(style::PrintStyledContent("beats".yellow()))?
.queue(cursor::MoveTo(40, 1))?
.queue(style::PrintStyledContent(format!("{beat_string}").white()))?
.queue(cursor::MoveTo(x_offset, 3.max(rows / 2 - 2)))?;
self.root.render(stdout, zoom)?;
stdout
.queue(cursor::MoveTo(0, rows - 2))?
.queue(style::PrintStyledContent(" SPACE".green()))?
.queue(cursor::MoveTo(0, rows - 1))?
.queue(style::PrintStyledContent(" play ".yellow()))?
.queue(cursor::MoveTo(8, rows - 2))?
.queue(style::PrintStyledContent(" HOME".green()))?
.queue(cursor::MoveTo(8, rows - 1))?
.queue(style::PrintStyledContent(" sync ".yellow()))?
//.queue(style::PrintStyledContent(" ↑↓←→".green()))?
//.queue(style::PrintStyledContent(" navigate ".yellow()))?
.queue(cursor::MoveTo(14, rows - 2))?
.queue(style::PrintStyledContent(" `".green()))?
.queue(cursor::MoveTo(14, rows - 1))?
.queue(style::PrintStyledContent(" markers ".yellow()))?
.queue(cursor::MoveTo(23, rows - 2))?
.queue(style::PrintStyledContent(" ,".green()))?
.queue(cursor::MoveTo(23, rows - 1))?
.queue(style::PrintStyledContent(" routing ".yellow()))?
.queue(cursor::MoveTo(32, rows - 2))?
.queue(style::PrintStyledContent(" a".green()))?
.queue(cursor::MoveTo(32, rows - 1))?
.queue(style::PrintStyledContent(" add audio ".yellow()))?
.queue(cursor::MoveTo(43, rows - 2))?
.queue(style::PrintStyledContent(" m".green()))?
.queue(cursor::MoveTo(43, rows - 1))?
.queue(style::PrintStyledContent(" add MIDI ".yellow()))?
.queue(cursor::MoveTo(54, rows - 2))?
.queue(style::PrintStyledContent(" o".green()))?
.queue(cursor::MoveTo(54, rows - 1))?
.queue(style::PrintStyledContent(" add OSC ".yellow()))?
.flush()?;
Ok(())
}
}
#[derive(Debug, Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
#[arg(long="jack-client-name", default_value="blooper")]
jack_client_name: String,
#[arg(long="jack-audio-in")]
jack_audio_ins: Vec<String>,
#[arg(long="jack-audio-out")]
jack_audio_outs: Vec<String>,
#[arg(long="jack-midi-in")]
jack_midi_ins: Vec<String>,
#[arg(long="jack-midi-out")]
jack_midi_outs: Vec<String>,
}
enum Command {
Play,
Stop,
Rec,
Dub,
Trim,
Jump,
}

177
src/mixer.rs Normal file
View file

@ -0,0 +1,177 @@
use std::error::Error;
use std::io::{stdout, Write};
use std::thread::spawn;
use std::time::Duration;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{channel, Sender, Receiver}
};
pub struct Mixer {
exit: bool,
cols: u16,
rows: u16,
tracks: Vec<Track>,
selected_track: usize,
selected_column: usize,
}
pub struct Track {
name: String,
gain: f64,
level: f64,
pan: f64,
route: String,
}
impl Mixer {
pub fn new () -> Self {
Self {
exit: false,
cols: 0,
rows: 0,
selected_column: 0,
selected_track: 1,
tracks: vec! [
Track {
name: "Track 1".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 1".into()
},
Track {
name: "Track 2".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 2".into()
},
Track {
name: "Track 3".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 1".into()
},
Track {
name: "Track 4".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 2".into()
},
Track {
name: "Bus 1".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Mix".into()
},
Track {
name: "Bus 2".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Mix".into()
},
Track {
name: "Mix".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Output".into()
},
]
}
}
pub fn run_tui () -> Result<(), Box<dyn Error>> {
let mut app = Self::new();
let sleep = std::time::Duration::from_millis(16);
let mut stdout = std::io::stdout();
crossterm::terminal::enable_raw_mode()?;
let (tx, input) = channel::<crossterm::event::Event>();
let exited = Arc::new(AtomicBool::new(false));
// Spawn the input thread
let exit_input_thread = exited.clone();
spawn(move || {
loop {
// Exit if flag is set
if exit_input_thread.fetch_and(true, Ordering::Relaxed) {
break
}
// Listen for events and send them to the main thread
if crossterm::event::poll(Duration::from_millis(100)).is_ok() {
if tx.send(crossterm::event::read().unwrap()).is_err() {
break
}
}
}
});
loop {
app.render(&mut stdout)?;
app.handle(input.recv()?)?;
if app.exit {
crossterm::terminal::disable_raw_mode()?;
break
}
}
Ok(())
}
fn handle (&mut self, event: crossterm::event::Event) -> Result<(), Box<dyn Error>> {
use crossterm::event::{Event, KeyCode, KeyModifiers};
if let Event::Key(event) = event {
match event.code {
KeyCode::Char('c') => {
if event.modifiers == KeyModifiers::CONTROL {
self.exit = true;
}
},
KeyCode::Down => {
self.selected_track = (self.selected_track + 1) % self.tracks.len();
println!("{}", self.selected_track);
}
KeyCode::Up => {
if self.selected_track == 0 {
self.selected_track = self.tracks.len() - 1;
} else {
self.selected_track = self.selected_track - 1;
}
println!("{}", self.selected_track);
}
_ => {
println!("{event:?}");
}
}
}
Ok(())
}
fn render (&mut self, stdout: &mut std::io::Stdout) -> Result<(), Box<dyn Error>> {
use crossterm::{*, style::{*, Stylize}};
let (cols, rows) = terminal::size()?;
if true || cols != self.cols || rows != self.rows { // TODO perf
self.cols = cols;
self.rows = rows;
stdout
.queue(terminal::Clear(terminal::ClearType::All))?
.queue(cursor::Hide)?
.queue(cursor::MoveTo(1, 0))?
.queue(PrintStyledContent("[Arrows]".yellow().bold()))?
.queue(cursor::MoveTo(1, 1))?
.queue(PrintStyledContent("Navigate".yellow()))?
.queue(cursor::MoveTo(11, 0))?
.queue(PrintStyledContent("[+/-]".yellow().bold()))?
.queue(cursor::MoveTo(11, 1))?
.queue(PrintStyledContent("Adjust value".yellow()))?
.queue(cursor::MoveTo(25, 0))?
.queue(PrintStyledContent("[Ins/Del]".yellow().bold()))?
.queue(cursor::MoveTo(25, 1))?
.queue(PrintStyledContent("Add/remove track".yellow()))?
.queue(cursor::MoveTo(0, 3))?.queue(Print(
" Name Gain Pre Level Pan Post Route"))?;
for (i, track) in self.tracks.iter().enumerate() {
let row = 4 + i as u16;
let mut content = format!(
" {:7} █ {:.1}dB █ [ ] █ {:.1}dB C █ [ ] {:7} ",
track.name,
track.gain,
track.level,
track.route,
).bold();
if i == self.selected_track {
content = content.reverse();
}
stdout
.queue(cursor::MoveTo(0, row))?
.queue(PrintStyledContent(content))?;
}
stdout
.flush()?;
}
Ok(())
}
}

39
src/mixer/tui.rs Normal file
View file

@ -0,0 +1,39 @@
use super::Mixer;
impl<W: Write> Input<TUI<W>, bool> for Mixer {
fn handle (&mut self, engine: &mut TUI<W>) -> Result<Option<bool>> {
Ok(None)
}
}
impl<W: Write> Output<TUI<W>, [u16;2]> for Mixer {
fn render (&self, envine: &mut TUI<W>) -> Result<Option<[u16;2]>> {
let tracks_table = Columns::new()
.add(titles)
.add(input_meters)
.add(gains)
.add(gain_meters)
.add(pres)
.add(pre_meters)
.add(levels)
.add(pans)
.add(pan_meters)
.add(posts)
.add(routes)
Rows::new()
.add(Columns::new()
.add(Rows::new()
.add("[Arrows]".bold())
.add("Navigate"))
.add(Rows::new()
.add("[+/-]".bold())
.add("Adjust"))
.add(Rows::new()
.add("[Ins/Del]".bold())
.add("Add/remove track")))
.add(tracks_table)
.render(engine)
}
}

79
src/sequence.rs Normal file
View file

@ -0,0 +1,79 @@
pub mod audio;
pub mod midi;
pub mod osc;
pub mod time;
pub type Frame = usize;
pub enum Time {
Fixed(Frame),
Synced(usize),
}
//enum Event {
//Trigger,
//Gate,
//MIDI(MIDIEvent),
//Audio,
//OSC,
//Text,
//Sequence
//}
//struct Clip {
//name: String,
//length: u64,
//start: u64,
//end: u64,
//clips: Sequence<Event<Clip>>,
//markers: Sequence<Event<Marker>>,
//audio: Sequence<Event<audio::Sample>>,
//midi: Sequence<Event<midi::Message>>,
//osc: Sequence<Event<osc::Command>>,
//}
//enum ClipData {
//Trigger,
//Gate,
//MIDI,
//Audio,
//OSC,
//Text,
//Clip
//}
//impl Clip {
//fn new (name: &str, length: u64) -> Self {
//Self {
//name: name.into(),
//length,
//start: 0,
//end: length,
//clips: Sequence::new(),
//markers: Sequence::new(),
//audio: Sequence::new(),
//midi: Sequence::new(),
//osc: Sequence::new(),
//}
//}
//}
//struct Sequence<T> {
//events: Vec<Event<T>>,
//next: usize,
//}
//impl<T> Sequence<T> {
//fn new () -> Self {
//Self { events: vec![], next: 0 }
//}
//}
//struct Event<T> {
//time: u64,
//data: T,
//}
//struct Marker {
//name: String,
//}

4
src/sequence/audio.rs Normal file
View file

@ -0,0 +1,4 @@
pub struct Sample {
samples: Vec<Vec<u64>>,
cuepoints: Vec<Vec<Vec<u64>>>,
}

114
src/sequence/midi.rs Normal file
View file

@ -0,0 +1,114 @@
use crate::sequence::{Frame, Time};
/// Pulses per quarter note
pub const PPQ: usize = 96;
pub struct Message {
bytes: Vec<u8>
}
pub struct MIDISequence {
name: String,
length: usize,
events: Vec<(Frame, MIDIEvent)>,
notes: Vec<u8>,
}
impl MIDISequence {
pub fn new (name: &str, length: usize) -> Self {
Self {
name: name.to_string(),
length,
events: vec![],
notes: vec![],
}
}
pub fn add (&mut self, time: usize, event: MIDIEvent) -> &mut Self {
let mut sort = false;
match &event {
MIDIEvent::NoteOn(pitch, _velocity) => {
if !self.notes.contains(pitch) {
self.notes.push(*pitch);
sort = true;
}
}
}
if sort {
self.notes.sort();
}
self.events.push((time, event));
self
}
pub fn render (&self, stdout: &mut std::io::Stdout, resolution: usize)
-> Result<(), Box<dyn std::error::Error>>
{
use crossterm::{*, style::Stylize};
let (col, row) = cursor::position()?;
let unit = PPQ / resolution;
let length = self.length / unit;
let mut header = String::from(" ");
for i in 0..length {
if i % 8 == 0 {
header.push('┍');
} else {
header.push('━');
}
}
header.push('┑');
let mut tracks: Vec<(String, String)> = vec![];
for note in self.notes.iter().rev() {
let mut row_header = format!(" {note:3} ");
let mut row = String::new();
for beat in 0..length {
let mut active = false;
for (frame, event) in self.events.iter() {
match event {
MIDIEvent::NoteOn(pitch, _) => {
if pitch == note
&& *frame >= beat * unit
&& *frame < (beat + 1) * unit
{
active = true;
continue
}
}
}
}
if active {
row.push('⯀')
} else if beat == 0 {
row.push('│');
} else if beat % 8 == 0 {
row.push('┆');
} else {
row.push('·');
}
}
tracks.push((row_header, row));
}
stdout.queue(style::PrintStyledContent(header.grey()))?;
for (row_header, row) in tracks.into_iter() {
stdout
.queue(cursor::MoveDown(1))?
.queue(cursor::MoveToColumn(col))?
.queue(style::PrintStyledContent(row_header.grey()))?
.queue(style::PrintStyledContent(row.clone().white()))?
.queue(style::PrintStyledContent(row.clone().yellow()))?
.queue(style::PrintStyledContent(row.white()))?;
}
//stdout
//.queue(cursor::MoveDown(1))?
//.queue(cursor::MoveToColumn(col))?
//.queue(style::PrintStyledContent(footer.grey()))?;
//.queue(style::PrintStyledContent("················".grey()))?
//.queue(style::PrintStyledContent("│".yellow()))?
//.queue(cursor::MoveDown(1))?
//.queue(cursor::MoveLeft(18))?
//.queue(style::PrintStyledContent("└────────────────┘".yellow()))?;
Ok(())
}
}
pub enum MIDIEvent {
NoteOn(u8, u8)
}

4
src/sequence/osc.rs Normal file
View file

@ -0,0 +1,4 @@
pub struct Command {
name: String,
args: Vec<String>,
}

0
src/sequence/time.rs Normal file
View file

58
src/transport.rs Normal file
View file

@ -0,0 +1,58 @@
use std::error::Error;
use std::io::Write;
pub struct Transport {
cols: u16,
rows: u16,
}
impl Transport {
pub fn run_tui () -> Result<(), Box<dyn Error>> {
let mut app = Self { cols: 0, rows: 0 };
let sleep = std::time::Duration::from_millis(16);
let mut stdout = std::io::stdout();
loop {
app.render(&mut stdout)?;
std::thread::sleep(sleep);
}
}
fn render (&mut self, stdout: &mut std::io::Stdout) -> Result<(), Box<dyn Error>> {
use crossterm::{*, style::{*, Stylize}};
let (cols, rows) = terminal::size()?;
if cols != self.cols || rows != self.rows {
self.cols = cols;
self.rows = rows;
stdout
.queue(terminal::Clear(terminal::ClearType::All))?
.queue(cursor::Hide)?
.queue(cursor::MoveTo(1, 0))?
.queue(PrintStyledContent("[Home]".yellow().bold()))?
.queue(cursor::MoveTo(1, 1))?
.queue(PrintStyledContent("⏹ Stop and rewind".yellow().bold()))?
.queue(cursor::MoveTo(20, 0))?
.queue(PrintStyledContent("[Enter]".yellow().bold()))?
.queue(cursor::MoveTo(20, 1))?
.queue(PrintStyledContent("⏮ Play from start".yellow().bold()))?
.queue(cursor::MoveTo(40, 0))?
.queue(PrintStyledContent("[Space]".yellow().bold()))?
.queue(cursor::MoveTo(40, 1))?
.queue(PrintStyledContent("⯈ Play from cursor".yellow().bold()))?
.queue(cursor::MoveTo(1, 3))?.queue(Print("Rate: "))?
.queue(cursor::MoveTo(7, 3))?.queue(PrintStyledContent("48000Hz".white().bold()))?
.queue(cursor::MoveTo(20, 3))?.queue(Print("BPM: "))?
.queue(cursor::MoveTo(25, 3))?.queue(PrintStyledContent("120.34".white().bold()))?
.queue(cursor::MoveTo(35, 3))?.queue(Print("Signature: "))?
.queue(cursor::MoveTo(46, 3))?.queue(PrintStyledContent("4 / 4".white().bold()))?
.queue(cursor::MoveTo(1, 4))?.queue(Print("Time: "))?
.queue(cursor::MoveTo(7, 4))?.queue(PrintStyledContent("1m 23.456s".white().bold()))?
.queue(cursor::MoveTo(20, 4))?.queue(Print("Beat: "))?
.queue(cursor::MoveTo(26, 4))?.queue(PrintStyledContent("30x 3/4".white().bold()))?
.flush()?;
}
Ok(())
}
}