refactor: compact

This commit is contained in:
🪞👃🪞 2024-06-07 16:51:30 +03:00
parent abee6cc2c8
commit 60627ac3e5
43 changed files with 923 additions and 780 deletions

209
.misc/_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 {std::thread::sleep(std::time::Duration::from_millis(10))
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,
}

4
.misc/_sequence/audio.rs Normal file
View file

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

114
.misc/_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)
}

80
.misc/_sequence/mod.rs Normal file
View file

@ -0,0 +1,80 @@
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
.misc/_sequence/osc.rs Normal file
View file

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

0
.misc/_sequence/time.rs Normal file
View file

View file

View file

@ -0,0 +1,179 @@
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<
Box<dyn NotificationHandler>,
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(
Box::new(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
}
}

View file

@ -0,0 +1,7 @@
[package]
name = "midikbd"
[dependencies]
jack = "0.10"
clap = { version = "4.5.4", features = [ "derive" ] }
crossterm = "0.25"

View file

@ -0,0 +1,38 @@
extern crate clap;
extern crate crossterm;
extern crate engine;
type StdResult<T> = Result<T, Box<dyn std::error::Error>>
pub fn main () -> StdResult<()> {
let cli = Cli::parse();
let engine = run_jack_engine(move |_: &Client, _: &ProcessScope| {
Control::Continue
});
let app = App::new()
}
pub struct App {
sleep: std::time::Duration
}
impl App {
fn init () -> Self {
Self {
sleep: std::time::Duration::from_millis(16)
}
}
fn run (&self) -> StdResult<()> {
loop {
self.update()?;
self.render()?;
std::thread::sleep(self.sleep);
}
}
fn update (&self) -> StdResult<()> {
}
fn render (&self) -> StdResult<()> {
use crossterm::*;
let (cols, rows) = terminal::size()?;
}
}

View file

View file

View file

View file

View file

View file

View file

View file

@ -0,0 +1,46 @@
pub struct Timebase {
/// Sample rate
rate: u64,
/// Current frame
frame: u64,
/// Beats per bar
signature: (u64, u64),
/// Beats per minute
bpm: f64,
}
impl Timebase {
pub fn new (rate: u64, signature: (u64, u64), bpm: f64) -> Self {
Self {
rate,
frame: 0,
signature,
bpm,
}
}
pub fn seconds (&self) -> f64 {
self.frame as f64 / self.rate as f64
}
pub fn minutes (&self) -> f64 {
self.seconds / 60.0
}
pub fn beats (&self) -> f64 {
self.minutes / self.bpm
}
pub fn bar (&self) -> u64 {
((self.beats() * self.signature.0 as f64) / self.signature.1 as f64) as u64
}
pub fn beat (&self) -> u64 {
((self.beats() * self.signature.0 as f64) % self.signature.1 as f64) as u64
}
pub fn time_string (&self) -> String {
let minutes = self.minutes() as u64;
let seconds = self.seconds() as u64;
let milliseconds = self.seconds() - seconds;
format!("{minutes}:{seconds}.{milliseconds:03}")
}
pub fn beat_string (&self) -> String {
let beats = self.beats() as u64;
format!("{beats} {}/{}", minutes, self.beat(), self.signature.1)
}
}

View file

@ -0,0 +1,8 @@
[package]
name = "bloop_transport"
[dependencies]
jack = "0.10"
clap = { version = "4.5.4", features = [ "derive" ] }
crossterm = "0.25"

View file

@ -0,0 +1,39 @@
extern crate clap;
extern crate crossterm;
extern crate engine;
type StdResult<T> = Result<T, Box<dyn std::error::Error>>
pub fn main () -> StdResult<()> {
let cli = Cli::parse();
let engine = run_jack_engine(move |_: &Client, _: &ProcessScope| {
Control::Continue
});
let app = App::new()
}
pub struct App {
sleep: std::time::Duration,
state: TransportState,
}
impl App {
fn init () -> Self {
Self {
sleep: std::time::Duration::from_millis(16)
}
}
fn run (&self) -> StdResult<()> {
loop {
self.update()?;
self.render()?;
std::thread::sleep(self.sleep);
}
}
fn update (&self) -> StdResult<()> {
}
fn render (&self) -> StdResult<()> {
use crossterm::*;
let (cols, rows) = terminal::size()?;
}
}