display/play/stop transport

This commit is contained in:
🪞👃🪞 2024-05-30 21:27:02 +03:00
parent 265dc13248
commit 1f928fba9d
8 changed files with 251 additions and 177 deletions

View file

@ -62,7 +62,7 @@ impl App {
.add(13 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) .add(13 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(14 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) .add(14 * PPQ / 4, MIDIEvent::NoteOn(44, 100))
.add(15 * PPQ / 4, MIDIEvent::NoteOn(44, 100)); .add(15 * PPQ / 4, MIDIEvent::NoteOn(44, 100));
Ok(Self { Ok(Self {std::thread::sleep(std::time::Duration::from_millis(10))
jack: Jack::init_from_cli(&options)?, jack: Jack::init_from_cli(&options)?,
time: 0, time: 0,
root, root,

View file

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

View file

@ -214,8 +214,9 @@ pub fn main_loop <T: Exitable> (
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
let mut stdout = stdout(); let mut stdout = stdout();
let sleep = std::time::Duration::from_millis(16); let sleep = std::time::Duration::from_millis(16);
let poll = std::time::Duration::from_millis(100);
crossterm::terminal::enable_raw_mode()?; crossterm::terminal::enable_raw_mode()?;
let (tx, input) = channel::<crossterm::event::Event>(); let (tx, input) = std::sync::mpsc::channel::<crossterm::event::Event>();
let exited = Arc::new(AtomicBool::new(false)); let exited = Arc::new(AtomicBool::new(false));
let exit_input_thread = exited.clone(); let exit_input_thread = exited.clone();
spawn(move || { spawn(move || {
@ -225,7 +226,7 @@ pub fn main_loop <T: Exitable> (
break break
} }
// Listen for events and send them to the main thread // Listen for events and send them to the main thread
if crossterm::event::poll(Duration::from_millis(100)).is_ok() { if crossterm::event::poll(poll).is_ok() {
if tx.send(crossterm::event::read().unwrap()).is_err() { if tx.send(crossterm::event::read().unwrap()).is_err() {
break break
} }

View file

@ -4,8 +4,9 @@ pub use std::thread::spawn;
pub use std::time::Duration; pub use std::time::Duration;
pub use std::sync::{ pub use std::sync::{
Arc, Arc,
Mutex,
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
mpsc::{channel, Sender, Receiver} mpsc::{self, channel, Sender, Receiver}
}; };
pub use crossterm::{ pub use crossterm::{
QueueableCommand, QueueableCommand,
@ -24,10 +25,16 @@ pub use jack::{
ClosureProcessHandler, ClosureProcessHandler,
Control, Control,
Frames, Frames,
MidiIn,
MidiOut,
NotificationHandler, NotificationHandler,
Port, Port,
PortId, PortId,
ProcessHandler,
ProcessScope, ProcessScope,
Transport,
TransportState,
TransportStatePosition
}; };
pub type Jack<N> = AsyncClient< pub type Jack<N> = AsyncClient<
N, N,

View file

@ -37,7 +37,7 @@ pub fn render_box (
let edge: String = std::iter::repeat("").take(w.saturating_sub(2) as usize).collect(); let edge: String = std::iter::repeat("").take(w.saturating_sub(2) as usize).collect();
stdout.queue(MoveTo(x, y))?.queue(PrintStyledContent(format!("{edge}").bold().yellow()))?; stdout.queue(MoveTo(x, y))?.queue(PrintStyledContent(format!("{edge}").bold().yellow()))?;
if let Some(title) = title { if let Some(title) = title {
stdout.queue(MoveTo(x+1, y))?.queue(PrintStyledContent(format!(" {title} ").bold().yellow()))?; stdout.queue(MoveTo(x+1, y))?.queue(PrintStyledContent(format!(" {title} ").yellow()))?;
} }
for row in y+1..y+h { for row in y+1..y+h {
stdout.queue(MoveTo(x, row))?.queue(PrintStyledContent("".bold().yellow()))?; stdout.queue(MoveTo(x, row))?.queue(PrintStyledContent("".bold().yellow()))?;

View file

@ -14,23 +14,62 @@ pub const ACTIONS: [(&'static str, &'static str);3] = [
pub struct Transport { pub struct Transport {
exited: bool, exited: bool,
sample_rate: u64, title: String,
position: u64, client: ::jack::Client,
bpm: f64, transport: ::jack::Transport,
//position: Arc<Mutex<Option<TransportStatePosition>>>,
//poll_thread: std::thread::JoinHandle<()>,
} }
impl Transport { impl Transport {
pub fn new () -> Result<Self, Box<dyn Error>> { pub fn new () -> Result<Self, Box<dyn Error>> {
let (client, status) = Client::new(
"bloop_transport_client",
ClientOptions::NO_START_SERVER
)?;
// Poll transport state every 10ms
//let poll = std::time::Duration::from_millis(16);
//let poll_thread = {
//let transport = transport.clone();
//let position = position.clone();
//std::thread::spawn(move || loop {
//std::thread::sleep(poll);
//match transport.query() {
//Ok(state) => *position.lock().unwrap() = Some(state),
//Err(error) => {
//*position.lock().unwrap() = None;
////println!("{error:?}");
//}
//}
//})
//};
Ok(Self { Ok(Self {
exited: false, exited: false,
sample_rate: 48000, title: String::from("Untitled project"),
position: 0, transport: client.transport(),
bpm: 120.0 client,
//position,
//poll_thread
}) })
} }
pub fn play_from_start_or_stop_and_rewind (&mut self) { pub fn play_from_start_or_stop_and_rewind (&mut self) {
} }
pub fn play_or_pause (&mut self) {
pub fn play_or_pause (&mut self) -> Result<(), Box<dyn Error>> {
match self.transport.query_state()? {
TransportState::Stopped => self.play(),
TransportState::Rolling => self.stop(),
_ => Ok(())
}
}
pub fn play (&mut self) -> Result<(), Box<dyn Error>> {
Ok(self.transport.start()?)
}
pub fn stop (&mut self) -> Result<(), Box<dyn Error>> {
Ok(self.transport.stop()?)
} }
} }

View file

@ -1,6 +1,6 @@
use crate::prelude::*; use crate::prelude::*;
use super::*; use super::*;
pub fn handle (state: &mut Transport, event: &Event) -> Result<(), Box<dyn Error>> { pub fn handle (state: &mut super::Transport, event: &Event) -> Result<(), Box<dyn Error>> {
Ok(()) Ok(())
} }

View file

@ -7,31 +7,58 @@ pub fn render (
mut offset: (u16, u16) mut offset: (u16, u16)
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
let move_to = |col, row| MoveTo(offset.0 + col, offset.1 + row); let move_to = |col, row| MoveTo(offset.0 + col, offset.1 + row);
let position = state.transport.query();
stdout.queue(move_to( 1, 0))?.queue( stdout.queue(move_to( 1, 0))?.queue(
Print("Project: ") Print("Project: ")
)?.queue(move_to(10, 0))?.queue( )?.queue(move_to(10, 0))?.queue(
PrintStyledContent("The Quick Brown Fox - Jumping Over Lazy Dogs".white().bold()) PrintStyledContent(state.title.clone().white().bold())
)?.queue(move_to( 1, 1))?.queue(
Print("Rate: ")
)?.queue(move_to( 7, 1))?.queue(
PrintStyledContent("48000Hz".white().bold())
)?.queue(move_to(20, 1))?.queue(
Print("BPM: ")
)?.queue(move_to(25, 1))?.queue(
PrintStyledContent("120.34".white().bold())
)?.queue(move_to(35, 1))?.queue(
Print("Signature: ")
)?.queue(move_to(46, 1))?.queue(
PrintStyledContent("4 / 4".white().bold())
)?.queue(move_to( 1, 2))?.queue(
Print("Time: ")
)?.queue(move_to( 7, 2))?.queue(
PrintStyledContent("1m 23.456s".white().bold())
)?.queue(move_to(20, 2))?.queue(
Print("Beat: ")
)?.queue(move_to(26, 2))?.queue(
PrintStyledContent("30x 3/4".white().bold())
)?; )?;
if let Ok(position) = state.transport.query() {
let frame = position.pos.frame();
let rate = position.pos.frame_rate();
let bbt = position.pos.bbt();
stdout
.queue(move_to( 1, 1))?.queue(Print("Frame: "))?
.queue(move_to( 1, 2))?.queue(
PrintStyledContent(
format!("{frame}").white().bold(),
))?
.queue(move_to(11, 1))?.queue(Print("Rate: "))?
.queue(move_to(11, 2))?.queue(
PrintStyledContent(match rate {
Some(rate) => format!("{rate}Hz"),
None => String::from("(none)"),
}.white().bold())
)?
.queue(move_to(20, 1))?.queue(Print("Time: "))?
.queue(move_to(20, 2))?.queue(
PrintStyledContent(match rate {
Some(rate) => format!("{:.03}", frame as f64 / rate as f64),
None => String::from("(none)")
}.white().bold())
)?
.queue(move_to(30, 1))?.queue(Print("BPM: "))?
.queue(move_to(30, 2))?.queue(
PrintStyledContent(match bbt {
Some(bbt) => format!("{:.01}", bbt.bpm),
None => String::from("(none)")
}.white().bold())
)?
.queue(move_to(39, 1))?.queue(Print("Timesig: "))?
.queue(move_to(39, 2))?.queue(
PrintStyledContent(match bbt {
Some(bbt) => format!("{}/{}", bbt.sig_num, bbt.sig_denom),
None => String::from("(none)")
}.white().bold())
)?
.queue(move_to(50, 1))?.queue(Print("Beat: "))?
.queue(move_to(50, 2))?.queue(
PrintStyledContent(match bbt {
Some(bbt) => format!("{}.{}.{}", bbt.bar, bbt.beat, bbt.tick),
None => String::from("(none)")
}.white().bold())
)?;
}
Ok(()) Ok(())
} }