wip: port: make device

This commit is contained in:
🪞👃🪞 2025-05-21 00:07:35 +03:00
parent 447638ee71
commit cb7e4f7a95
31 changed files with 602 additions and 865 deletions

View file

@ -1,13 +1,5 @@
use crate::*;
/// Define a type alias for iterators of sized items (columns).
macro_rules! def_sizes_iter {
($Type:ident => $($Item:ty),+) => {
pub trait $Type<'a> =
Iterator<Item=(usize, $(&'a $Item,)+ usize, usize)> + Send + Sync + 'a;
}
}
mod arranger_api; pub use self::arranger_api::*;
mod arranger_clip; pub use self::arranger_clip::*;
mod arranger_model; pub use self::arranger_model::*;
@ -20,7 +12,7 @@ def_sizes_iter!(ScenesSizes => Scene);
def_sizes_iter!(TracksSizes => Track);
def_sizes_iter!(InputsSizes => MidiInput);
def_sizes_iter!(OutputsSizes => MidiOutput);
def_sizes_iter!(PortsSizes => Arc<str>, [PortConnect]);
def_sizes_iter!(PortsSizes => Arc<str>, [Connect]);
pub(crate) fn wrap (bg: Color, fg: Color, content: impl Content<TuiOut>) -> impl Content<TuiOut> {
let left = Tui::fg_bg(bg, Reset, Fixed::x(1, RepeatV("")));

View file

@ -156,7 +156,7 @@ impl ArrangementCommand {
fn output_add (arranger: &mut Arrangement) -> Perhaps<Self> {
arranger.midi_outs.push(MidiOutput::new(
arranger.jack(),
format!("/M{}", arranger.midi_outs.len() + 1),
&format!("/M{}", arranger.midi_outs.len() + 1),
&[]
)?);
Ok(None)
@ -164,7 +164,7 @@ impl ArrangementCommand {
fn input_add (arranger: &mut Arrangement) -> Perhaps<Self> {
arranger.midi_ins.push(MidiInput::new(
arranger.jack(),
format!("M{}/", arranger.midi_ins.len() + 1),
&format!("M{}/", arranger.midi_ins.len() + 1),
&[]
)?);
Ok(None)

View file

@ -1,9 +1,9 @@
use crate::*;
has!(Jack: |self: Arrangement|self.jack);
has!(Jack<'static>: |self: Arrangement|self.jack);
has!(Clock: |self: Arrangement|self.clock);
has!(Selection: |self: Arrangement|self.selection);
has!(Vec<MidiInput>: |self: Arrangement|self.midi_ins);
has!(Vec<MidiOutput>: |self: Arrangement|self.midi_outs);
has!(Vec<MidiInput>: |self: Arrangement|self.midi_ins);
has!(Vec<MidiOutput>: |self: Arrangement|self.midi_outs);
has!(Vec<Scene>: |self: Arrangement|self.scenes);
has!(Vec<Track>: |self: Arrangement|self.tracks);
has!(Measure<TuiOut>: |self: Arrangement|self.size);
@ -15,24 +15,24 @@ maybe_has!(Scene: |self: Arrangement|
{ Has::<Selection>::get(self).track().map(|index|Has::<Vec<Scene>>::get(self).get(index)).flatten() };
{ Has::<Selection>::get(self).track().map(|index|Has::<Vec<Scene>>::get_mut(self).get_mut(index)).flatten() });
from_dsl!(MidiInputCommand: |state: Arrangement, iter|state.selected_midi_in().as_ref()
.map(|t|FromDsl::take_from(t, iter)).transpose().map(|x|x.flatten()));
.map(|t|Namespace::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(MidiOutputCommand: |state: Arrangement, iter|state.selected_midi_out().as_ref()
.map(|t|FromDsl::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(DeviceCommand: |state: Arrangement, iter|state.selected_device().as_ref()
.map(|t|FromDsl::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(TrackCommand: |state: Arrangement, iter|state.selected_track().as_ref()
.map(|t|FromDsl::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(SceneCommand: |state: Arrangement, iter|state.selected_scene().as_ref()
.map(|t|FromDsl::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(ClipCommand: |state: Arrangement, iter|state.selected_clip().as_ref()
.map(|t|FromDsl::take_from(t, iter)).transpose().map(|x|x.flatten()));
.map(|t|Namespace::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(DeviceCommand:|state: Arrangement, iter|state.selected_device().as_ref()
.map(|t|Namespace::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(TrackCommand: |state: Arrangement, iter|state.selected_track().as_ref()
.map(|t|Namespace::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(SceneCommand: |state: Arrangement, iter|state.selected_scene().as_ref()
.map(|t|Namespace::take_from(t, iter)).transpose().map(|x|x.flatten()));
from_dsl!(ClipCommand: |state: Arrangement, iter|state.selected_clip().as_ref()
.map(|t|Namespace::take_from(t, iter)).transpose().map(|x|x.flatten()));
#[tengri_proc::expose] impl Arrangement {
fn selected_midi_in (&self) -> Option<MidiInput> { todo!() }
fn selected_midi_out (&self) -> Option<MidiOutput> { todo!() }
fn selected_device (&self) -> Option<Device> { todo!() }
fn selected_track (&self) -> Option<Track> { todo!() }
fn selected_scene (&self) -> Option<Scene> { todo!() }
fn selected_clip (&self) -> Option<MidiClip> { todo!() }
fn selected_device (&self) -> Option<Device> { todo!() }
fn selected_track (&self) -> Option<Track> { todo!() }
fn selected_scene (&self) -> Option<Scene> { todo!() }
fn selected_clip (&self) -> Option<MidiClip> { todo!() }
fn _todo_usize_stub_ (&self) -> usize { todo!() }
fn _todo_arc_str_stub_ (&self) -> Arc<str> { todo!() }
fn _todo_item_theme_stub (&self) -> ItemTheme { todo!() }
@ -47,7 +47,7 @@ from_dsl!(ClipCommand: |state: Arrangement, iter|state.selected_clip().as_
/// Base color.
pub color: ItemTheme,
/// Jack client handle
pub jack: Jack,
pub jack: Jack<'static>,
/// Source of time
pub clock: Clock,
/// Allows one MIDI clip to be edited
@ -152,64 +152,6 @@ impl Arrangement {
clip.write().unwrap().toggle_loop()
}
}
/// Add multiple tracks
pub fn tracks_add (
&mut self,
count: usize,
width: Option<usize>,
mins: &[PortConnect],
mouts: &[PortConnect],
) -> Usually<()> {
let jack = self.jack().clone();
let track_color_1 = ItemColor::random();
let track_color_2 = ItemColor::random();
for i in 0..count {
let color = track_color_1.mix(track_color_2, i as f32 / count as f32).into();
let mut track = self.track_add(None, Some(color), mins, mouts)?.1;
if let Some(width) = width {
track.width = width;
}
}
Ok(())
}
/// Add a track
pub fn track_add (
&mut self,
name: Option<&str>,
color: Option<ItemTheme>,
mins: &[PortConnect],
mouts: &[PortConnect],
) -> Usually<(usize, &mut Track)> {
let name: Arc<str> = name.map_or_else(
||format!("trk{:02}", self.track_last).into(),
|x|x.to_string().into()
);
self.track_last += 1;
let mut track = Track {
width: (name.len() + 2).max(12),
color: color.unwrap_or_else(ItemTheme::random),
sequencer: Sequencer::new(
&format!("{name}"),
self.jack(),
Some(self.clock()),
None,
mins,
mouts
)?,
name,
..Default::default()
};
self.tracks_mut().push(track);
let len = self.tracks().len();
let index = len - 1;
for scene in self.scenes_mut().iter_mut() {
while scene.clips.len() < len {
scene.clips.push(None);
}
}
Ok((index, &mut self.tracks_mut()[index]))
}
}
#[cfg(feature = "sampler")]

View file

@ -1,5 +1,62 @@
use crate::*;
impl Arrangement {
/// Add multiple tracks
pub fn tracks_add (
&mut self,
count: usize, width: Option<usize>,
mins: &[Connect], mouts: &[Connect],
) -> Usually<()> {
let jack = self.jack().clone();
let track_color_1 = ItemColor::random();
let track_color_2 = ItemColor::random();
for i in 0..count {
let color = track_color_1.mix(track_color_2, i as f32 / count as f32).into();
let mut track = self.track_add(None, Some(color), mins, mouts)?.1;
if let Some(width) = width {
track.width = width;
}
}
Ok(())
}
/// Add a track
pub fn track_add (
&mut self,
name: Option<&str>, color: Option<ItemTheme>,
mins: &[Connect], mouts: &[Connect],
) -> Usually<(usize, &mut Track)> {
let name: Arc<str> = name.map_or_else(
||format!("trk{:02}", self.track_last).into(),
|x|x.to_string().into()
);
self.track_last += 1;
let mut track = Track {
width: (name.len() + 2).max(12),
color: color.unwrap_or_else(ItemTheme::random),
sequencer: Sequencer::new(
&format!("{name}"),
self.jack(),
Some(self.clock()),
None,
mins,
mouts
)?,
name,
..Default::default()
};
self.tracks_mut().push(track);
let len = self.tracks().len();
let index = len - 1;
for scene in self.scenes_mut().iter_mut() {
while scene.clips.len() < len {
scene.clips.push(None);
}
}
Ok((index, &mut self.tracks_mut()[index]))
}
}
impl<T: Has<Vec<Track>> + Send + Sync> HasTracks for T {}
pub trait HasTracks: Has<Vec<Track>> + Send + Sync {
@ -132,11 +189,11 @@ impl Track {
pub fn new (
name: &impl AsRef<str>,
color: Option<ItemTheme>,
jack: &Jack,
jack: &Jack<'static>,
clock: Option<&Clock>,
clip: Option<&Arc<RwLock<MidiClip>>>,
midi_from: &[PortConnect],
midi_to: &[PortConnect],
midi_from: &[Connect],
midi_to: &[Connect],
) -> Usually<Self> {
Ok(Self {
name: name.as_ref().into(),
@ -156,19 +213,19 @@ impl Track {
pub fn new_with_sampler (
name: &impl AsRef<str>,
color: Option<ItemTheme>,
jack: &Jack,
jack: &Jack<'static>,
clock: Option<&Clock>,
clip: Option<&Arc<RwLock<MidiClip>>>,
midi_from: &[PortConnect],
midi_to: &[PortConnect],
audio_from: &[&[PortConnect];2],
audio_to: &[&[PortConnect];2],
midi_from: &[Connect],
midi_to: &[Connect],
audio_from: &[&[Connect];2],
audio_to: &[&[Connect];2],
) -> Usually<Self> {
let mut track = Self::new(name, color, jack, clock, clip, midi_from, midi_to)?;
track.devices.push(Device::Sampler(Sampler::new(
jack,
&format!("{}/sampler", name.as_ref()),
&[PortConnect::exact(format!("{}:{}",
&[Connect::exact(format!("{}:{}",
jack.with_client(|c|c.name().to_string()),
track.sequencer.midi_outs[0].name()
))],
@ -284,10 +341,10 @@ pub(crate) fn io_ports <'a, T: PortsSizes<'a>> (
) -> impl Content<TuiOut> + 'a {
Map::new(iter, move|(
index, name, connections, y, y2
): (usize, &'a Arc<str>, &'a [PortConnect], usize, usize), _|
): (usize, &'a Arc<str>, &'a [Connect], usize, usize), _|
map_south(y as u16, (y2-y) as u16, Bsp::s(
Fill::x(Tui::bold(true, Tui::fg_bg(fg, bg, Align::w(Bsp::e(" 󰣲 ", name))))),
Map::new(||connections.iter(), move|connect: &'a PortConnect, index|map_south(index as u16, 1,
Map::new(||connections.iter(), move|connect: &'a Connect, index|map_south(index as u16, 1,
Fill::x(Align::w(Tui::bold(false, Tui::fg_bg(fg, bg,
&connect.info)))))))))
}
@ -297,7 +354,7 @@ pub(crate) fn io_conns <'a, T: PortsSizes<'a>> (
) -> impl Content<TuiOut> + 'a {
Map::new(iter, move|(
index, name, connections, y, y2
): (usize, &'a Arc<str>, &'a [PortConnect], usize, usize), _|
): (usize, &'a Arc<str>, &'a [Connect], usize, usize), _|
map_south(y as u16, (y2-y) as u16, Bsp::s(
Fill::x(Tui::bold(true, wrap(bg, fg, Fill::x(Align::w("▞▞▞▞ ▞▞▞▞"))))),
Map::new(||connections.iter(), move|connect, index|map_south(index as u16, 1,

View file

@ -39,7 +39,7 @@ impl Arrangement {
pub fn view_outputs <'a> (&'a self, theme: ItemTheme) -> impl Content<TuiOut> + 'a {
let mut h = 1;
for output in self.midi_outs().iter() {
h += 1 + output.conn().len();
h += 1 + output.connections.len();
}
let h = h as u16;
let list = Bsp::s(
@ -50,8 +50,8 @@ impl Arrangement {
Align::w(Bsp::e("", Tui::fg(Rgb(255,255,255),Tui::bold(true, port.name())))),
Fill::x(Align::e(format!("{}/{} ",
port.port().get_connections().len(),
port.conn().len())))))));
for (index, conn) in port.conn().iter().enumerate() {
port.connections.len())))))));
for (index, conn) in port.connections.iter().enumerate() {
add(&Fixed::y(1, Fill::x(Align::w(format!(" c{index:02}{}", conn.info())))));
}
}
@ -72,7 +72,7 @@ impl Arrangement {
Either(true, Tui::fg(Green, ""), " · "),
Either(false, Tui::fg(Yellow, ""), " · "),
))));
for (index, conn) in port.conn().iter().enumerate() {
for (index, conn) in port.connections.iter().enumerate() {
add(&Fixed::y(1, Fill::x("")));
}
}})))}}))))))

View file

@ -43,7 +43,7 @@ impl std::fmt::Debug for Clock {
}
impl Clock {
pub fn new (jack: &Jack, bpm: Option<f64>) -> Usually<Self> {
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 {
@ -56,9 +56,9 @@ impl Clock {
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", &[])?))),
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", &[])?))),
};
if let Some(bpm) = bpm {
clock.timebase.bpm.set(bpm);

View file

@ -24,20 +24,29 @@ pub(crate) use Color::*;
mod device; pub use self::device::*;
mod dialog; pub use self::dialog::*;
/// Define a type alias for iterators of sized items (columns).
macro_rules! def_sizes_iter {
($Type:ident => $($Item:ty),+) => {
pub trait $Type<'a> =
Iterator<Item=(usize, $(&'a $Item,)+ usize, usize)> + Send + Sync + 'a;
}
}
#[cfg(feature = "arranger")] mod arranger; #[cfg(feature = "arranger")] pub use self::arranger::*;
#[cfg(feature = "browser")] mod browser; #[cfg(feature = "browser")] pub use self::browser::*;
#[cfg(feature = "clap")] mod clap; #[cfg(feature = "clap")] pub use self::clap::*;
#[cfg(feature = "clock")] mod clock; #[cfg(feature = "clock")] pub use self::clock::*;
#[cfg(feature = "editor")] mod editor; #[cfg(feature = "editor")] pub use self::editor::*;
#[cfg(feature = "pool")] mod pool; #[cfg(feature = "pool")] pub use self::pool::*;
#[cfg(feature = "sequencer")] mod sequencer; #[cfg(feature = "sequencer")] pub use self::sequencer::*;
#[cfg(feature = "sampler")] mod sampler; #[cfg(feature = "sampler")] pub use self::sampler::*;
#[cfg(feature = "lv2")] mod lv2; #[cfg(feature = "lv2")] pub use self::lv2::*;
#[cfg(feature = "meter")] mod meter; #[cfg(feature = "meter")] pub use self::meter::*;
#[cfg(feature = "mixer")] mod mixer; #[cfg(feature = "mixer")] pub use self::mixer::*;
#[cfg(feature = "lv2")] mod lv2; #[cfg(feature = "lv2")] pub use self::lv2::*;
#[cfg(feature = "pool")] mod pool; #[cfg(feature = "pool")] pub use self::pool::*;
#[cfg(feature = "port")] mod port; #[cfg(feature = "port")] pub use self::port::*;
#[cfg(feature = "sampler")] mod sampler; #[cfg(feature = "sampler")] pub use self::sampler::*;
#[cfg(feature = "sequencer")] mod sequencer; #[cfg(feature = "sequencer")] pub use self::sequencer::*;
#[cfg(feature = "sf2")] mod sf2; #[cfg(feature = "sf2")] pub use self::sf2::*;
#[cfg(feature = "vst2")] mod vst2; #[cfg(feature = "vst2")] pub use self::vst2::*;
#[cfg(feature = "vst3")] mod vst3; #[cfg(feature = "vst3")] pub use self::vst3::*;
#[cfg(feature = "clap")] mod clap; #[cfg(feature = "clap")] pub use self::clap::*;
pub fn button_2 <'a> (
key: impl Content<TuiOut> + 'a, label: impl Content<TuiOut> + 'a, editing: bool,

View file

@ -4,7 +4,7 @@ use crate::*;
#[derive(Debug)]
pub struct Lv2 {
/// JACK client handle (needs to not be dropped for standalone mode to work).
pub jack: Jack,
pub jack: Jack<'static>,
pub name: Arc<str>,
pub path: Option<Arc<str>>,
pub selected: usize,
@ -26,7 +26,7 @@ pub struct Lv2 {
impl Lv2 {
pub fn new (
jack: &Jack,
jack: &Jack<'static>,
name: &str,
uri: &str,
) -> Usually<Self> {

View file

@ -14,7 +14,7 @@ pub struct Pool {
}
from_dsl!(BrowserCommand: |state: Pool, iter|Ok(state.browser
.as_ref()
.map(|p|FromDsl::take_from(p, iter))
.map(|p|Namespace::take_from(p, iter))
.transpose()?
.flatten()));
impl Default for Pool {

View file

@ -0,0 +1,8 @@
mod port_audio_out; pub use self::port_audio_out::*;
mod port_audio_in; pub use self::port_audio_in::*;
mod port_connect; pub use self::port_connect::*;
mod port_midi_out; pub use self::port_midi_out::*;
mod port_midi_in; pub use self::port_midi_in::*;
pub(crate) use ConnectName::*;
pub(crate) use ConnectScope::*;
pub(crate) use ConnectStatus::*;

View file

@ -0,0 +1,44 @@
use crate::*;
#[derive(Debug)] pub struct AudioInput {
/// Handle to JACK client, for receiving reconnect events.
jack: Jack<'static>,
/// Port name
name: Arc<str>,
/// Port handle.
port: Port<AudioIn>,
/// List of ports to connect to.
pub connections: Vec<Connect>,
}
has!(Jack<'static>: |self: AudioInput|self.jack);
impl JackPort for AudioInput {
type Port = AudioIn;
type Pair = AudioOut;
fn name (&self) -> &Arc<str> {
&self.name
}
fn port (&self) -> &Port<Self::Port> {
&self.port
}
fn port_mut (&mut self) -> &mut Port<Self::Port> {
&mut self.port
}
fn into_port (self) -> Port<Self::Port> {
self.port
}
fn connections (&self) -> &[Connect] {
self.connections.as_slice()
}
fn new (jack: &Jack<'static>, name: &impl AsRef<str>, connect: &[Connect])
-> Usually<Self> where Self: Sized
{
let port = Self {
port: Self::register(jack, name)?,
jack: jack.clone(),
name: name.as_ref().into(),
connections: connect.to_vec()
};
port.connect_to_matching()?;
Ok(port)
}
}

View file

@ -0,0 +1,44 @@
use crate::*;
#[derive(Debug)] pub struct AudioOutput {
/// Handle to JACK client, for receiving reconnect events.
jack: Jack<'static>,
/// Port name
name: Arc<str>,
/// Port handle.
port: Port<AudioOut>,
/// List of ports to connect to.
pub connections: Vec<Connect>,
}
has!(Jack<'static>: |self: AudioOutput|self.jack);
impl JackPort for AudioOutput {
type Port = AudioOut;
type Pair = AudioIn;
fn name (&self) -> &Arc<str> {
&self.name
}
fn port (&self) -> &Port<Self::Port> {
&self.port
}
fn port_mut (&mut self) -> &mut Port<Self::Port> {
&mut self.port
}
fn into_port (self) -> Port<Self::Port> {
self.port
}
fn connections (&self) -> &[Connect] {
self.connections.as_slice()
}
fn new (jack: &Jack<'static>, name: &impl AsRef<str>, connect: &[Connect])
-> Usually<Self> where Self: Sized
{
let port = Self {
port: Self::register(jack, name)?,
jack: jack.clone(),
name: name.as_ref().into(),
connections: connect.to_vec()
};
port.connect_to_matching()?;
Ok(port)
}
}

View file

@ -0,0 +1,181 @@
use crate::*;
pub trait JackPort: HasJack<'static> {
type Port: PortSpec + Default;
type Pair: PortSpec + Default;
fn new (jack: &Jack<'static>, name: &impl AsRef<str>, connect: &[Connect])
-> Usually<Self> where Self: Sized;
fn register (jack: &Jack<'static>, name: &impl AsRef<str>) -> Usually<Port<Self::Port>> {
Ok(jack.register_port::<Self::Port>(name.as_ref())?)
}
fn name (&self) -> &Arc<str>;
fn connections (&self) -> &[Connect];
fn port (&self) -> &Port<Self::Port>;
fn port_mut (&mut self) -> &mut Port<Self::Port>;
fn into_port (self) -> Port<Self::Port> where Self: Sized;
fn close (self) -> Usually<()> where Self: Sized {
let jack = self.jack().clone();
Ok(jack.with_client(|c|c.unregister_port(self.into_port()))?)
}
fn ports (&self, re_name: Option<&str>, re_type: Option<&str>, flags: PortFlags) -> Vec<String> {
self.with_client(|c|c.ports(re_name, re_type, flags))
}
fn port_by_id (&self, id: u32) -> Option<Port<Unowned>> {
self.with_client(|c|c.port_by_id(id))
}
fn port_by_name (&self, name: impl AsRef<str>) -> Option<Port<Unowned>> {
self.with_client(|c|c.port_by_name(name.as_ref()))
}
fn connect_to_matching <'k> (&'k self) -> Usually<()> {
for connect in self.connections().iter() {
//panic!("{connect:?}");
let status = match &connect.name {
Exact(name) => self.connect_exact(name),
RegExp(re) => self.connect_regexp(re, connect.scope),
}?;
*connect.status.write().unwrap() = status;
}
Ok(())
}
fn connect_exact <'k> (&'k self, name: &str) ->
Usually<Vec<(Port<Unowned>, Arc<str>, ConnectStatus)>>
{
self.with_client(move|c|{
let mut status = vec![];
for port in c.ports(None, None, PortFlags::empty()).iter() {
if port.as_str() == &*name {
if let Some(port) = c.port_by_name(port.as_str()) {
let port_status = self.connect_to_unowned(&port)?;
let name = port.name()?.into();
status.push((port, name, port_status));
if port_status == Connected {
break
}
}
}
}
Ok(status)
})
}
fn connect_regexp <'k> (
&'k self, re: &str, scope: ConnectScope
) -> Usually<Vec<(Port<Unowned>, Arc<str>, ConnectStatus)>> {
self.with_client(move|c|{
let mut status = vec![];
let ports = c.ports(Some(&re), None, PortFlags::empty());
for port in ports.iter() {
if let Some(port) = c.port_by_name(port.as_str()) {
let port_status = self.connect_to_unowned(&port)?;
let name = port.name()?.into();
status.push((port, name, port_status));
if port_status == Connected && scope == One {
break
}
}
}
Ok(status)
})
}
/** Connect to a matching port by name. */
fn connect_to_name (&self, name: impl AsRef<str>) -> Usually<ConnectStatus> {
self.with_client(|c|if let Some(ref port) = c.port_by_name(name.as_ref()) {
self.connect_to_unowned(port)
} else {
Ok(Missing)
})
}
/** Connect to a matching port by reference. */
fn connect_to_unowned (&self, port: &Port<Unowned>) -> Usually<ConnectStatus> {
self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(self.port(), port) {
Connected
} else if let Ok(_) = c.connect_ports(port, self.port()) {
Connected
} else {
Mismatch
}))
}
/** Connect to an owned matching port by reference. */
fn connect_to_owned (&self, port: &Port<Self::Pair>) -> Usually<ConnectStatus> {
self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(self.port(), port) {
Connected
} else if let Ok(_) = c.connect_ports(port, self.port()) {
Connected
} else {
Mismatch
}))
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConnectName {
/** Exact match */
Exact(Arc<str>),
/** Match regular expression */
RegExp(Arc<str>),
}
#[derive(Clone, Copy, Debug, PartialEq)] pub enum ConnectScope {
One,
All
}
#[derive(Clone, Copy, Debug, PartialEq)] pub enum ConnectStatus {
Missing,
Disconnected,
Connected,
Mismatch,
}
#[derive(Clone, Debug)] pub struct Connect {
pub name: ConnectName,
pub scope: ConnectScope,
pub status: Arc<RwLock<Vec<(Port<Unowned>, Arc<str>, ConnectStatus)>>>,
pub info: Arc<String>,
}
impl Connect {
pub fn collect (exact: &[impl AsRef<str>], re: &[impl AsRef<str>], re_all: &[impl AsRef<str>])
-> Vec<Self>
{
let mut connections = vec![];
for port in exact.iter() { connections.push(Self::exact(port)) }
for port in re.iter() { connections.push(Self::regexp(port)) }
for port in re_all.iter() { connections.push(Self::regexp_all(port)) }
connections
}
/// Connect to this exact port
pub fn exact (name: impl AsRef<str>) -> Self {
let info = format!("=:{}", name.as_ref()).into();
let name = Exact(name.as_ref().into());
Self { name, scope: One, status: Arc::new(RwLock::new(vec![])), info }
}
pub fn regexp (name: impl AsRef<str>) -> Self {
let info = format!("~:{}", name.as_ref()).into();
let name = RegExp(name.as_ref().into());
Self { name, scope: One, status: Arc::new(RwLock::new(vec![])), info }
}
pub fn regexp_all (name: impl AsRef<str>) -> Self {
let info = format!("+:{}", name.as_ref()).into();
let name = RegExp(name.as_ref().into());
Self { name, scope: All, status: Arc::new(RwLock::new(vec![])), info }
}
pub fn info (&self) -> Arc<str> {
let status = {
let status = self.status.read().unwrap();
let mut ok = 0;
for (_, _, state) in status.iter() {
if *state == Connected {
ok += 1
}
}
format!("{ok}/{}", status.len())
};
let scope = match self.scope {
One => " ", All => "*",
};
let name = match &self.name {
Exact(name) => format!("= {name}"), RegExp(name) => format!("~ {name}"),
};
format!(" ({}) {} {}", status, scope, name).into()
}
}

View file

@ -0,0 +1,109 @@
use crate::*;
//impl_port!(MidiInput: MidiOut -> MidiIn |j, n|j.register_port::<MidiOut>(n));
#[derive(Debug)] pub struct MidiInput {
/// Handle to JACK client, for receiving reconnect events.
jack: Jack<'static>,
/// Port name
name: Arc<str>,
/// Port handle.
port: Port<MidiIn>,
/// List of currently held notes.
held: Arc<RwLock<[bool;128]>>,
/// List of ports to connect to.
pub connections: Vec<Connect>,
}
has!(Jack<'static>: |self: MidiInput|self.jack);
impl JackPort for MidiInput {
type Port = MidiIn;
type Pair = MidiOut;
fn name (&self) -> &Arc<str> {
&self.name
}
fn port (&self) -> &Port<Self::Port> {
&self.port
}
fn port_mut (&mut self) -> &mut Port<Self::Port> {
&mut self.port
}
fn into_port (self) -> Port<Self::Port> {
self.port
}
fn connections (&self) -> &[Connect] {
self.connections.as_slice()
}
fn new (jack: &Jack<'static>, name: &impl AsRef<str>, connect: &[Connect])
-> Usually<Self> where Self: Sized
{
let port = Self {
port: Self::register(jack, name)?,
jack: jack.clone(),
name: name.as_ref().into(),
connections: connect.to_vec(),
held: Arc::new(RwLock::new([false;128]))
};
port.connect_to_matching()?;
Ok(port)
}
}
impl MidiInput {
pub fn parsed <'a> (&'a self, scope: &'a ProcessScope) -> impl Iterator<Item=(usize, LiveEvent<'a>, &'a [u8])> {
parse_midi_input(self.port().iter(scope))
}
}
#[tengri_proc::command(MidiInput)]
impl MidiInputCommand {
//fn _todo_ (_port: &mut MidiInput) -> Perhaps<Self> { Ok(None) }
}
impl<T: Has<Vec<MidiInput>>> HasMidiIns for T {
fn midi_ins (&self) -> &Vec<MidiInput> {
self.get()
}
fn midi_ins_mut (&mut self) -> &mut Vec<MidiInput> {
self.get_mut()
}
}
/// Trait for thing that may receive MIDI.
pub trait HasMidiIns {
fn midi_ins (&self) -> &Vec<MidiInput>;
fn midi_ins_mut (&mut self) -> &mut Vec<MidiInput>;
/// Collect MIDI input from app ports (TODO preallocate large buffers)
fn midi_input_collect <'a> (&'a self, scope: &'a ProcessScope) -> CollectedMidiInput<'a> {
self.midi_ins().iter()
.map(|port|port.port().iter(scope)
.map(|RawMidi { time, bytes }|(time, LiveEvent::parse(bytes)))
.collect::<Vec<_>>())
.collect::<Vec<_>>()
}
fn midi_ins_with_sizes <'a> (&'a self) ->
impl Iterator<Item=(usize, &Arc<str>, &[Connect], usize, usize)> + Send + Sync + 'a
{
let mut y = 0;
self.midi_ins().iter().enumerate().map(move|(i, input)|{
let height = 1 + input.connections().len();
let data = (i, input.name(), input.connections(), y, y + height);
y += height;
data
})
}
}
pub type CollectedMidiInput<'a> = Vec<Vec<(u32, Result<LiveEvent<'a>, MidiError>)>>;
impl<T: HasMidiIns + HasJack<'static>> AddMidiIn for T {
fn midi_in_add (&mut self) -> Usually<()> {
let index = self.midi_ins().len();
let port = MidiInput::new(self.jack(), &format!("M/{index}"), &[])?;
self.midi_ins_mut().push(port);
Ok(())
}
}
/// May create new MIDI input ports.
pub trait AddMidiIn {
fn midi_in_add (&mut self) -> Usually<()>;
}

View file

@ -0,0 +1,148 @@
use crate::*;
#[derive(Debug)] pub struct MidiOutput {
/// Handle to JACK client, for receiving reconnect events.
jack: Jack<'static>,
/// Port name
name: Arc<str>,
/// Port handle.
port: Port<MidiOut>,
/// List of ports to connect to.
pub connections: Vec<Connect>,
/// List of currently held notes.
held: Arc<RwLock<[bool;128]>>,
/// Buffer
note_buffer: Vec<u8>,
/// Buffer
output_buffer: Vec<Vec<Vec<u8>>>,
}
has!(Jack<'static>: |self: MidiOutput|self.jack);
impl JackPort for MidiOutput {
type Port = MidiOut;
type Pair = MidiIn;
fn name (&self) -> &Arc<str> {
&self.name
}
fn port (&self) -> &Port<Self::Port> {
&self.port
}
fn port_mut (&mut self) -> &mut Port<Self::Port> {
&mut self.port
}
fn into_port (self) -> Port<Self::Port> {
self.port
}
fn connections (&self) -> &[Connect] {
self.connections.as_slice()
}
fn new (jack: &Jack<'static>, name: &impl AsRef<str>, connect: &[Connect])
-> Usually<Self> where Self: Sized
{
let port = Self::register(jack, name)?;
let jack = jack.clone();
let name = name.as_ref().into();
let connections = connect.to_vec();
let port = Self {
jack,
port,
name,
connections,
held: Arc::new([false;128].into()),
note_buffer: vec![0;8],
output_buffer: vec![vec![];65536],
};
port.connect_to_matching()?;
Ok(port)
}
}
impl MidiOutput {
/// Clear the section of the output buffer that we will be using,
/// emitting "all notes off" at start of buffer if requested.
pub fn buffer_clear (&mut self, scope: &ProcessScope, reset: bool) {
let n_frames = (scope.n_frames() as usize).min(self.output_buffer.len());
for frame in &mut self.output_buffer[0..n_frames] {
frame.clear();
}
if reset {
all_notes_off(&mut self.output_buffer);
}
}
/// Write a note to the output buffer
pub fn buffer_write <'a> (
&'a mut self,
sample: usize,
event: LiveEvent,
) {
self.note_buffer.fill(0);
event.write(&mut self.note_buffer).expect("failed to serialize MIDI event");
self.output_buffer[sample].push(self.note_buffer.clone());
// Update the list of currently held notes.
if let LiveEvent::Midi { ref message, .. } = event {
update_keys(&mut*self.held.write().unwrap(), message);
}
}
/// Write a chunk of MIDI data from the output buffer to the output port.
pub fn buffer_emit (&mut self, scope: &ProcessScope) {
let samples = scope.n_frames() as usize;
let mut writer = self.port.writer(scope);
for (time, events) in self.output_buffer.iter().enumerate().take(samples) {
for bytes in events.iter() {
writer.write(&RawMidi { time: time as u32, bytes }).unwrap_or_else(|_|{
panic!("Failed to write MIDI data: {bytes:?}");
});
}
}
}
}
#[tengri_proc::command(MidiOutput)]
impl MidiOutputCommand {
fn _todo_ (_port: &mut MidiOutput) -> Perhaps<Self> { Ok(None) }
}
impl<T: Has<Vec<MidiOutput>>> HasMidiOuts for T {
fn midi_outs (&self) -> &Vec<MidiOutput> {
self.get()
}
fn midi_outs_mut (&mut self) -> &mut Vec<MidiOutput> {
self.get_mut()
}
}
/// Trait for thing that may output MIDI.
pub trait HasMidiOuts {
fn midi_outs (&self) -> &Vec<MidiOutput>;
fn midi_outs_mut (&mut self) -> &mut Vec<MidiOutput>;
fn midi_outs_with_sizes <'a> (&'a self) ->
impl Iterator<Item=(usize, &Arc<str>, &[Connect], usize, usize)> + Send + Sync + 'a
{
let mut y = 0;
self.midi_outs().iter().enumerate().map(move|(i, output)|{
let height = 1 + output.connections().len();
let data = (i, output.name(), output.connections(), y, y + height);
y += height;
data
})
}
fn midi_outs_emit (&mut self, scope: &ProcessScope) {
for port in self.midi_outs_mut().iter_mut() {
port.buffer_emit(scope)
}
}
}
/// Trail for thing that may gain new MIDI ports.
impl<T: HasMidiOuts + HasJack<'static>> AddMidiOut for T {
fn midi_out_add (&mut self) -> Usually<()> {
let index = self.midi_outs().len();
let port = MidiOutput::new(self.jack(), &format!("{index}/M"), &[])?;
self.midi_outs_mut().push(port);
Ok(())
}
}
/// May create new MIDI output ports.
pub trait AddMidiOut {
fn midi_out_add (&mut self) -> Usually<()>;
}

View file

@ -49,16 +49,16 @@ pub struct Sampler {
impl Sampler {
pub fn new (
jack: &Jack,
jack: &Jack<'static>,
name: impl AsRef<str>,
midi_from: &[PortConnect],
audio_from: &[&[PortConnect];2],
audio_to: &[&[PortConnect];2],
midi_from: &[Connect],
audio_from: &[&[Connect];2],
audio_to: &[&[Connect];2],
) -> Usually<Self> {
let name = name.as_ref();
Ok(Self {
name: name.into(),
midi_in: MidiInput::new(jack, format!("M/{name}"), midi_from)?,
midi_in: MidiInput::new(jack, &format!("M/{name}"), midi_from)?,
audio_ins: vec![
AudioInput::new(jack, &format!("L/{name}"), audio_from[0])?,
AudioInput::new(jack, &format!("R/{name}"), audio_from[1])?,

View file

@ -70,17 +70,17 @@ impl Default for Sequencer {
impl Sequencer {
pub fn new (
name: impl AsRef<str>,
jack: &Jack,
jack: &Jack<'static>,
clock: Option<&Clock>,
clip: Option<&Arc<RwLock<MidiClip>>>,
midi_from: &[PortConnect],
midi_to: &[PortConnect],
midi_from: &[Connect],
midi_to: &[Connect],
) -> Usually<Self> {
let _name = name.as_ref();
let clock = clock.cloned().unwrap_or_default();
Ok(Self {
midi_ins: vec![MidiInput::new(jack, format!("M/{}", name.as_ref()), midi_from)?,],
midi_outs: vec![MidiOutput::new(jack, format!("{}/M", name.as_ref()), midi_to)?, ],
midi_ins: vec![MidiInput::new(jack, &format!("M/{}", name.as_ref()), midi_from)?,],
midi_outs: vec![MidiOutput::new(jack, &format!("{}/M", name.as_ref()), midi_to)?, ],
play_clip: clip.map(|clip|(Moment::zero(&clock.timebase), Some(clip.clone()))),
clock,
reset: true,
@ -101,9 +101,9 @@ impl std::fmt::Debug for Sequencer {
}
}
has!(Clock: |self: Sequencer|self.clock);
has!(Vec<MidiInput>: |self:Sequencer| self.midi_ins);
has!(Vec<MidiOutput>: |self:Sequencer| self.midi_outs);
has!(Clock: |self:Sequencer|self.clock);
has!(Vec<MidiInput>: |self:Sequencer|self.midi_ins);
has!(Vec<MidiOutput>: |self:Sequencer|self.midi_outs);
impl MidiMonitor for Sequencer {
fn notes_in (&self) -> &Arc<RwLock<[bool; 128]>> {