feat(M1.3): scope MIDI bindings to stable surfaces

Validate channel and data ranges, reject duplicate physical keys, preserve independent device controls, and allow shared logical targets. Tests: cargo test -p fader-core --test bindings --locked initially failed for missing types; cargo test -p fader-core --all-targets --locked now passes (22 tests). Strict core Clippy and formatting passed.
This commit is contained in:
Dandaedre 2026-10-05 08:16:48 +02:00
parent e0a309b565
commit 6a3198d0e9
5 changed files with 202 additions and 1 deletions

124
core/src/bindings.rs Normal file
View File

@ -0,0 +1,124 @@
//! Device-scoped control bindings without native MIDI handles.
use crate::{FaderId, SurfaceId};
use std::collections::{BTreeMap, btree_map::Entry};
use thiserror::Error;
/// Invalid channel or data range.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum MidiRangeError {
/// Human-facing channels are numbered 1 through 16.
#[error("MIDI channel {0} is outside 1..=16")]
Channel(u16),
/// MIDI data bytes contain seven bits.
#[error("MIDI data {0} is outside 0..=127")]
Data(u16),
}
/// Validated human-facing MIDI channel number.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct MidiChannel(u8);
impl MidiChannel {
/// Validates a channel before conversion to wire indexing.
pub fn new(value: u16) -> Result<Self, MidiRangeError> {
match value {
1..=16 => Ok(Self(value as u8)),
_ => Err(MidiRangeError::Channel(value)),
}
}
/// The human-facing channel number.
pub const fn get(self) -> u8 {
self.0
}
/// Zero-based channel for the MIDI status nibble.
pub const fn wire_index(self) -> u8 {
self.0 - 1
}
}
/// A seven-bit MIDI data value or control number.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct MidiData(u8);
impl MidiData {
/// Rejects data values containing status bits before narrowing.
pub fn new(value: u16) -> Result<Self, MidiRangeError> {
if value <= 127 {
Ok(Self(value as u8))
} else {
Err(MidiRangeError::Data(value))
}
}
/// Returns the validated data byte.
pub const fn get(self) -> u8 {
self.0
}
}
/// Supported initial control namespaces.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum MessageKind {
/// Seven-bit control change.
ControlChange,
/// Note on/off button pair.
Note,
}
/// A physical control, including its stable surface identity.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct BindingKey {
/// Configured surface identity.
pub surface: SurfaceId,
/// Channel, independent of other connected surfaces.
pub channel: MidiChannel,
/// Message namespace.
pub kind: MessageKind,
/// CC or note number.
pub number: MidiData,
}
/// Logical intent for a bound control.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BindingAction {
/// Absolute normalized volume.
Volume,
/// Toggle mute on a press edge.
ToggleMute,
}
/// A control's logical destination and action.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Binding {
/// Configured fader destination.
pub fader: FaderId,
/// Requested logical operation.
pub action: BindingAction,
}
/// Duplicate physical controls would route ambiguously.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("duplicate physical binding: {0:?}")]
pub struct BindingError(pub BindingKey);
/// An unambiguous device-scoped lookup table.
#[derive(Clone, Debug, Default)]
pub struct Bindings(BTreeMap<BindingKey, Binding>);
impl Bindings {
/// Builds the table, rejecting duplicate keys even if destinations agree.
pub fn new(
entries: impl IntoIterator<Item = (BindingKey, Binding)>,
) -> Result<Self, BindingError> {
let mut table = BTreeMap::new();
for (key, binding) in entries {
match table.entry(key) {
Entry::Vacant(entry) => {
entry.insert(binding);
}
Entry::Occupied(entry) => return Err(BindingError(entry.key().clone())),
}
}
Ok(Self(table))
}
/// Unknown controls are left unbound.
pub fn get(&self, key: &BindingKey) -> Option<&Binding> {
self.0.get(key)
}
}

View File

