mirror of
https://codeberg.org/unspeaker/tek.git
synced 2026-07-17 15:56:57 +02:00
wip: nermalize
This commit is contained in:
parent
915e13aec8
commit
35197fb826
12 changed files with 4649 additions and 4718 deletions
820
src/sequence.rs
820
src/sequence.rs
|
|
@ -1,3 +1,4 @@
|
|||
use ::std::sync::{Arc, RwLock};
|
||||
|
||||
/// Contains state for viewing and editing a clip.
|
||||
///
|
||||
|
|
@ -594,3 +595,822 @@ pub trait MidiRange: TimeRange + NoteRange {}
|
|||
// Lowest note displayed
|
||||
pub note_lo: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl MidiClip {
|
||||
pub fn new (
|
||||
name: impl AsRef<str>,
|
||||
looped: bool,
|
||||
length: usize,
|
||||
notes: Option<MidiData>,
|
||||
color: Option<ItemTheme>,
|
||||
) -> Self {
|
||||
Self {
|
||||
uuid: uuid::Uuid::new_v4(),
|
||||
name: name.as_ref().into(),
|
||||
ppq: PPQ,
|
||||
length,
|
||||
notes: notes.unwrap_or(vec![Vec::with_capacity(16);length]),
|
||||
looped,
|
||||
loop_start: 0,
|
||||
loop_length: length,
|
||||
percussive: true,
|
||||
color: color.unwrap_or_else(ItemTheme::random)
|
||||
}
|
||||
}
|
||||
pub fn count_midi_messages (&self) -> usize {
|
||||
let mut count = 0;
|
||||
for tick in self.notes.iter() {
|
||||
count += tick.len();
|
||||
}
|
||||
count
|
||||
}
|
||||
pub fn set_length (&mut self, length: usize) {
|
||||
self.length = length;
|
||||
self.notes = vec![Vec::with_capacity(16);length];
|
||||
}
|
||||
pub fn duplicate (&self) -> Self {
|
||||
let mut clone = self.clone();
|
||||
clone.uuid = uuid::Uuid::new_v4();
|
||||
clone
|
||||
}
|
||||
pub fn toggle_loop (&mut self) { self.looped = !self.looped; }
|
||||
pub fn record_event (&mut self, pulse: usize, message: MidiMessage) {
|
||||
if pulse >= self.length { panic!("extend clip first") }
|
||||
self.notes[pulse].push(message);
|
||||
}
|
||||
/// Check if a range `start..end` contains MIDI Note On `k`
|
||||
pub fn contains_note_on (&self, k: u7, start: usize, end: usize) -> bool {
|
||||
for events in self.notes[start.max(0)..end.min(self.notes.len())].iter() {
|
||||
for event in events.iter() {
|
||||
if let MidiMessage::NoteOn {key,..} = event { if *key == k { return true } }
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
pub fn stop_all () -> Self {
|
||||
Self::new(
|
||||
"Stop",
|
||||
false,
|
||||
1,
|
||||
Some(vec![vec![MidiMessage::Controller {
|
||||
controller: 123.into(),
|
||||
value: 0.into()
|
||||
}]]),
|
||||
Some(ItemColor::from_tui(Color::Rgb(32, 32, 32)).into())
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for MidiClip {
|
||||
fn eq (&self, other: &Self) -> bool {
|
||||
self.uuid == other.uuid
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for MidiClip {}
|
||||
|
||||
impl MidiClip {
|
||||
fn _todo_opt_bool_stub_ (&self) -> Option<bool> { todo!() }
|
||||
fn _todo_bool_stub_ (&self) -> bool { 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!() }
|
||||
fn _todo_opt_item_theme_stub (&self) -> Option<ItemTheme> { todo!() }
|
||||
}
|
||||
impl_has!(Sequencer: |self: Track| self.sequencer);
|
||||
impl_has!(Clock: |self: Sequencer| self.clock);
|
||||
impl_has!(Vec<MidiInput>: |self: Sequencer| self.midi_ins);
|
||||
impl_has!(Vec<MidiOutput>: |self: Sequencer| self.midi_outs);
|
||||
impl_has!(Measure<Tui>: |self: MidiEditor| self.size);
|
||||
impl_has!(Measure<Tui>: |self: PianoHorizontal| self.size);
|
||||
impl_default!(Sequencer: Self {
|
||||
clock: Clock::default(),
|
||||
play_clip: None,
|
||||
next_clip: None,
|
||||
midi_ins: vec![],
|
||||
midi_outs: vec![],
|
||||
recording: false,
|
||||
monitoring: true,
|
||||
overdub: false,
|
||||
notes_in: RwLock::new([false;128]).into(),
|
||||
notes_out: RwLock::new([false;128]).into(),
|
||||
note_buf: vec![0;8],
|
||||
midi_buf: vec![],
|
||||
reset: true,
|
||||
});
|
||||
impl Sequencer {
|
||||
pub fn new (
|
||||
name: impl AsRef<str>,
|
||||
jack: &Jack<'static>,
|
||||
#[cfg(feature = "clock")] clock: Option<&Clock>,
|
||||
#[cfg(feature = "clip")] clip: Option<&Arc<RwLock<MidiClip>>>,
|
||||
#[cfg(feature = "port")] midi_from: &[Connect],
|
||||
#[cfg(feature = "port")] midi_to: &[Connect],
|
||||
) -> Usually<Self> {
|
||||
let _name = name.as_ref();
|
||||
#[cfg(feature = "clock")] let clock = clock.cloned().unwrap_or_default();
|
||||
Ok(Self {
|
||||
reset: true,
|
||||
notes_in: RwLock::new([false;128]).into(),
|
||||
notes_out: RwLock::new([false;128]).into(),
|
||||
#[cfg(feature = "port")] midi_ins: vec![MidiInput::new(jack, &format!("M/{}", name.as_ref()), midi_from)?,],
|
||||
#[cfg(feature = "port")] midi_outs: vec![MidiOutput::new(jack, &format!("{}/M", name.as_ref()), midi_to)?, ],
|
||||
#[cfg(feature = "clip")] play_clip: clip.map(|clip|(Moment::zero(&clock.timebase), Some(clip.clone()))),
|
||||
#[cfg(feature = "clock")] clock,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
fn process_rolling (&mut self, scope: &ProcessScope) -> Control {
|
||||
self.process_clear(scope, false);
|
||||
// Write chunk of clip to output, handle switchover
|
||||
if self.process_playback(scope) {
|
||||
self.process_switchover(scope);
|
||||
}
|
||||
// Monitor input to output
|
||||
self.process_monitoring(scope);
|
||||
// Record and/or monitor input
|
||||
self.process_recording(scope);
|
||||
// Emit contents of MIDI buffers to JACK MIDI output ports.
|
||||
self.midi_outs_emit(scope);
|
||||
Control::Continue
|
||||
}
|
||||
fn process_stopped (&mut self, scope: &ProcessScope) -> Control {
|
||||
if self.monitoring() && self.midi_ins().len() > 0 && self.midi_outs().len() > 0 {
|
||||
self.process_monitoring(scope)
|
||||
}
|
||||
Control::Continue
|
||||
}
|
||||
fn process_monitoring (&mut self, scope: &ProcessScope) {
|
||||
let notes_in = self.notes_in().clone(); // For highlighting keys and note repeat
|
||||
let monitoring = self.monitoring();
|
||||
for input in self.midi_ins.iter() {
|
||||
for (sample, event, bytes) in input.parsed(scope) {
|
||||
if let LiveEvent::Midi { message, .. } = event {
|
||||
if monitoring {
|
||||
self.midi_buf[sample].push(bytes.to_vec());
|
||||
}
|
||||
// FIXME: don't lock on every event!
|
||||
update_keys(&mut notes_in.write().unwrap(), &message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Clear the section of the output buffer that we will be using,
|
||||
/// emitting "all notes off" at start of buffer if requested.
|
||||
fn process_clear (&mut self, scope: &ProcessScope, reset: bool) {
|
||||
let n_frames = (scope.n_frames() as usize).min(self.midi_buf_mut().len());
|
||||
for frame in &mut self.midi_buf_mut()[0..n_frames] {
|
||||
frame.clear();
|
||||
}
|
||||
if reset {
|
||||
all_notes_off(self.midi_buf_mut());
|
||||
}
|
||||
for port in self.midi_outs_mut().iter_mut() {
|
||||
// Clear output buffer(s)
|
||||
port.buffer_clear(scope, false);
|
||||
}
|
||||
}
|
||||
fn process_recording (&mut self, scope: &ProcessScope) {
|
||||
if self.monitoring() {
|
||||
self.monitor(scope);
|
||||
}
|
||||
if let Some((started, ref clip)) = self.play_clip.clone() {
|
||||
self.record_clip(scope, started, clip);
|
||||
}
|
||||
if let Some((_start_at, _clip)) = &self.next_clip() {
|
||||
self.record_next();
|
||||
}
|
||||
}
|
||||
fn process_playback (&mut self, scope: &ProcessScope) -> bool {
|
||||
// If a clip is playing, write a chunk of MIDI events from it to the output buffer.
|
||||
// If no clip is playing, prepare for switchover immediately.
|
||||
if let Some((started, clip)) = &self.play_clip {
|
||||
// Length of clip, to repeat or stop on end.
|
||||
let length = clip.as_ref().map_or(0, |p|p.read().unwrap().length);
|
||||
// Index of first sample to populate.
|
||||
let offset = self.clock().get_sample_offset(scope, &started);
|
||||
// Write MIDI events from clip at sample offsets corresponding to pulses.
|
||||
for (sample, pulse) in self.clock().get_pulses(scope, offset) {
|
||||
// If a next clip is enqueued, and we're past the end of the current one,
|
||||
// break the loop here (FIXME count pulse correctly)
|
||||
let past_end = if clip.is_some() { pulse >= length } else { true };
|
||||
// Is it time for switchover?
|
||||
if self.next_clip().is_some() && past_end {
|
||||
return true
|
||||
}
|
||||
// If there's a currently playing clip, output notes from it to buffer:
|
||||
if let Some(clip) = clip {
|
||||
// Source clip from which the MIDI events will be taken.
|
||||
let clip = clip.read().unwrap();
|
||||
// Clip with zero length is not processed
|
||||
if clip.length > 0 {
|
||||
// Current pulse index in source clip
|
||||
let pulse = pulse % clip.length;
|
||||
// Output each MIDI event from clip at appropriate frames of output buffer:
|
||||
for message in clip.notes[pulse].iter() {
|
||||
for port in self.midi_outs.iter_mut() {
|
||||
port.buffer_write(sample, LiveEvent::Midi {
|
||||
channel: 0.into(), /* TODO */
|
||||
message: *message
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
/// Handle switchover from current to next playing clip.
|
||||
fn process_switchover (&mut self, scope: &ProcessScope) {
|
||||
let _midi_buf = self.midi_buf_mut();
|
||||
let sample0 = scope.last_frame_time() as usize;
|
||||
//let samples = scope.n_frames() as usize;
|
||||
if let Some((start_at, clip)) = &self.next_clip() {
|
||||
let start = start_at.sample.get() as usize;
|
||||
let sample = self.clock().started.read().unwrap()
|
||||
.as_ref().unwrap().sample.get() as usize;
|
||||
// If it's time to switch to the next clip:
|
||||
if start <= sample0.saturating_sub(sample) {
|
||||
// Samples elapsed since clip was supposed to start
|
||||
let _skipped = sample0 - start;
|
||||
// Switch over to enqueued clip
|
||||
let started = Moment::from_sample(self.clock().timebase(), start as f64);
|
||||
// Launch enqueued clip
|
||||
*self.play_clip_mut() = Some((started, clip.clone()));
|
||||
// Unset enqueuement (TODO: where to implement looping?)
|
||||
*self.next_clip_mut() = None;
|
||||
// Fill in remaining ticks of chunk from next clip.
|
||||
self.process_playback(scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl HasMidiBuffers for Sequencer {
|
||||
fn note_buf_mut (&mut self) -> &mut Vec<u8> { &mut self.note_buf }
|
||||
fn midi_buf_mut (&mut self) -> &mut Vec<Vec<Vec<u8>>> { &mut self.midi_buf }
|
||||
}
|
||||
impl std::fmt::Debug for Sequencer {
|
||||
fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
f.debug_struct("Sequencer")
|
||||
.field("clock", &self.clock)
|
||||
.field("play_clip", &self.play_clip)
|
||||
.field("next_clip", &self.next_clip)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl MidiMonitor for Sequencer {
|
||||
fn monitoring (&self) -> bool { self.monitoring }
|
||||
fn monitoring_mut (&mut self) -> &mut bool { &mut self.monitoring }
|
||||
fn notes_in (&self) -> &Arc<RwLock<[bool; 128]>> { &self.notes_in }
|
||||
}
|
||||
impl MidiRecord for Sequencer {
|
||||
fn recording (&self) -> bool { self.recording }
|
||||
fn recording_mut (&mut self) -> &mut bool { &mut self.recording }
|
||||
fn overdub (&self) -> bool { self.overdub }
|
||||
fn overdub_mut (&mut self) -> &mut bool { &mut self.overdub }
|
||||
}
|
||||
#[cfg(feature="clip")] impl HasPlayClip for Sequencer {
|
||||
fn reset (&self) -> bool { self.reset }
|
||||
fn reset_mut (&mut self) -> &mut bool { &mut self.reset }
|
||||
fn play_clip (&self) -> &Option<(Moment, Option<Arc<RwLock<MidiClip>>>)> {
|
||||
&self.play_clip
|
||||
}
|
||||
fn play_clip_mut (&mut self) -> &mut Option<(Moment, Option<Arc<RwLock<MidiClip>>>)> {
|
||||
&mut self.play_clip
|
||||
}
|
||||
fn next_clip (&self) -> &Option<(Moment, Option<Arc<RwLock<MidiClip>>>)> {
|
||||
&self.next_clip
|
||||
}
|
||||
fn next_clip_mut (&mut self) -> &mut Option<(Moment, Option<Arc<RwLock<MidiClip>>>)> {
|
||||
&mut self.next_clip
|
||||
}
|
||||
}
|
||||
/// JACK process callback for a sequencer's clip sequencer/recorder.
|
||||
impl Audio for Sequencer {
|
||||
fn process (&mut self, _: &Client, scope: &ProcessScope) -> Control {
|
||||
if self.clock().is_rolling() {
|
||||
self.process_rolling(scope)
|
||||
} else {
|
||||
self.process_stopped(scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Draw<Tui> for MidiEditor {
|
||||
fn draw(self, to: &mut Tui) -> Usually<XYWH<u16>> {
|
||||
self.tui().draw(to)
|
||||
}
|
||||
}
|
||||
impl Draw<Tui> for PianoHorizontal {
|
||||
fn draw(self, to: &mut Tui) -> Usually<XYWH<u16>> {
|
||||
self.tui().draw(to)
|
||||
}
|
||||
}
|
||||
impl std::fmt::Debug for MidiEditor {
|
||||
fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
f.debug_struct("MidiEditor").field("mode", &self.mode).finish()
|
||||
}
|
||||
}
|
||||
impl_from!(MidiEditor: |clip: &Arc<RwLock<MidiClip>>| {
|
||||
let model = Self::from(Some(clip.clone()));
|
||||
model.redraw();
|
||||
model
|
||||
});
|
||||
impl_from!(MidiEditor: |clip: Option<Arc<RwLock<MidiClip>>>| {
|
||||
let mut model = Self::default();
|
||||
*model.clip_mut() = clip;
|
||||
model.redraw();
|
||||
model
|
||||
});
|
||||
impl_default!(MidiEditor: Self {
|
||||
size: Measure::new(0, 0), mode: PianoHorizontal::new(None)
|
||||
});
|
||||
impl_default!(OctaveVertical: Self {
|
||||
on: [false; 12], colors: [Rgb(255,255,255), Rgb(0,0,0), Rgb(255,0,0)]
|
||||
});
|
||||
impl MidiEditor {
|
||||
/// Put note at current position
|
||||
pub fn put_note (&mut self, advance: bool) {
|
||||
let mut redraw = false;
|
||||
if let Some(clip) = self.clip() {
|
||||
let mut clip = clip.write().unwrap();
|
||||
let note_start = self.get_time_pos();
|
||||
let note_pos = self.get_note_pos();
|
||||
let note_len = self.get_note_len();
|
||||
let note_end = note_start + (note_len.saturating_sub(1));
|
||||
let key: u7 = u7::from(note_pos as u8);
|
||||
let vel: u7 = 100.into();
|
||||
let length = clip.length;
|
||||
let note_end = note_end % length;
|
||||
let note_on = MidiMessage::NoteOn { key, vel };
|
||||
if !clip.notes[note_start].iter().any(|msg|*msg == note_on) {
|
||||
clip.notes[note_start].push(note_on);
|
||||
}
|
||||
let note_off = MidiMessage::NoteOff { key, vel };
|
||||
if !clip.notes[note_end].iter().any(|msg|*msg == note_off) {
|
||||
clip.notes[note_end].push(note_off);
|
||||
}
|
||||
if advance {
|
||||
self.set_time_pos((note_end + 1) % clip.length);
|
||||
}
|
||||
redraw = true;
|
||||
}
|
||||
if redraw {
|
||||
self.mode.redraw();
|
||||
}
|
||||
}
|
||||
fn _todo_opt_clip_stub (&self) -> Option<Arc<RwLock<MidiClip>>> { todo!() }
|
||||
fn clip_length (&self) -> usize { self.clip().as_ref().map(|p|p.read().unwrap().length).unwrap_or(1) }
|
||||
fn note_length (&self) -> usize { self.get_note_len() }
|
||||
fn note_pos (&self) -> usize { self.get_note_pos() }
|
||||
fn note_pos_next (&self) -> usize { self.get_note_pos() + 1 }
|
||||
fn note_pos_next_octave (&self) -> usize { self.get_note_pos() + 12 }
|
||||
fn note_pos_prev (&self) -> usize { self.get_note_pos().saturating_sub(1) }
|
||||
fn note_pos_prev_octave (&self) -> usize { self.get_note_pos().saturating_sub(12) }
|
||||
fn note_len (&self) -> usize { self.get_note_len() }
|
||||
fn note_len_next (&self) -> usize { self.get_note_len() + 1 }
|
||||
fn note_len_prev (&self) -> usize { self.get_note_len().saturating_sub(1) }
|
||||
fn note_range (&self) -> usize { self.get_note_axis() }
|
||||
fn note_range_next (&self) -> usize { self.get_note_axis() + 1 }
|
||||
fn note_range_prev (&self) -> usize { self.get_note_axis().saturating_sub(1) }
|
||||
fn time_zoom (&self) -> usize { self.get_time_zoom() }
|
||||
fn time_zoom_next (&self) -> usize { self.get_time_zoom() + 1 }
|
||||
fn time_zoom_next_fine (&self) -> usize { self.get_time_zoom() + 1 }
|
||||
fn time_zoom_prev (&self) -> usize { self.get_time_zoom().saturating_sub(1).max(1) }
|
||||
fn time_zoom_prev_fine (&self) -> usize { self.get_time_zoom().saturating_sub(1).max(1) }
|
||||
fn time_lock (&self) -> bool { self.get_time_lock() }
|
||||
fn time_lock_toggled (&self) -> bool { !self.get_time_lock() }
|
||||
fn time_pos (&self) -> usize { self.get_time_pos() }
|
||||
fn time_pos_next (&self) -> usize { (self.get_time_pos() + self.get_note_len()) % self.clip_length() }
|
||||
fn time_pos_next_fine (&self) -> usize { (self.get_time_pos() + 1) % self.clip_length() }
|
||||
fn time_pos_prev (&self) -> usize {
|
||||
let step = self.get_note_len();
|
||||
self.get_time_pos().overflowing_sub(step)
|
||||
.0.min(self.clip_length().saturating_sub(step))
|
||||
}
|
||||
fn time_pos_prev_fine (&self) -> usize {
|
||||
self.get_time_pos().overflowing_sub(1)
|
||||
.0.min(self.clip_length().saturating_sub(1))
|
||||
}
|
||||
pub fn clip_status (&self) -> impl Draw<Tui> + '_ {
|
||||
let (_color, name, length, looped) = if let Some(clip) = self.clip().as_ref().map(|p|p.read().unwrap()) {
|
||||
(clip.color, clip.name.clone(), clip.length, clip.looped)
|
||||
} else { (ItemTheme::G[64], String::new().into(), 0, false) };
|
||||
w_exact(20, south!(
|
||||
w_full(origin_w(east(
|
||||
button_2("f2", "name ", false),
|
||||
w_full(origin_e(Tui::fg(Rgb(255, 255, 255), format!("{name} "))))))),
|
||||
w_full(origin_w(east(
|
||||
button_2("l", "ength ", false),
|
||||
w_full(origin_e(Tui::fg(Rgb(255, 255, 255), format!("{length} "))))))),
|
||||
w_full(origin_w(east(
|
||||
button_2("r", "epeat ", false),
|
||||
w_full(origin_e(Tui::fg(Rgb(255, 255, 255), format!("{looped} "))))))),
|
||||
))
|
||||
}
|
||||
pub fn edit_status (&self) -> impl Draw<Tui> + '_ {
|
||||
let (_color, length) = if let Some(clip) = self.clip().as_ref().map(|p|p.read().unwrap()) {
|
||||
(clip.color, clip.length)
|
||||
} else { (ItemTheme::G[64], 0) };
|
||||
let time_pos = self.get_time_pos();
|
||||
let time_zoom = self.get_time_zoom();
|
||||
let time_lock = if self.get_time_lock() { "[lock]" } else { " " };
|
||||
let note_pos = self.get_note_pos();
|
||||
let note_name = format!("{:4}", note_pitch_to_name(note_pos));
|
||||
let note_pos = format!("{:>3}", note_pos);
|
||||
let note_len = format!("{:>4}", self.get_note_len());
|
||||
w_exact(20, south!(
|
||||
w_full(origin_w(east(
|
||||
button_2("t", "ime ", false),
|
||||
w_full(origin_e(Tui::fg(Rgb(255, 255, 255),
|
||||
format!("{length} /{time_zoom} +{time_pos} "))))))),
|
||||
w_full(origin_w(east(
|
||||
button_2("z", "lock ", false),
|
||||
w_full(origin_e(Tui::fg(Rgb(255, 255, 255),
|
||||
format!("{time_lock}"))))))),
|
||||
w_full(origin_w(east(
|
||||
button_2("x", "note ", false),
|
||||
w_full(origin_e(Tui::fg(Rgb(255, 255, 255),
|
||||
format!("{note_name} {note_pos} {note_len}"))))))),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeRange for MidiEditor {
|
||||
fn time_len (&self) -> &AtomicUsize { self.mode.time_len() }
|
||||
fn time_zoom (&self) -> &AtomicUsize { self.mode.time_zoom() }
|
||||
fn time_lock (&self) -> &AtomicBool { self.mode.time_lock() }
|
||||
fn time_start (&self) -> &AtomicUsize { self.mode.time_start() }
|
||||
fn time_axis (&self) -> &AtomicUsize { self.mode.time_axis() }
|
||||
}
|
||||
|
||||
impl NoteRange for MidiEditor {
|
||||
fn note_lo (&self) -> &AtomicUsize { self.mode.note_lo() }
|
||||
fn note_axis (&self) -> &AtomicUsize { self.mode.note_axis() }
|
||||
}
|
||||
|
||||
impl NotePoint for MidiEditor {
|
||||
fn note_len (&self) -> &AtomicUsize { self.mode.note_len() }
|
||||
fn note_pos (&self) -> &AtomicUsize { self.mode.note_pos() }
|
||||
}
|
||||
|
||||
impl TimePoint for MidiEditor {
|
||||
fn time_pos (&self) -> &AtomicUsize { self.mode.time_pos() }
|
||||
}
|
||||
|
||||
impl MidiViewer for MidiEditor {
|
||||
fn buffer_size (&self, clip: &MidiClip) -> (usize, usize) { self.mode.buffer_size(clip) }
|
||||
fn redraw (&self) { self.mode.redraw() }
|
||||
fn clip (&self) -> &Option<Arc<RwLock<MidiClip>>> { self.mode.clip() }
|
||||
fn clip_mut (&mut self) -> &mut Option<Arc<RwLock<MidiClip>>> { self.mode.clip_mut() }
|
||||
fn set_clip (&mut self, p: Option<&Arc<RwLock<MidiClip>>>) { self.mode.set_clip(p) }
|
||||
}
|
||||
|
||||
impl MidiEditor {
|
||||
fn tui (&self) -> impl Draw<Tui> { self.autoscroll(); /*self.autozoom();*/ self.size.of(&self.mode) }
|
||||
}
|
||||
|
||||
|
||||
impl PianoHorizontal {
|
||||
pub fn new (clip: Option<&Arc<RwLock<MidiClip>>>) -> Self {
|
||||
let size = Measure::new(0, 0);
|
||||
let mut range = MidiSelection::from((12, true));
|
||||
range.time_axis = size.x.clone();
|
||||
range.note_axis = size.y.clone();
|
||||
let piano = Self {
|
||||
keys_width: 5,
|
||||
size,
|
||||
range,
|
||||
buffer: RwLock::new(Default::default()).into(),
|
||||
point: MidiCursor::default(),
|
||||
clip: clip.cloned(),
|
||||
color: clip.as_ref().map(|p|p.read().unwrap().color).unwrap_or(ItemTheme::G[64]),
|
||||
};
|
||||
piano.redraw();
|
||||
piano
|
||||
}
|
||||
}
|
||||
|
||||
impl PianoHorizontal {
|
||||
fn tui (&self) -> impl Draw<Tui> {
|
||||
south(
|
||||
east(w_exact(5, format!("{}x{}", self.size.w(), self.size.h())), self.timeline()),
|
||||
east(self.keys(), self.size.of(below(wh_full(self.notes()), wh_full(self.cursor())))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PianoHorizontal {
|
||||
/// Draw the piano roll background.
|
||||
///
|
||||
/// This mode uses full blocks on note on and half blocks on legato: █▄ █▄ █▄
|
||||
fn draw_bg (buf: &mut BigBuffer, clip: &MidiClip, zoom: usize, note_len: usize, note_point: usize, time_point: usize) {
|
||||
for (y, note) in (0..=127).rev().enumerate() {
|
||||
for (x, time) in (0..buf.width).map(|x|(x, x*zoom)) {
|
||||
let cell = buf.get_mut(x, y).unwrap();
|
||||
if note == (127-note_point) || time == time_point {
|
||||
cell.set_bg(Rgb(0,0,0));
|
||||
} else {
|
||||
cell.set_bg(clip.color.darkest.rgb);
|
||||
}
|
||||
if time % 384 == 0 {
|
||||
cell.set_fg(clip.color.darker.rgb);
|
||||
cell.set_char('│');
|
||||
} else if time % 96 == 0 {
|
||||
cell.set_fg(clip.color.dark.rgb);
|
||||
cell.set_char('╎');
|
||||
} else if time % note_len == 0 {
|
||||
cell.set_fg(clip.color.darker.rgb);
|
||||
cell.set_char('┊');
|
||||
} else if (127 - note) % 12 == 0 {
|
||||
cell.set_fg(clip.color.darker.rgb);
|
||||
cell.set_char('=');
|
||||
} else if (127 - note) % 6 == 0 {
|
||||
cell.set_fg(clip.color.darker.rgb);
|
||||
cell.set_char('—');
|
||||
} else {
|
||||
cell.set_fg(clip.color.darker.rgb);
|
||||
cell.set_char('·');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Draw the piano roll foreground.
|
||||
///
|
||||
/// This mode uses full blocks on note on and half blocks on legato: █▄ █▄ █▄
|
||||
fn draw_fg (buf: &mut BigBuffer, clip: &MidiClip, zoom: usize) {
|
||||
let style = Style::default().fg(clip.color.base.rgb);//.bg(Rgb(0, 0, 0));
|
||||
let mut notes_on = [false;128];
|
||||
for (x, time_start) in (0..clip.length).step_by(zoom).enumerate() {
|
||||
for (_y, note) in (0..=127).rev().enumerate() {
|
||||
if let Some(cell) = buf.get_mut(x, note) {
|
||||
if notes_on[note] {
|
||||
cell.set_char('▂');
|
||||
cell.set_style(style);
|
||||
}
|
||||
}
|
||||
}
|
||||
let time_end = time_start + zoom;
|
||||
for time in time_start..time_end.min(clip.length) {
|
||||
for event in clip.notes[time].iter() {
|
||||
match event {
|
||||
MidiMessage::NoteOn { key, .. } => {
|
||||
let note = key.as_int() as usize;
|
||||
if let Some(cell) = buf.get_mut(x, note) {
|
||||
cell.set_char('█');
|
||||
cell.set_style(style);
|
||||
}
|
||||
notes_on[note] = true
|
||||
},
|
||||
MidiMessage::NoteOff { key, .. } => {
|
||||
notes_on[key.as_int() as usize] = false
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
fn notes (&self) -> impl Draw<Tui> {
|
||||
let time_start = self.get_time_start();
|
||||
let note_lo = self.get_note_lo();
|
||||
let note_hi = self.get_note_hi();
|
||||
let buffer = self.buffer.clone();
|
||||
Thunk::new(move|to: &mut Tui|{
|
||||
let source = buffer.read().unwrap();
|
||||
let XYWH(x0, y0, w, _h) = to.area();
|
||||
//if h as usize != note_axis {
|
||||
//panic!("area height mismatch: {h} <> {note_axis}");
|
||||
//}
|
||||
for (area_x, screen_x) in (x0..x0+w).enumerate() {
|
||||
for (area_y, screen_y, _note) in note_y_iter(note_lo, note_hi, y0) {
|
||||
let source_x = time_start + area_x;
|
||||
let source_y = note_hi - area_y;
|
||||
// TODO: enable loop rollover:
|
||||
//let source_x = (time_start + area_x) % source.width.max(1);
|
||||
//let source_y = (note_hi - area_y) % source.height.max(1);
|
||||
let is_in_x = source_x < source.width;
|
||||
let is_in_y = source_y < source.height;
|
||||
if is_in_x && is_in_y {
|
||||
if let Some(source_cell) = source.get(source_x, source_y) {
|
||||
if let Some(cell) = to.buffer.cell_mut(ratatui::prelude::Position::from((screen_x, screen_y))) {
|
||||
*cell = source_cell.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
fn cursor (&self) -> impl Draw<Tui> {
|
||||
let note_hi = self.get_note_hi();
|
||||
let note_lo = self.get_note_lo();
|
||||
let note_pos = self.get_note_pos();
|
||||
let note_len = self.get_note_len();
|
||||
let time_pos = self.get_time_pos();
|
||||
let time_start = self.get_time_start();
|
||||
let time_zoom = self.get_time_zoom();
|
||||
let style = Some(Style::default().fg(self.color.lightest.rgb));
|
||||
Thunk::new(move|to: &mut Tui|{
|
||||
let XYWH(x0, y0, w, _) = to.area();
|
||||
for (_area_y, screen_y, note) in note_y_iter(note_lo, note_hi, y0) {
|
||||
if note == note_pos {
|
||||
for x in 0..w {
|
||||
let screen_x = x0 + x;
|
||||
let time_1 = time_start + x as usize * time_zoom;
|
||||
let time_2 = time_1 + time_zoom;
|
||||
if time_1 <= time_pos && time_pos < time_2 {
|
||||
to.blit(&"█", screen_x, screen_y, style);
|
||||
let tail = note_len as u16 / time_zoom as u16;
|
||||
for x_tail in (screen_x + 1)..(screen_x + tail) {
|
||||
to.blit(&"▂", x_tail, screen_y, style);
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
fn keys (&self) -> impl Draw<Tui> {
|
||||
let state = self;
|
||||
let color = state.color;
|
||||
let note_lo = state.get_note_lo();
|
||||
let note_hi = state.get_note_hi();
|
||||
let note_pos = state.get_note_pos();
|
||||
let key_style = Some(Style::default().fg(Rgb(192, 192, 192)).bg(Rgb(0, 0, 0)));
|
||||
let off_style = Some(Style::default().fg(Tui::g(255)));
|
||||
let on_style = Some(Style::default().fg(Rgb(255,0,0)).bg(color.base.rgb).bold());
|
||||
h_full(w_exact(self.keys_width, Thunk::new(move|to: &mut Tui|{
|
||||
let XYWH(x, y0, _w, _h) = to.area();
|
||||
for (_area_y, screen_y, note) in note_y_iter(note_lo, note_hi, y0) {
|
||||
to.blit(&to_key(note), x, screen_y, key_style);
|
||||
if note > 127 {
|
||||
continue
|
||||
}
|
||||
if note == note_pos {
|
||||
to.blit(&format!("{:<5}", note_pitch_to_name(note)), x, screen_y, on_style)
|
||||
} else {
|
||||
to.blit(¬e_pitch_to_name(note), x, screen_y, off_style)
|
||||
};
|
||||
}
|
||||
})))
|
||||
}
|
||||
fn timeline (&self) -> impl Draw<Tui> + '_ {
|
||||
w_full(h_exact(1, Thunk::new(move|to: &mut Tui|{
|
||||
let XYWH(x, y, w, _h) = to.area();
|
||||
let style = Some(Style::default().dim());
|
||||
let length = self.clip.as_ref().map(|p|p.read().unwrap().length).unwrap_or(1);
|
||||
for (area_x, screen_x) in (0..w).map(|d|(d, d+x)) {
|
||||
let t = area_x as usize * self.time_zoom().get();
|
||||
if t < length {
|
||||
to.blit(&"|", screen_x, y, style);
|
||||
}
|
||||
}
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeRange for PianoHorizontal {
|
||||
fn time_len (&self) -> &AtomicUsize { self.range.time_len() }
|
||||
fn time_zoom (&self) -> &AtomicUsize { self.range.time_zoom() }
|
||||
fn time_lock (&self) -> &AtomicBool { self.range.time_lock() }
|
||||
fn time_start (&self) -> &AtomicUsize { self.range.time_start() }
|
||||
fn time_axis (&self) -> &AtomicUsize { self.range.time_axis() }
|
||||
}
|
||||
|
||||
impl NoteRange for PianoHorizontal {
|
||||
fn note_lo (&self) -> &AtomicUsize { self.range.note_lo() }
|
||||
fn note_axis (&self) -> &AtomicUsize { self.range.note_axis() }
|
||||
}
|
||||
|
||||
impl NotePoint for PianoHorizontal {
|
||||
fn note_len (&self) -> &AtomicUsize { self.point.note_len() }
|
||||
fn note_pos (&self) -> &AtomicUsize { self.point.note_pos() }
|
||||
}
|
||||
|
||||
impl TimePoint for PianoHorizontal {
|
||||
fn time_pos (&self) -> &AtomicUsize { self.point.time_pos() }
|
||||
}
|
||||
|
||||
impl MidiViewer for PianoHorizontal {
|
||||
fn clip (&self) -> &Option<Arc<RwLock<MidiClip>>> { &self.clip }
|
||||
fn clip_mut (&mut self) -> &mut Option<Arc<RwLock<MidiClip>>> { &mut self.clip }
|
||||
/// Determine the required space to render the clip.
|
||||
fn buffer_size (&self, clip: &MidiClip) -> (usize, usize) { (clip.length / self.range.time_zoom().get(), 128) }
|
||||
fn redraw(self) {
|
||||
*self.buffer.write().unwrap() = if let Some(clip) = self.clip.as_ref() {
|
||||
let clip = clip.read().unwrap();
|
||||
let buf_size = self.buffer_size(&clip);
|
||||
let mut buffer = BigBuffer::from(buf_size);
|
||||
let time_zoom = self.get_time_zoom();
|
||||
self.time_len().set(clip.length);
|
||||
PianoHorizontal::draw_bg(&mut buffer, &clip, time_zoom,self.get_note_len(), self.get_note_pos(), self.get_time_pos());
|
||||
PianoHorizontal::draw_fg(&mut buffer, &clip, time_zoom);
|
||||
buffer
|
||||
} else {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
fn set_clip (&mut self, clip: Option<&Arc<RwLock<MidiClip>>>) {
|
||||
*self.clip_mut() = clip.cloned();
|
||||
self.color = clip.map(|p|p.read().unwrap().color).unwrap_or(ItemTheme::G[64]);
|
||||
self.redraw();
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PianoHorizontal {
|
||||
fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
let buffer = self.buffer.read().unwrap();
|
||||
f.debug_struct("PianoHorizontal")
|
||||
.field("time_zoom", &self.range.time_zoom)
|
||||
.field("buffer", &format!("{}x{}", buffer.width, buffer.height))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl OctaveVertical {
|
||||
fn color (&self, pitch: usize) -> Color {
|
||||
let pitch = pitch % 12;
|
||||
self.colors[if self.on[pitch] { 2 } else { match pitch { 0 | 2 | 4 | 5 | 6 | 8 | 10 => 0, _ => 1 } }]
|
||||
}
|
||||
}
|
||||
impl OctaveVertical {
|
||||
fn tui (&self) -> impl Draw<Tui> {
|
||||
east!(
|
||||
Tui::fg_bg(self.color(0), self.color(1), "▙"),
|
||||
Tui::fg_bg(self.color(2), self.color(3), "▙"),
|
||||
Tui::fg_bg(self.color(4), self.color(5), "▌"),
|
||||
Tui::fg_bg(self.color(6), self.color(7), "▟"),
|
||||
Tui::fg_bg(self.color(8), self.color(9), "▟"),
|
||||
Tui::fg_bg(self.color(10), self.color(11), "▟"),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl_from!(MidiSelection: |data:(usize, bool)| Self {
|
||||
time_len: Arc::new(0.into()),
|
||||
note_axis: Arc::new(0.into()),
|
||||
note_lo: Arc::new(0.into()),
|
||||
time_axis: Arc::new(0.into()),
|
||||
time_start: Arc::new(0.into()),
|
||||
time_zoom: Arc::new(data.0.into()),
|
||||
time_lock: Arc::new(data.1.into()),
|
||||
});
|
||||
impl_default!(MidiCursor: Self {
|
||||
time_pos: Arc::new(0.into()),
|
||||
note_pos: Arc::new(36.into()),
|
||||
note_len: Arc::new(24.into()),
|
||||
});
|
||||
|
||||
impl NotePoint for MidiCursor {
|
||||
fn note_len (&self) -> &AtomicUsize {
|
||||
&self.note_len
|
||||
}
|
||||
fn note_pos (&self) -> &AtomicUsize {
|
||||
&self.note_pos
|
||||
}
|
||||
}
|
||||
|
||||
impl TimePoint for MidiCursor {
|
||||
fn time_pos (&self) -> &AtomicUsize {
|
||||
self.time_pos.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeRange for MidiSelection {
|
||||
fn time_len (&self) -> &AtomicUsize { &self.time_len }
|
||||
fn time_zoom (&self) -> &AtomicUsize { &self.time_zoom }
|
||||
fn time_lock (&self) -> &AtomicBool { &self.time_lock }
|
||||
fn time_start (&self) -> &AtomicUsize { &self.time_start }
|
||||
fn time_axis (&self) -> &AtomicUsize { &self.time_axis }
|
||||
}
|
||||
|
||||
impl NoteRange for MidiSelection {
|
||||
fn note_lo (&self) -> &AtomicUsize { &self.note_lo }
|
||||
fn note_axis (&self) -> &AtomicUsize { &self.note_axis }
|
||||
}
|
||||
|
||||
impl Iterator for Ticker {
|
||||
type Item = (usize, usize);
|
||||
fn next (&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
if self.sample > self.end { return None }
|
||||
let spp = self.spp;
|
||||
let sample = self.sample as f64;
|
||||
let start = self.start;
|
||||
let end = self.end;
|
||||
self.sample += 1;
|
||||
//println!("{spp} {sample} {start} {end}");
|
||||
let jitter = sample.rem_euclid(spp); // ramps
|
||||
let next_jitter = (sample + 1.0).rem_euclid(spp);
|
||||
if jitter > next_jitter { // at crossing:
|
||||
let time = (sample as usize) % (end as usize-start as usize);
|
||||
let tick = (sample / spp) as usize;
|
||||
return Some((time, tick))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue