mod generated;
pub use generated::{
CONTROLLER_COUNT, CONTROLLERS, DEFAULT_FIRMWARE, Group, PARAMETER_COUNT, ParamId, TABLE_COUNT,
TableId,
};
use generated::{CONTROLLER_OF_PARAMETER, NO_CONTROLLER};
use core::fmt;
use crate::error::{Error, Result};
use crate::pixels::{Glyph, Pixels};
use crate::sysex::inquiry::Version;
use crate::wire::{Channel, ChannelMessage};
pub const NRPN_NUMBER_MSB: u8 = 99;
pub const NRPN_NUMBER_LSB: u8 = 98;
pub const DATA_ENTRY_MSB: u8 = 6;
pub const DATA_ENTRY_LSB: u8 = 38;
const MOD_DEPTHS: [ParamId; 8] = [
ParamId::Mod1Depth,
ParamId::Mod2Depth,
ParamId::Mod3Depth,
ParamId::Mod4Depth,
ParamId::Mod5Depth,
ParamId::Mod6Depth,
ParamId::Mod7Depth,
ParamId::Mod8Depth,
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Parameter {
pub name: &'static str,
pub group: Group,
pub min: u16,
pub max: u16,
pub kind: Kind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Kind {
Continuous,
Switch,
Enumerated(TableId),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Shape {
Unipolar,
Bipolar {
centre: u16,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Swing {
Centred,
Rising,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ValueEntry {
pub value: u16,
pub name: &'static str,
pub parameters: &'static [ParamId],
pub swing: Option<Swing>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ValueTable {
pub id: TableId,
pub name: &'static str,
pub confirmed: bool,
pub partial: bool,
pub entries: &'static [ValueEntry],
pub cells: &'static [(u16, Pixels)],
}
impl ValueTable {
#[must_use]
pub fn name_of(&self, value: u16) -> Option<&'static str> {
self.entry(value).map(|entry| entry.name)
}
#[must_use]
pub fn parameters_of(&self, value: u16) -> &'static [ParamId] {
self.entry(value).map_or(&[], |entry| entry.parameters)
}
#[must_use]
pub fn swing_of(&self, value: u16) -> Option<Swing> {
self.entry(value)?.swing
}
#[must_use]
pub fn cell_of(&self, value: u16) -> Option<&'static Pixels> {
let index = self
.cells
.binary_search_by_key(&value, |&(drawn, _)| drawn)
.ok()?;
self.cells.get(index).map(|(_, cell)| cell)
}
pub fn values_naming(&self, parameter: ParamId) -> impl Iterator<Item = u16> + 'static {
let entries = self.entries;
let mut last: Option<(usize, u16)> = None;
core::iter::from_fn(move || {
let next = entries
.iter()
.filter(|entry| entry.parameters.contains(¶meter))
.map(|entry| (entry.parameters.len(), entry.value))
.filter(|key| last.is_none_or(|last| *key > last))
.min()?;
last = Some(next);
Some(next.1)
})
}
#[must_use]
pub fn entry(&self, value: u16) -> Option<&'static ValueEntry> {
let index = self
.entries
.binary_search_by_key(&value, |entry| entry.value)
.ok()?;
self.entries.get(index)
}
}
impl fmt::Display for ValueTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ControllerKind {
Parameter,
Standard,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Controller {
pub cc: u8,
pub name: &'static str,
pub kind: ControllerKind,
pub parameter: Option<ParamId>,
pub glyph: Option<Glyph>,
}
impl Controller {
#[must_use]
pub fn for_cc(cc: u8) -> Option<&'static Self> {
CONTROLLERS
.binary_search_by_key(&cc, |controller| controller.cc)
.ok()
.and_then(|index| CONTROLLERS.get(index))
}
#[must_use]
pub fn for_parameter(parameter: ParamId) -> Option<&'static Self> {
let index = CONTROLLER_OF_PARAMETER
.get(usize::from(parameter.offset()))
.copied()
.filter(|index| *index != NO_CONTROLLER)?;
CONTROLLERS.get(usize::from(index))
}
}
impl fmt::Display for Controller {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CC {} ({})", self.cc, self.name)
}
}
impl TryFrom<u8> for ParamId {
type Error = Error;
fn try_from(offset: u8) -> Result<Self> {
Self::from_offset(offset)
}
}
impl From<ParamId> for u8 {
fn from(parameter: ParamId) -> Self {
parameter.offset()
}
}
impl ParamId {
#[must_use]
pub const fn offset(self) -> u8 {
self as u8
}
pub fn from_offset(offset: u8) -> Result<Self> {
Self::ALL
.get(usize::from(offset))
.copied()
.ok_or(Error::ParameterOutOfRange(offset))
}
#[must_use]
pub const fn name(self) -> &'static str {
self.info().name
}
#[must_use]
pub const fn group(self) -> Group {
self.info().group
}
#[must_use]
pub fn short_name(self) -> &'static str {
let name = self.name();
name.strip_prefix(self.group().name())
.map_or(name, |rest| rest.trim_start())
}
#[must_use]
pub const fn kind(self) -> Kind {
self.info().kind
}
#[must_use]
pub const fn min(self) -> u16 {
self.info().min
}
#[must_use]
pub const fn max(self) -> u16 {
self.info().max
}
#[must_use]
pub const fn accepts(self, value: u16) -> bool {
let info = self.info();
value >= info.min && value <= info.max
}
#[must_use]
pub const fn clamp(self, value: u16) -> u16 {
let info = self.info();
if value < info.min {
info.min
} else if value > info.max {
info.max
} else {
value
}
}
#[must_use]
pub fn label(self, value: u16) -> Option<&'static str> {
self.label_for(value, DEFAULT_FIRMWARE)
}
#[must_use]
pub fn label_for(self, value: u16, firmware: Version) -> Option<&'static str> {
match self.kind() {
Kind::Continuous => None,
Kind::Switch => match value {
0 => Some("Off"),
1 => Some("On"),
_ => None,
},
Kind::Enumerated(table) => table.table_for(firmware).name_of(value),
}
}
#[must_use]
pub fn choices(self) -> Option<&'static [ValueEntry]> {
self.choices_for(DEFAULT_FIRMWARE)
}
#[must_use]
pub fn choices_for(self, firmware: Version) -> Option<&'static [ValueEntry]> {
let Kind::Enumerated(table) = self.kind() else {
return None;
};
let entries = table.table_for(firmware).entries;
let first = entries.iter().position(|entry| self.accepts(entry.value))?;
let run = entries.get(first..)?;
let named = run
.iter()
.take_while(|entry| self.accepts(entry.value))
.count();
let span = usize::from(self.max() - self.min()) + 1;
if named != span {
return None;
}
run.get(..named)
}
#[must_use]
pub fn controller(self) -> Option<&'static Controller> {
Controller::for_parameter(self)
}
#[must_use]
pub fn targets(self, value: u16) -> &'static [ParamId] {
self.targets_for(value, DEFAULT_FIRMWARE)
}
#[must_use]
pub fn targets_for(self, value: u16, firmware: Version) -> &'static [ParamId] {
match self.kind() {
Kind::Continuous | Kind::Switch => &[],
Kind::Enumerated(table) => table.table_for(firmware).parameters_of(value),
}
}
#[must_use]
pub fn modulation_reach(self, destination: Self) -> Option<f32> {
const REACH: [(ParamId, f32); 0] = [];
if !MOD_DEPTHS.contains(&self) {
return None;
}
TableId::ModDestination
.table()
.values_naming(destination)
.next()?;
REACH
.iter()
.find(|&&(reached, _)| reached == destination)
.map(|&(_, fraction)| fraction)
}
pub const fn edit(self, value: u16) -> Result<NrpnEdit> {
NrpnEdit::new(self, value)
}
#[must_use]
pub const fn to_cc_value(self, raw: u16) -> u8 {
let info = self.info();
let span = info.max - info.min;
if span == 0 {
return 0;
}
let scaled = ((self.clamp(raw) - info.min) as u32 * 127) / span as u32;
(scaled & 0x7F) as u8
}
#[must_use]
pub const fn from_cc_value(self, value: u8) -> u16 {
let info = self.info();
let span = (info.max - info.min) as u32;
let raw = info.min as u32 + ((value & 0x7F) as u32 * span) / 127;
self.clamp((raw & 0xFFFF) as u16)
}
}
impl fmt::Display for ParamId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl Group {
pub fn parameters(self) -> impl Iterator<Item = ParamId> {
ParamId::ALL
.iter()
.copied()
.filter(move |parameter| parameter.group() == self)
}
}
impl fmt::Display for Group {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl TableId {
#[must_use]
pub const fn table(self) -> &'static ValueTable {
self.table_for(DEFAULT_FIRMWARE)
}
}
impl fmt::Display for TableId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.table().name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NrpnEdit {
pub parameter: ParamId,
pub value: u16,
}
impl NrpnEdit {
pub const LEN: usize = 12;
pub const fn new(parameter: ParamId, value: u16) -> Result<Self> {
if parameter.accepts(value) {
Ok(Self { parameter, value })
} else {
Err(Error::ValueOutOfRange {
parameter: parameter.offset(),
value,
max: parameter.max(),
})
}
}
#[must_use]
pub const fn controls(self) -> [(u8, u8); 4] {
let offset = self.parameter.offset();
[
(NRPN_NUMBER_MSB, (offset >> 7) & 0x7F),
(NRPN_NUMBER_LSB, offset & 0x7F),
(DATA_ENTRY_MSB, ((self.value >> 7) & 0x7F) as u8),
(DATA_ENTRY_LSB, (self.value & 0x7F) as u8),
]
}
pub fn encode_into(self, channel: Channel, out: &mut [u8]) -> Result<usize> {
if out.len() < Self::LEN {
return Err(Error::BufferTooSmall {
needed: Self::LEN,
available: out.len(),
});
}
let mut written = 0;
for (slot, (controller, value)) in out.chunks_exact_mut(3).zip(self.controls()) {
written +=
ChannelMessage::ControlChange { controller, value }.encode_into(channel, slot)?;
}
Ok(written)
}
}
impl fmt::Display for NrpnEdit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.parameter.label(self.value) {
Some(label) => write!(f, "{} = {label}", self.parameter),
None => write!(f, "{} = {}", self.parameter, self.value),
}
}
}
#[cfg(test)]
#[expect(
clippy::expect_used,
reason = "a failed expectation is the test failure"
)]
mod tests {
use super::*;
use crate::ids::ProtocolVersion;
const FIRMWARE_1_0: Version = Version { major: 1, minor: 0 };
#[test]
fn every_offset_names_exactly_one_parameter() {
for (index, parameter) in ParamId::ALL.iter().copied().enumerate() {
let offset = u8::try_from(index).expect("242 offsets fit in a byte");
assert_eq!(parameter.offset(), offset);
assert_eq!(ParamId::from_offset(offset), Ok(parameter));
}
assert_eq!(
ParamId::from_offset(242),
Err(Error::ParameterOutOfRange(242))
);
}
#[test]
fn the_table_is_as_long_as_a_program_dump() {
assert_eq!(
ProtocolVersion::V6.program_data_len(),
PARAMETER_COUNT,
"every byte of a program is a parameter"
);
}
#[test]
fn every_parameter_belongs_to_exactly_one_group() {
let counted: usize = Group::ALL
.iter()
.map(|group| group.parameters().count())
.sum();
assert_eq!(counted, PARAMETER_COUNT);
assert_eq!(ParamId::Lfo1Rate.group(), Group::Lfo1);
assert_eq!(Group::Lfo1.name(), "LFO 1");
}
#[test]
fn an_nrpn_edit_is_four_control_changes() {
let mut bytes = [0; NrpnEdit::LEN];
let len = ParamId::Lfo1Shape
.edit(3)
.expect("3 is an LFO shape")
.encode_into(Channel::ONE, &mut bytes)
.expect("the buffer is long enough");
assert_eq!(len, NrpnEdit::LEN);
assert_eq!(
bytes,
[0xB0, 99, 0, 0xB0, 98, 2, 0xB0, 6, 0, 0xB0, 38, 3],
"select parameter 2, then set it to 3"
);
}
#[test]
fn a_parameter_past_offset_127_sets_the_number_high_byte() {
let parameter = ParamId::from_offset(200).expect("200 is a parameter");
let edit = parameter.edit(0).expect("zero is in range");
assert_eq!(edit.controls()[0], (NRPN_NUMBER_MSB, 1));
assert_eq!(edit.controls()[1], (NRPN_NUMBER_LSB, 72));
}
#[test]
fn a_value_past_127_sets_both_data_entry_bytes() {
let edit = ParamId::Lfo1Rate.edit(200).expect("200 is in range");
assert_eq!(edit.controls()[2], (DATA_ENTRY_MSB, 1));
assert_eq!(edit.controls()[3], (DATA_ENTRY_LSB, 72));
}
#[test]
fn a_value_outside_the_range_is_refused_rather_than_sent() {
assert_eq!(
ParamId::Lfo1Shape.edit(7),
Err(Error::ValueOutOfRange {
parameter: 2,
value: 7,
max: 6,
})
);
assert_eq!(ParamId::Lfo1Shape.clamp(7), 6);
assert!(ParamId::Lfo1Shape.accepts(6));
}
#[test]
fn a_short_buffer_is_refused_rather_than_half_filled() {
let mut bytes = [0; NrpnEdit::LEN - 1];
assert_eq!(
ParamId::Lfo1Rate
.edit(0)
.expect("zero is in range")
.encode_into(Channel::ONE, &mut bytes),
Err(Error::BufferTooSmall {
needed: NrpnEdit::LEN,
available: NrpnEdit::LEN - 1,
})
);
assert_eq!(bytes, [0; NrpnEdit::LEN - 1]);
}
#[test]
fn switches_and_value_tables_name_their_values_and_sweeps_do_not() {
assert_eq!(ParamId::Lfo1KeySync.kind(), Kind::Switch);
assert_eq!(ParamId::Lfo1KeySync.label(0), Some("Off"));
assert_eq!(ParamId::Lfo1KeySync.label(1), Some("On"));
assert_eq!(ParamId::Lfo1KeySync.label(2), None);
assert_eq!(
ParamId::Lfo1Shape.kind(),
Kind::Enumerated(TableId::LfoShape)
);
assert_eq!(ParamId::Lfo1Shape.label(6), Some("Sample & Glide"));
assert_eq!(ParamId::Lfo1Rate.kind(), Kind::Continuous);
assert_eq!(ParamId::Lfo1Rate.label(64), None);
}
#[test]
fn a_complete_value_table_names_every_value_its_parameter_accepts() {
for parameter in ParamId::ALL.iter().copied() {
let Kind::Enumerated(id) = parameter.kind() else {
continue;
};
let table = id.table();
if table.partial || !table.confirmed {
continue;
}
for value in parameter.min()..=parameter.max() {
assert!(
parameter.label(value).is_some(),
"{parameter} has no name for {value} in {table}"
);
}
}
}
#[test]
fn the_firmware_a_program_was_written_on_changes_what_its_values_mean() {
assert_eq!(ParamId::Mod1Source.label(6), Some("Expression"));
assert_eq!(ParamId::Mod1Source.label_for(6, FIRMWARE_1_0), Some("LFO1"));
assert_eq!(TableId::ModSource.table_for(FIRMWARE_1_0).entries.len(), 23);
assert_eq!(TableId::ModSource.table().entries.len(), 25);
}
#[test]
fn a_modulation_destination_names_the_parameters_it_moves() {
assert_eq!(ParamId::Mod3Destination.label(20), Some("VCF Freq"));
assert_eq!(
ParamId::Mod3Destination.targets(20),
&[ParamId::VcfFrequency]
);
let attacks = ParamId::Mod1Destination.targets(25);
assert_eq!(ParamId::Mod1Destination.label(25), Some("All Attack"));
assert_eq!(attacks.len(), 3);
assert!(attacks.contains(&ParamId::VcfEnvelopeAttackTime));
}
#[test]
fn a_destination_that_addresses_nothing_says_so_by_naming_nothing() {
assert!(ParamId::Mod1Destination.targets(0).is_empty(), "Off");
assert_eq!(ParamId::Mod1Destination.label(11), Some("OSC1 Pitch"));
assert!(ParamId::Mod1Destination.targets(11).is_empty());
assert!(ParamId::Lfo1Rate.targets(64).is_empty(), "a sweep");
assert!(ParamId::Lfo1KeySync.targets(1).is_empty(), "a switch");
assert!(ParamId::Lfo1Shape.targets(3).is_empty(), "a named set");
}
#[test]
fn the_firmware_moves_what_a_destination_addresses() {
assert_eq!(
ParamId::Mod1Destination.targets(20),
&[ParamId::VcfFrequency]
);
assert_eq!(
ParamId::Mod1Destination.targets_for(20, FIRMWARE_1_0),
&[ParamId::VcfLfoDepth]
);
assert_eq!(
ParamId::Mod1Destination.targets_for(17, FIRMWARE_1_0),
&[ParamId::VcfFrequency]
);
}
#[test]
fn every_effect_slot_is_reachable_from_the_matrix() {
let table = TableId::ModDestination.table();
let slots = table
.entries
.iter()
.flat_map(|entry| entry.parameters.iter().copied())
.filter(|parameter| parameter.group() == Group::Effects)
.count();
assert_eq!(slots, 4 * 12 + 4);
}
#[test]
fn the_destinations_naming_a_parameter_come_narrowest_first() {
let table = TableId::ModDestination.table();
for parameter in ParamId::ALL.iter().copied() {
let mut previous: Option<(usize, u16)> = None;
let mut yielded = 0;
for value in table.values_naming(parameter) {
let entry = table.entry(value).expect("a listed value");
assert!(
entry.parameters.contains(¶meter),
"{parameter} by {value}"
);
let key = (entry.parameters.len(), value);
assert!(
previous.is_none_or(|last| key > last),
"{parameter} out of order"
);
previous = Some(key);
yielded += 1;
}
let scanned = table
.entries
.iter()
.filter(|entry| entry.parameters.contains(¶meter))
.count();
assert_eq!(yielded, scanned, "{parameter}");
}
let one = table
.values_naming(ParamId::ModEnvelopeReleaseTime)
.next()
.expect("the matrix reaches it");
assert_eq!(table.parameters_of(one), &[ParamId::ModEnvelopeReleaseTime]);
let old = TableId::ModDestination.table_for(FIRMWARE_1_0);
let first = old
.values_naming(ParamId::VcfFrequency)
.next()
.expect("VCF Freq is on 1.0 too");
assert_eq!(old.name_of(first), Some("VCF Freq"));
assert_ne!(
first,
table
.values_naming(ParamId::VcfFrequency)
.next()
.expect("and on 1.1")
);
}
#[test]
fn a_source_says_which_way_it_swings() {
let sources = TableId::ModSource.table();
assert_eq!(sources.swing_of(7), Some(Swing::Centred)); assert_eq!(sources.swing_of(16), Some(Swing::Rising)); assert_eq!(sources.swing_of(1), Some(Swing::Centred)); assert_eq!(sources.swing_of(2), Some(Swing::Rising)); assert_eq!(sources.swing_of(0), None); assert_eq!(sources.swing_of(12), None); assert_eq!(sources.swing_of(200), None);
let old = TableId::ModSource.table_for(FIRMWARE_1_0);
assert_eq!(old.name_of(6), Some("LFO1"));
assert_eq!(old.swing_of(6), Some(Swing::Centred));
for id in TableId::ALL.iter().copied() {
if id == TableId::ModSource {
continue;
}
assert!(
id.table().entries.iter().all(|entry| entry.swing.is_none()),
"{id:?} swings"
);
}
}
#[test]
fn a_matrix_entry_carries_a_cell_where_one_was_drawn() {
for id in [TableId::ModSource, TableId::ModDestination] {
let table = id.table();
assert!(table.cell_of(0).is_none(), "{id:?}: Off is nothing to draw");
for (left, right) in table.cells.iter().zip(table.cells.iter().skip(1)) {
assert!(
left.0 < right.0,
"{id:?}: cells out of order at {}",
right.0
);
}
for (value, cell) in table.cells {
assert!(
table.entry(*value).is_some(),
"{id:?}: a cell for nothing at {value}"
);
assert!(
cell.rows().iter().any(|row| *row != 0),
"{id:?}: {value} is blank"
);
assert!(
cell.rows().iter().any(|row| *row != 0x7f),
"{id:?}: {value} is solid"
);
}
let old = id.table_for(FIRMWARE_1_0);
for entry in table.entries {
let Some(twin) = old.entries.iter().find(|e| e.name == entry.name) else {
continue;
};
assert_eq!(
table.cell_of(entry.value),
old.cell_of(twin.value),
"{}",
entry.name
);
}
}
let sources = TableId::ModSource.table();
for entry in sources.entries.iter().filter(|e| e.name != "Off") {
assert!(
sources.cell_of(entry.value).is_some(),
"the source {} is undrawn",
entry.name
);
}
let destinations = TableId::ModDestination.table();
for entry in destinations.entries.iter().filter(|e| e.name != "Off") {
if entry.parameters.len() == 1 {
continue;
}
assert!(
destinations.cell_of(entry.value).is_some(),
"the destination {} is undrawn",
entry.name
);
}
for id in TableId::ALL.iter().copied() {
if matches!(id, TableId::ModSource | TableId::ModDestination) {
continue;
}
assert!(id.table().cells.is_empty(), "{id:?} carries a cell");
}
}
#[test]
fn no_modulation_reach_is_established() {
for depth in MOD_DEPTHS {
for destination in ParamId::ALL.iter().copied() {
assert_eq!(depth.modulation_reach(destination), None);
}
}
assert_eq!(
ParamId::Mod1Source.modulation_reach(ParamId::VcfFrequency),
None
);
}
#[test]
fn every_parameter_a_table_names_is_a_parameter() {
for id in TableId::ALL {
for entry in id.table().entries {
for parameter in entry.parameters {
assert_eq!(
ParamId::from_offset(parameter.offset()),
Ok(*parameter),
"{entry:?} in {id}"
);
}
}
}
}
#[test]
fn the_groups_are_listed_twice_in_two_different_orders() {
assert_eq!(Group::ORDER.len(), Group::ALL.len());
for group in Group::ALL {
assert!(Group::ORDER.contains(group), "{group} is not laid out");
}
let starts = Group::ORDER.iter().map(|group| {
group
.parameters()
.next()
.expect("a group in the table has a parameter")
.offset()
});
assert!(starts.is_sorted(), "the order is not the instrument's own");
assert_eq!(Group::ORDER.first(), Some(&Group::Lfo1));
assert_eq!(Group::ORDER.last(), Some(&Group::Program));
}
#[test]
fn a_parameter_offers_a_list_only_when_every_value_has_a_name() {
let shapes = ParamId::Lfo1Shape.choices().expect("all seven are named");
assert_eq!(shapes.len(), usize::from(ParamId::Lfo1Shape.max()) + 1);
assert_eq!(shapes.first().map(|entry| entry.name), Some("Sine"));
assert_eq!(
shapes.last().map(|entry| entry.name),
Some("Sample & Glide")
);
assert!(TableId::LfoMonoMode.table().partial);
assert!(ParamId::Lfo1MonoMode.choices().is_none());
assert!(ParamId::Lfo1Rate.choices().is_none(), "a sweep");
assert!(ParamId::Lfo1KeySync.choices().is_none(), "a switch");
}
#[test]
fn every_value_a_list_offers_is_named_and_accepted() {
for firmware in [DEFAULT_FIRMWARE, FIRMWARE_1_0] {
for parameter in ParamId::ALL.iter().copied() {
let Some(choices) = parameter.choices_for(firmware) else {
continue;
};
for entry in choices {
assert!(parameter.accepts(entry.value), "{parameter}");
assert_eq!(
parameter.label_for(entry.value, firmware),
Some(entry.name),
"{parameter}"
);
}
for value in parameter.min()..=parameter.max() {
assert!(
choices.iter().any(|entry| entry.value == value),
"{parameter} offers a list that skips {value}"
);
}
}
}
}
#[test]
fn a_parameter_name_drops_the_group_a_panel_already_prints() {
assert_eq!(ParamId::VcfEnvelopeDepth.short_name(), "Envelope Depth");
assert_eq!(ParamId::Lfo1Rate.short_name(), "Rate");
assert_eq!(ParamId::ProgramNameChar1.short_name(), "Name Char 1");
assert_eq!(ParamId::Mod1Source.short_name(), "Mod 1 Source");
for parameter in ParamId::ALL.iter().copied() {
let short = parameter.short_name();
assert!(!short.is_empty(), "{parameter} shortens to nothing");
assert!(parameter.name().ends_with(short), "{parameter}");
}
}
#[test]
fn a_table_answers_only_for_the_values_it_lists() {
let partial = TableId::LfoMonoMode.table();
assert!(partial.partial, "the SPREAD-n run is not written out");
assert_eq!(partial.name_of(1), Some("Mono"));
assert_eq!(partial.name_of(200), None);
}
#[test]
fn the_controller_table_is_in_controller_number_order() {
assert!(CONTROLLERS.windows(2).all(|pair| match pair {
[a, b] => a.cc < b.cc,
_ => true,
}));
assert_eq!(Controller::for_cc(255), None);
}
#[test]
fn controllers_and_parameters_agree_in_both_directions() {
for controller in &CONTROLLERS {
assert_eq!(Controller::for_cc(controller.cc), Some(controller));
let Some(parameter) = controller.parameter else {
assert_ne!(controller.kind, ControllerKind::Parameter);
continue;
};
assert_eq!(controller.kind, ControllerKind::Parameter);
assert_eq!(parameter.controller(), Some(controller));
}
assert_eq!(Controller::for_cc(3), None, "CC 3 is undefined");
}
#[test]
fn a_control_change_reaches_the_ends_of_the_range_it_scales() {
for parameter in ParamId::ALL.iter().copied() {
assert_eq!(parameter.to_cc_value(parameter.min()), 0, "{parameter}");
assert_eq!(parameter.to_cc_value(parameter.max()), 127, "{parameter}");
assert_eq!(parameter.from_cc_value(0), parameter.min(), "{parameter}");
assert_eq!(parameter.from_cc_value(127), parameter.max(), "{parameter}");
}
}
#[test]
fn scaling_is_lossless_only_where_the_range_fits_in_seven_bits() {
let fine = ParamId::ProgramNameChar1;
assert_eq!(fine.max(), 127);
for raw in 0..=fine.max() {
assert_eq!(fine.from_cc_value(fine.to_cc_value(raw)), raw);
}
let coarse = ParamId::Lfo1Rate;
assert_eq!(coarse.max(), 255);
assert_eq!(coarse.from_cc_value(coarse.to_cc_value(3)), 2);
}
#[test]
#[cfg(feature = "alloc")]
fn an_edit_prints_as_the_synthesizer_would_name_it() {
let edit = ParamId::Lfo1Shape.edit(1).expect("1 is an LFO shape");
assert_eq!(alloc::format!("{edit}"), "LFO 1 Shape = Triangle");
let sweep = ParamId::Lfo1Rate.edit(64).expect("64 is in range");
assert_eq!(alloc::format!("{sweep}"), "LFO 1 Rate = 64");
}
#[test]
fn a_bipolar_centre_is_inside_the_range_and_not_at_an_end() {
let mut bipolar = 0;
for parameter in ParamId::ALL.iter().copied() {
let Shape::Bipolar { centre } = parameter.shape() else {
continue;
};
bipolar += 1;
assert!(parameter.accepts(centre), "{parameter}");
assert!(centre > parameter.min(), "{parameter} centres on its floor");
assert!(centre < parameter.max(), "{parameter} centres on its top");
}
assert_eq!(bipolar, 45);
assert_eq!(
ParamId::Mod1Depth.shape(),
Shape::Bipolar { centre: 128 },
"-128 at 0 and +127 at 255"
);
assert_eq!(ParamId::Lfo1Rate.shape(), Shape::Unipolar);
}
#[test]
fn a_sequencer_step_says_what_it_is() {
let step = ParamId::SeqStepValue1;
assert_eq!(step.shape(), Shape::Bipolar { centre: 128 });
assert_eq!(step.inactive(), Some(0), "zero skips the step");
assert_eq!(step.bounded_by(), Some(ParamId::SequenceLength));
let steps = || {
ParamId::ALL
.iter()
.copied()
.filter(|parameter| parameter.bounded_by().is_some())
};
assert_eq!(steps().count(), 32);
for step in steps() {
assert_eq!(step.group(), Group::ControlSequencer);
assert_eq!(step.inactive(), Some(0));
assert!(step.name().starts_with("Seq Step Value"));
}
assert_eq!(ParamId::SequenceLength.bounded_by(), None);
assert_eq!(ParamId::Lfo1Rate.inactive(), None);
}
#[test]
fn every_sequencer_step_reads_the_same_way() {
for step in ParamId::ALL
.iter()
.copied()
.filter(|p| p.name().starts_with("Seq Step Value"))
{
assert_eq!(step.kind(), Kind::Continuous, "{step}");
assert_eq!(step.max(), 255, "{step}");
}
assert!(
ParamId::SeqStepValue9
.correction()
.is_some_and(|text| text.contains("switch")),
"the slip is recorded"
);
assert_eq!(ParamId::SeqStepValue1.correction(), None);
}
#[test]
fn the_manuals_own_words_are_reachable() {
assert_eq!(
ParamId::VcfFrequency.display(),
Some("50.0 Hz to 20000.0 Hz")
);
assert_eq!(ParamId::Lfo1SlewRate.display(), None);
assert_eq!(ParamId::Lfo1SlewRate.note(), None);
assert!(
ParamId::Lfo1Rate
.note()
.is_some_and(|note| note.contains("Arp Sync"))
);
let counted = |field: fn(ParamId) -> Option<&'static str>| {
ParamId::ALL
.iter()
.copied()
.filter(|parameter| field(*parameter).is_some())
.count()
};
assert_eq!(counted(ParamId::display), 26);
assert_eq!(counted(ParamId::note), 129);
assert_eq!(counted(ParamId::correction), 37);
}
#[test]
fn a_description_is_there_exactly_when_the_feature_is() {
let described = ParamId::ALL
.iter()
.copied()
.filter(|parameter| parameter.description().is_some())
.count();
assert_eq!(
described,
if cfg!(feature = "descriptions") {
PARAMETER_COUNT
} else {
0
}
);
}
#[cfg(feature = "descriptions")]
#[test]
fn a_description_says_what_the_control_does() {
assert!(
ParamId::VcfFrequency
.description()
.is_some_and(|text| text.contains("cutoff")),
);
for parameter in ParamId::ALL.iter().copied() {
let text = parameter.description().expect("every parameter has one");
assert!(text.ends_with('.'), "{parameter}: not a sentence");
assert!(
!text.is_empty() && text.starts_with(char::is_uppercase),
"{parameter}: {text:?}"
);
assert_ne!(
Some(text),
parameter.note(),
"{parameter}: repeats its note"
);
}
}
#[test]
fn an_inferred_reading_is_marked_and_explained() {
assert!(!ParamId::PitchBendUpDepth.confirmed());
assert!(ParamId::PitchBendUpDepth.correction().is_some());
assert!(ParamId::VcfFrequency.confirmed());
for parameter in ParamId::ALL.iter().copied() {
assert!(
parameter.confirmed() || parameter.correction().is_some(),
"{parameter} is unconfirmed and does not say why"
);
}
}
}