@ -5,6 +5,7 @@
#![forbid(unsafe_code)]
mod bindings;
mod id;
mod matching;
mod revision;
@ -12,6 +13,10 @@ mod routing;
mod state;
mod volume;
pub use bindings::{
Binding, BindingAction, BindingError, BindingKey, Bindings, MessageKind, MidiChannel, MidiData,
MidiRangeError,
};
pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId};
pub use matching::{
ApplicationMatcher, ApplicationRuntime, ApplicationSelector, MetadataField, SelectorError,

45
core/tests/bindings.rs Normal file
View File

@ -0,0 +1,45 @@
use fader_core::{
Binding, BindingAction, BindingKey, Bindings, FaderId, MessageKind, MidiChannel, MidiData,
SurfaceId,
};
#[test]
fn identical_controls_on_different_surfaces_are_independent() {
let key = |surface| BindingKey {
surface: SurfaceId::new(surface).unwrap(),
channel: MidiChannel::new(1).unwrap(),
kind: MessageKind::ControlChange,
number: MidiData::new(7).unwrap(),
};
let left = Binding {
fader: FaderId::new("left").unwrap(),
action: BindingAction::Volume,
};
let right = Binding {
fader: FaderId::new("right").unwrap(),
action: BindingAction::ToggleMute,
};
let bindings =
Bindings::new([(key("desk"), left.clone()), (key("stage"), right.clone())]).unwrap();
assert_eq!(bindings.get(&key("desk")), Some(&left));
assert_eq!(bindings.get(&key("stage")), Some(&right));
assert_eq!(bindings.get(&key("absent")), None);
assert!(Bindings::new([(key("desk"), left), (key("desk"), right)]).is_err());
}
#[test]
fn midi_ranges_validate_before_narrowing_or_index_conversion() {
for channel in 1..=16 {
assert_eq!(
MidiChannel::new(channel).unwrap().wire_index(),
(channel - 1) as u8
);
}
for channel in [0, 17, 256, u16::MAX] {
assert!(MidiChannel::new(channel).is_err());
}
assert_eq!(MidiData::new(127).unwrap().get(), 127);
for data in [128, 256, u16::MAX] {
assert!(MidiData::new(data).is_err());
}
}

View File

@ -46,3 +46,30 @@ fn dangling_targets_are_rejected_before_routing() {
.is_err()
);
}
#[test]
fn several_faders_can_share_one_target() {
let app = ApplicationId::new("music").unwrap();
let first = FaderId::new("first").unwrap();
let second = FaderId::new("second").unwrap();
let handle = StreamHandle::new(BackendEpoch::new(2), 3, 1);
let routing = Routing::new(
BTreeSet::from([app.clone()]),
BTreeMap::new(),
BTreeMap::from([
(first.clone(), Target::Application(app.clone())),
(second.clone(), Target::Application(app.clone())),
]),
)
.unwrap();
let live = BTreeMap::from([(app, BTreeSet::from([handle]))]);
assert_eq!(
routing.resolve(&first, &live),
routing.resolve(&second, &live)
);
assert!(
routing
.resolve(&FaderId::new("unknown").unwrap(), &live)
.is_err()
);
}

View File

@ -29,7 +29,7 @@ Dependencies: M0.
- [x] **M1.1 Typed values:** stable IDs, finite gain, channel vectors, mute/availability/mixed states, revisions and backend epochs. Tests: invalid ranges/NaN/infinity rejected; gain/silence/channel-balance properties hold; IDs cannot be interchanged accidentally.
- [x] **M1.2 Application selectors:** normalized metadata, exact/regex matching, OR selectors, multiple live streams and offline objects. Tests: anchored/unanchored/case-sensitive cases, missing fields, malformed regex, stream creation/removal and backend ID reuse.
- [ ] **M1.3 Fader resolution:** surface binding -> fader -> application/group -> deduplicated live streams. Tests: identical CCs on different surfaces stay separate, multiple faders can share an object, and overlap never writes the same stream twice per operation.
- [x] **M1.3 Fader resolution:** surface binding -> fader -> application/group -> deduplicated live streams. Tests: identical CCs on different surfaces stay separate, multiple faders can share an object, and overlap never writes the same stream twice per operation.
- [ ] **M1.4 Group gain:** absolute and relative modes with channel balance, aggregate max/mixed state, zero fallback and clipping. Tests: heterogeneous members, externally changed members, all-zero recovery, empty group, late joiner adopting live state, and partial failure.
- [ ] **M1.5 Mute:** explicit set/toggle independent of volume. Tests: mixed-group toggle mutes all, fully muted toggle unmutes all, two rapid toggles cancel logically, zero gain does not imply mute, and unmute does not alter gain.