Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -349,3 +349,10 @@ and X11-style licences) and libxcb-xkb (https://xcb.freedesktop.org, X11 licence
as Ubuntu 22.04 builds them, in usr/lib/chromaforge/, with their copyright files beside them as
LICENSE-libxkbcommon.txt and LICENSE-libxcb.txt. winit opens them at run time for the keyboard;
the AppImage carries them for desktops that do not have them installed.

MIDI controllers
----------------
crates/surface/src/midi.rs and the MIDI controller page of Settings ▸ Controls were written with
MIDI2LR (https://github.com/rsjaffe/MIDI2LR, Copyright (c) Rory Jaffe and contributors, GNU General
Public License version 3) read as a reference for behaviour: which kinds of relative encoding
controllers send and how MIDI learn reads them.
4 changes: 2 additions & 2 deletions apps/app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1818,9 +1818,9 @@ fn run() -> eframe::Result {
app.ui.settings.gpu = false;
app.notices.push(notice);
}
let (midi_actions, midi_reload, midi_problem) = midi::start(cc.egui_ctx.clone());
let (midi_actions, midi_reload, midi_problem, midi_raw, midi_ports, midi_out) = midi::start(cc.egui_ctx.clone());
app.notices.extend(midi_problem);
app = app.with_midi(midi_actions, midi_reload);
app = app.with_midi(midi_actions, midi_reload).with_midi_surface(midi_raw, midi_ports, midi_out);
// requests from --control and from the control-surface listener
let (control_tx, control_rx) = std::sync::mpsc::channel();
let mut control_started = false;
Expand Down
245 changes: 208 additions & 37 deletions apps/app/src/midi.rs

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion crates/surface/src/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ pub fn find_control(id: &str) -> Option<&'static ControlDef> {
pub fn group_of(id: &str) -> PageGroup {
match find_control(id) {
Some(c) => c.group,
// a MIDI controller's knobs and faders page with the dials, its notes with the keys
None if id.starts_with("midi.cc.") || id.starts_with("midi.pb.") => PageGroup::Dials,
None if id.starts_with("dial") || id.starts_with("roller") || id.starts_with("enc") || id.starts_with("knob") => PageGroup::Dials,
None => PageGroup::Keys,
}
Expand All @@ -129,7 +131,8 @@ pub fn group_of(id: &str) -> PageGroup {
pub fn is_encoder(id: &str) -> bool {
match find_control(id) {
Some(c) => c.kind == ControlKind::Encoder,
None => group_of(id) == PageGroup::Dials && !id.starts_with("pad"),
// a MIDI control's binding says what it does (a CC may be a button)
None => group_of(id) == PageGroup::Dials && !id.starts_with("pad") && !crate::midi::is_midi(id),
}
}

Expand All @@ -155,6 +158,9 @@ mod tests {
assert_eq!(group_of("pad.2"), PageGroup::Dials);
assert_eq!(group_of("knob.7"), PageGroup::Dials);
assert_eq!(group_of("midi.note.36"), PageGroup::Keys);
assert_eq!(group_of("midi.cc.1.16"), PageGroup::Dials);
assert_eq!(group_of("midi.pb.1"), PageGroup::Dials);
assert!(!is_encoder("midi.cc.1.16"), "a CC's binding says whether it turns or presses");
assert!(is_encoder("dial") && is_encoder("roller") && is_encoder("knob.3"));
assert!(!is_encoder("key.1") && !is_encoder("pad.1"));
}
Expand Down
138 changes: 138 additions & 0 deletions crates/surface/src/feedback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
//! MIDI feedback: the app sends values back to the controller, so motor faders move to the
//! photo's value, knob rings with a place show it, and button lights show whether what the button
//! does is on.
//!
//! [`message`] makes the MIDI message that shows a value or a light on a control; [`Feedback`]
//! sends only what changed since the last time, and leaves a control alone while the hand is on
//! it (a fader being moved must not be pulled back by its own echo). Endless knobs get no message
//! here: how their LED rings take a value differs from one controller to the next, so built-in
//! layouts drive them.
//!
//! Behaviour follows MIDI2LR's feedback (<https://github.com/rsjaffe/MIDI2LR>, GPL-3.0, read as a
//! reference for behaviour): absolute controls are sent their value, relative ones nothing.

use std::collections::BTreeMap;

use crate::midi::{CcMode, parse_id};

/// What a control should show.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Show {
/// A place in the value's range (0…1): a fader, a knob with ends, a ring.
Position(f64),
/// A light: on or off.
Lit(bool),
}

/// The message that shows `show` on `control` (sending as `mode` for a control change), or none
/// when the control can't show it.
pub fn message(control: &str, mode: CcMode, show: Show) -> Option<Vec<u8>> {
let (kind, channel, number) = parse_id(control)?;
let ch = channel.checked_sub(1)?;
if ch > 15 {
return None;
}
let seven = |p: f64| (if p.is_finite() { p.clamp(0.0, 1.0) } else { 0.0 } * 127.0).round() as u8;
match (kind, show) {
("cc", Show::Position(p)) if mode == CcMode::Absolute => Some(vec![0xB0 | ch, number?, seven(p)]),
("cc", Show::Lit(on)) if mode == CcMode::Button => Some(vec![0xB0 | ch, number?, if on { 127 } else { 0 }]),
("note", Show::Lit(on)) => Some(vec![0x90 | ch, number?, if on { 127 } else { 0 }]),
("pb", Show::Position(p)) => {
let v = (if p.is_finite() { p.clamp(0.0, 1.0) } else { 0.0 } * 16383.0).round() as u16;
Some(vec![0xE0 | ch, (v & 0x7F) as u8, (v >> 7) as u8])
}
_ => None,
}
}

/// A control moved within this long (ms) is under the hand: it is sent nothing.
pub const HELD_MS: f64 = 300.0;
/// The most controls remembered.
const MAX_CONTROLS: usize = 512;

/// What was sent to each control, and when each was last moved.
#[derive(Clone, Debug, Default)]
pub struct Feedback {
sent: BTreeMap<String, Vec<u8>>,
touched: BTreeMap<String, f64>,
}

impl Feedback {
/// `control` moved at `now_ms`: it gets nothing while the hand is on it, and its value again
/// once it rests (a motor fader settles on the value it set).
pub fn touched(&mut self, control: &str, now_ms: f64) {
if self.touched.len() >= MAX_CONTROLS && !self.touched.contains_key(control) {
self.touched.clear();
}
self.touched.insert(control.to_string(), now_ms);
self.sent.remove(control);
}

/// The messages to send now for what each control should show (`wanted`: control → message):
/// only those that changed, and none to a control under the hand.
pub fn changes(&mut self, wanted: impl IntoIterator<Item = (String, Vec<u8>)>, now_ms: f64) -> Vec<(String, Vec<u8>)> {
self.touched.retain(|_, at| now_ms - *at < HELD_MS && now_ms >= *at);
let mut out = Vec::new();
for (control, bytes) in wanted {
if self.touched.contains_key(&control) || self.sent.get(&control) == Some(&bytes) {
continue;
}
if self.sent.len() >= MAX_CONTROLS && !self.sent.contains_key(&control) {
self.sent.clear();
}
self.sent.insert(control.clone(), bytes.clone());
out.push((control, bytes));
}
out
}

/// Send everything again next time (a port reconnected, feedback turned on).
pub fn reset(&mut self) {
self.sent.clear();
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn messages_for_faders_knobs_and_lights() {
assert_eq!(message("midi.cc.1.7", CcMode::Absolute, Show::Position(1.0)), Some(vec![0xB0, 7, 127]));
assert_eq!(message("midi.cc.11.9", CcMode::Absolute, Show::Position(0.5)), Some(vec![0xBA, 9, 64]));
assert_eq!(message("midi.pb.1", CcMode::Absolute, Show::Position(0.0)), Some(vec![0xE0, 0, 0]));
assert_eq!(message("midi.pb.2", CcMode::Absolute, Show::Position(1.0)), Some(vec![0xE1, 0x7F, 0x7F]));
assert_eq!(message("midi.note.1.10", CcMode::Absolute, Show::Lit(true)), Some(vec![0x90, 10, 127]));
assert_eq!(message("midi.note.1.10", CcMode::Absolute, Show::Lit(false)), Some(vec![0x90, 10, 0]));
assert_eq!(message("midi.cc.1.20", CcMode::Button, Show::Lit(true)), Some(vec![0xB0, 20, 127]));
// endless knobs: the layouts drive their rings
assert_eq!(message("midi.cc.1.16", CcMode::SignMagnitude, Show::Position(0.5)), None);
assert_eq!(message("midi.cc.1.16", CcMode::Absolute, Show::Lit(true)), None);
assert_eq!(message("dial", CcMode::Absolute, Show::Position(0.5)), None);
assert_eq!(message("midi.cc.1.7", CcMode::Absolute, Show::Position(f64::NAN)), Some(vec![0xB0, 7, 0]));
}

#[test]
fn only_changes_are_sent_and_never_to_a_control_in_hand() {
let mut f = Feedback::default();
let want = |v: u8| vec![("midi.cc.1.7".to_string(), vec![0xB0, 7, v])];
assert_eq!(f.changes(want(10), 0.0).len(), 1);
assert!(f.changes(want(10), 10.0).is_empty(), "unchanged");
f.touched("midi.cc.1.7", 20.0);
assert!(f.changes(want(40), 100.0).is_empty(), "under the hand");
// once it rests it gets the value, even the one it was last sent
assert_eq!(f.changes(want(10), 20.0 + HELD_MS + 1.0), want(10));
f.reset();
assert_eq!(f.changes(want(10), 1000.0).len(), 1, "a reset sends everything again");
}

#[test]
fn many_controls_stay_bounded() {
let mut f = Feedback::default();
for i in 0..3000 {
f.touched(&format!("c{i}"), 0.0);
f.changes([(format!("d{i}"), vec![0x90, 1, 1])], 0.0);
}
assert!(f.sent.len() <= MAX_CONTROLS && f.touched.len() <= MAX_CONTROLS);
}
}
6 changes: 6 additions & 0 deletions crates/surface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
//! - [`settings`]: everything the user tunes, stored as `control-surfaces.json`.
//! - [`loupedeck`]: the Loupedeck+ console's controls, their defaults, and importing a Loupedeck
//! profile's layout.
//! - [`midi`]: MIDI controllers: raw messages to input, how each control sends, which ports to use.
//! - [`feedback`]: values sent back to MIDI controllers (motor faders, rings, lights).
//! - [`pickup`]: faders and knobs with ends take over a value once they reach it.
//! - [`tactilebridge`]: imports a TactileBridge `settings.json` and its Logi profiles (`.lp5`).
//! - [`catalog`]: every action in categories (the editor's picker; plugins list them in their app).
//! - [`protocol`]: pairing tokens and the message shapes of the surface protocol.
Expand All @@ -28,10 +31,13 @@ pub mod catalog;
pub mod context;
pub mod defaults;
pub mod devices;
pub mod feedback;
pub mod icons;
pub mod layout;
pub mod loupedeck;
pub mod midi;
pub mod motion;
pub mod pickup;
pub mod profile;
pub mod protocol;
pub mod runtime;
Expand Down
Loading
Loading