nord-format 0.6.0

Read and write Nord keyboard files from Rust, byte for byte
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! The Stage bodies in the default suite: a synthetic specimen per decoded body, so
//! placing, gating and the round-trip invariant are exercised without the corpus.
//!
//! Three synthetic bodies carry the round-trip invariant: all zeros, all ones, and the
//! body that holds 1 at every bit no field claims and 0 at every bit one does. The last
//! isolates the unclaimed bits, which is where the invariant can break silently.

use nord_format::bits::Packed;
use nord_format::cbin::{Cbin, Header};
use nord_format::components::{KbZone4, ProgramCategory};
use nord_format::fields::{ControlKind, FieldSpec, Unit};
use nord_format::formats::{ns2, ns3, ns4};
use nord_format::layout::{BodyLayout, LayoutField};
use nord_format::{Entity, Live, OrganPreset, PianoPreset, Program, Synth};

/// A body holding 1 at every bit no [`LayoutField`] claims and 0 at every bit one does:
/// the most unclaimed bits a body can carry with no field asked to decode a value it
/// may refuse.
fn unclaimed_ones<const LEN: usize>(fields: &'static [LayoutField]) -> [u8; LEN] {
    fn clear(fields: &'static [LayoutField], base: u32, raw: &mut [u8]) {
        for field in fields {
            match field.nested {
                Some(nested) => clear(nested(), base + field.lo, raw),
                None => {
                    for bit in base + field.lo..=base + field.hi {
                        raw[bit as usize / 8] &= !(1 << (7 - bit % 8));
                    }
                }
            }
        }
    }
    let mut raw = [0xffu8; LEN];
    clear(fields, 0, &mut raw);
    raw
}

macro_rules! stage_body {
    ($name:ident, $body:ty, $len:expr, $format:expr, $versions:expr, $wrap:expr, $unwrap:pat => $inner:expr) => {
        mod $name {
            use super::*;

            fn file(body: $body, version: u32) -> Vec<u8> {
                let file = Cbin {
                    header: Header::new($format, (0, 0), version),
                    body,
                };
                nord_format::to_bytes(&$wrap(file)).expect("a synthetic file encodes")
            }

            #[test]
            fn a_zeroed_body_decodes_and_re_encodes_byte_for_byte() {
                let body = <$body>::try_from([0u8; $len]).expect("a zeroed body decodes");
                let version = *$versions.last().unwrap();
                let bytes = file(body, version);
                let entity = nord_format::from_stream(&mut std::io::Cursor::new(&bytes))
                    .expect("the file reads back");
                match &entity {
                    $unwrap => assert_eq!($inner.header.version, version),
                    other => panic!("decoded to {other:?}"),
                }
                assert_eq!(nord_format::to_bytes(&entity).unwrap(), bytes);
            }

            #[test]
            fn unclaimed_bits_ride_through_a_re_encode() {
                let raw: [u8; $len] = unclaimed_ones(<$body>::layout());
                let body = <$body>::try_from(raw).expect("a body whose every claimed bit is zero");
                assert_eq!(
                    <[u8; $len]>::from(&body),
                    raw,
                    "a bit no field claims did not survive the round trip"
                );
            }

            #[test]
            fn an_all_ones_body_decodes_and_re_encodes_byte_for_byte() {
                let raw = [0xffu8; $len];
                let body = <$body>::try_from(raw).expect("every field decodes its maximum");
                assert_eq!(
                    <[u8; $len]>::from(&body),
                    raw,
                    "a field wrapped its maximum instead of holding it"
                );
            }

            #[test]
            fn an_unknown_version_is_refused() {
                let body = <$body>::try_from([0u8; $len]).unwrap();
                let bytes = file(body, 999_999);
                let err = nord_format::from_stream(&mut std::io::Cursor::new(&bytes))
                    .expect_err("a version the offsets were never checked against");
                assert!(err.to_string().contains("999999"), "{err}");
            }
        }
    };
}

stage_body!(
    stage2_program,
    ns2::Program,
    ns2::program::BODY_LEN,
    ns2::program::FORMAT,
    ns2::program::KNOWN_VERSIONS,
    |f| Entity::Program(Program::Stage2(f)),
    Entity::Program(Program::Stage2(f)) => f
);
stage_body!(
    stage2_live,
    ns2::Program,
    ns2::program::BODY_LEN,
    ns2::live::FORMAT,
    ns2::program::KNOWN_VERSIONS,
    |f| Entity::Live(Live::Stage2(f)),
    Entity::Live(Live::Stage2(f)) => f
);
stage_body!(
    stage3_program,
    ns3::Program,
    ns3::program::BODY_LEN,
    ns3::program::FORMAT,
    ns3::program::KNOWN_VERSIONS,
    |f| Entity::Program(Program::Stage3(f)),
    Entity::Program(Program::Stage3(f)) => f
);
stage_body!(
    stage3_live,
    ns3::Program,
    ns3::program::BODY_LEN,
    ns3::live::FORMAT,
    ns3::program::KNOWN_VERSIONS,
    |f| Entity::Live(Live::Stage3(f)),
    Entity::Live(Live::Stage3(f)) => f
);
stage_body!(
    stage3_synth,
    ns3::SynthPreset,
    ns3::synth::BODY_LEN,
    ns3::synth::FORMAT,
    ns3::synth::KNOWN_VERSIONS,
    |f| Entity::Synth(Synth::Stage3(f)),
    Entity::Synth(Synth::Stage3(f)) => f
);
stage_body!(
    stage4_program,
    ns4::Program,
    ns4::program::BODY_LEN,
    ns4::program::FORMAT,
    ns4::program::KNOWN_VERSIONS,
    |f| Entity::Program(Program::Stage4(f)),
    Entity::Program(Program::Stage4(f)) => f
);
stage_body!(
    stage4_live,
    ns4::Program,
    ns4::program::BODY_LEN,
    ns4::live::FORMAT,
    ns4::program::KNOWN_VERSIONS,
    |f| Entity::Live(Live::Stage4(f)),
    Entity::Live(Live::Stage4(f)) => f
);
stage_body!(
    stage4_synth,
    ns4::synth::SynthPreset,
    ns4::synth::BODY_LEN,
    ns4::synth::FORMAT,
    ns4::synth::KNOWN_VERSIONS,
    |f| Entity::Synth(Synth::Stage4(f)),
    Entity::Synth(Synth::Stage4(f)) => f
);
stage_body!(
    stage4_piano_preset,
    ns4::piano_preset::PianoPreset,
    ns4::piano_preset::BODY_LEN,
    ns4::piano_preset::FORMAT,
    ns4::piano_preset::KNOWN_VERSIONS,
    |f| Entity::PianoPreset(PianoPreset::Stage4(f)),
    Entity::PianoPreset(PianoPreset::Stage4(f)) => f
);
stage_body!(
    stage4_organ_preset,
    ns4::organ_preset::OrganPreset,
    ns4::organ_preset::BODY_LEN,
    ns4::organ_preset::FORMAT,
    ns4::organ_preset::KNOWN_VERSIONS,
    |f| Entity::OrganPreset(OrganPreset::Stage4(f)),
    Entity::OrganPreset(OrganPreset::Stage4(f)) => f
);

#[test]
fn program_split_bits_have_exact_placements() {
    let mut raw = [0u8; ns2::program::BODY_LEN];
    raw[3] = 0x04;
    let stage2 = ns2::Program::try_from(raw).unwrap();
    assert!(stage2.split_enabled());
    assert_eq!(<[u8; ns2::program::BODY_LEN]>::from(&stage2), raw);

    let mut raw = [0u8; ns3::program::BODY_LEN];
    raw[5] = 0x10;
    let stage3 = ns3::Program::try_from(raw).unwrap();
    assert!(stage3.split_enabled);
    assert_eq!(<[u8; ns3::program::BODY_LEN]>::from(&stage3), raw);

    let mut raw = [0u8; ns4::program::BODY_LEN];
    raw[5] = 0x80;
    let stage4 = ns4::Program::try_from(raw).unwrap();
    assert!(stage4.split_enabled);
    assert_eq!(<[u8; ns4::program::BODY_LEN]>::from(&stage4), raw);
}

/// In each Stage 4 preset, layer A's keyboard zone sits one layer stride above B's.
///
/// Inferred from specimens; not confirmed on hardware.
#[test]
fn stage4_preset_zones_sit_one_stride_apart() {
    let mut raw = [0u8; ns4::synth::BODY_LEN];
    raw[42] |= 0b0010_0100;
    raw[93] |= 0b0010_0100;
    let body = ns4::synth::SynthPreset::try_from(raw).unwrap();
    assert_eq!(body.synth_a_performance.kb_zones, KbZone4::V9, "synth A");
    assert_eq!(body.synth_b_performance.kb_zones, KbZone4::V9, "synth B");
    assert_eq!(<[u8; ns4::synth::BODY_LEN]>::from(&body), raw);

    let mut raw = [0u8; ns4::organ_preset::BODY_LEN];
    raw[23] |= 0b1001_0000;
    raw[54] |= 0b1001_0000;
    let body = ns4::organ_preset::OrganPreset::try_from(raw).unwrap();
    assert_eq!(body.organ_a.kb_zones, KbZone4::V9, "organ A");
    assert_eq!(body.organ_b.kb_zones, KbZone4::V9, "organ B");
    assert_eq!(<[u8; ns4::organ_preset::BODY_LEN]>::from(&body), raw);

    let mut raw = [0u8; ns4::piano_preset::BODY_LEN];
    raw[18] |= 0b1001_0000;
    raw[30] |= 0b1001_0000;
    let body = ns4::piano_preset::PianoPreset::try_from(raw).unwrap();
    assert_eq!(body.piano_a.kb_zones, KbZone4::V9, "piano A");
    assert_eq!(body.piano_b.kb_zones, KbZone4::V9, "piano B");
    assert_eq!(<[u8; ns4::piano_preset::BODY_LEN]>::from(&body), raw);
}

/// Each Stage 4 preset places the layer type its program already declares, so the check
/// that matters is that nesting moved nothing. The bits below are the ones the preset
/// spelled out before it nested, taken at the far end of every layer — where a block
/// placed one byte out would show first.
#[test]
fn stage4_preset_layers_end_where_the_offsets_say() {
    let mut raw = [0u8; ns4::organ_preset::BODY_LEN];
    raw[51] = 0b0000_1000; // organ A percussion volume soft, bit 412
    raw[82] = 0b0000_1000; // organ B percussion volume soft, bit 660
    let body = ns4::organ_preset::OrganPreset::try_from(raw).unwrap();
    assert!(body.organ_a.percussion_volume_soft_enabled);
    assert!(body.organ_b.percussion_volume_soft_enabled);
    assert_eq!(<[u8; ns4::organ_preset::BODY_LEN]>::from(&body), raw);

    let mut raw = [0u8; ns4::piano_preset::BODY_LEN];
    raw[24] = 0b0000_1000; // piano A soft release, bit 196
    raw[36] = 0b0000_1000; // piano B soft release, bit 292
    let body = ns4::piano_preset::PianoPreset::try_from(raw).unwrap();
    assert!(body.piano_a.soft_rel_enabled);
    assert!(body.piano_b.soft_rel_enabled);
    assert_eq!(<[u8; ns4::piano_preset::BODY_LEN]>::from(&body), raw);

    let mut raw = [0u8; ns4::synth::BODY_LEN];
    raw[46] = 0b1000_0000; // synth A extern, bit 368
    raw[97] = 0b1000_0000; // synth B extern, bit 776
    raw[148] = 0b1000_0000; // synth C extern, bit 1184
    let body = ns4::synth::SynthPreset::try_from(raw).unwrap();
    assert!(body.synth_a_performance.extern_enabled);
    assert!(body.synth_b_performance.extern_enabled);
    assert!(body.synth_c_performance.extern_enabled);
    assert_eq!(<[u8; ns4::synth::BODY_LEN]>::from(&body), raw);
}

/// Look one field up in a body's registry, failing by name when it is not there.
fn spec<'a>(specs: &'a [FieldSpec], name: &str) -> &'a FieldSpec {
    specs
        .iter()
        .find(|spec| spec.name == name)
        .unwrap_or_else(|| panic!("no field {name}"))
}

/// A Stage 2 delay parameter is followed by the three slots that morph it, as every
/// other run in the body is — so the slots carry the parameter's own name and one width.
#[test]
fn stage2_delay_slots_carry_the_name_of_what_they_morph() {
    let specs = ns2::Slot::field_specs();
    for parameter in [
        "delay_tempo_master_clock_divisor",
        "delay_tempo",
        "delay_amount",
    ] {
        let widths: Vec<u32> = ["wheel", "aftertouch", "ctrl_pedal"]
            .iter()
            .map(|control| spec(&specs, &format!("{parameter}_{control}")).width)
            .collect();
        assert_eq!(widths[0], widths[1], "{parameter}");
        assert_eq!(widths[1], widths[2], "{parameter}");
    }
}

/// A morph slot beside a switch is still a morph slot: it is drawn on the switch, not as
/// a control of its own, whichever body declares it.
#[test]
fn switch_morph_slots_bind_to_the_switch_beside_them() {
    let bound = |specs: &[FieldSpec], slot: &str, parent: &str| {
        assert_eq!(
            spec(specs, slot).morph_parent().as_deref(),
            Some(parent),
            "{slot}",
        );
    };

    let globals = ns2::Program::field_specs();
    let slot = ns2::Slot::field_specs();
    let panel = ns3::Panel::field_specs();
    let voice = ns4::SynthVoice::field_specs();
    for control in ["wheel", "aftertouch", "ctrl_pedal"] {
        bound(
            &globals,
            &format!("rotary_speaker_speed_{control}"),
            "rotary_speaker_speed",
        );
        bound(
            &slot,
            &format!("synth_skip_sample_attack_{control}"),
            "synth_skip_sample_attack",
        );
        bound(
            &panel,
            &format!("extern_midi_cc_{control}"),
            "extern_midi_cc",
        );
        bound(
            &voice,
            &format!("filter_resonance_{control}"),
            "filter_resonance_freq_hp",
        );
    }
}

/// One representation of a concept: a Stage 2 slot spells every section's keyboard zone
/// and every clocked run's divisor the same way, so a caller finds them by section.
#[test]
fn a_stage2_slot_spells_its_repeated_concepts_alike() {
    let specs = ns2::Slot::field_specs();
    for section in ["organ", "piano", "synth", "extern"] {
        spec(&specs, &format!("{section}_kb_zone"));
    }
    for run in ["effect_1_rate", "effect_2_rate", "delay_tempo"] {
        spec(&specs, &format!("{run}_master_clock_divisor"));
    }
}

/// The rotor speed is one switch on every Stage, so the values a caller sets it to are
/// the same on every Stage.
#[test]
fn every_stage_offers_the_same_rotor_speeds() {
    let legal = |specs: &[FieldSpec], name: &str| (spec(specs, name).legal)();
    let stage2 = ns2::Program::field_specs();
    let stage3 = ns3::Program::field_specs();
    let stage4 = ns4::Program::field_specs();
    assert_eq!(
        legal(&stage2, "rotary_speaker_speed"),
        legal(&stage3, "rotary_speaker_speed"),
    );
    assert_eq!(
        legal(&stage3, "rotary_speaker_speed"),
        legal(&stage4, "rotary_speaker_slow_fast"),
    );
}

/// A vibrato/chorus mode is set by the name the panel prints on it, so the variant a
/// caller spells and the label it reads are the same word.
#[test]
fn stage3_organ_vibrato_modes_are_named_for_what_the_panel_prints() {
    for stored in 0..6u64 {
        let mode = ns3::program::OrganVibratoMode::from_bits(stored).expect("decoding is total");
        assert_eq!(format!("{mode:?}"), mode.label().expect("a named mode"));
    }
}

/// A MIDI number, a filter cutoff and half a split word are not panel `0..10` knobs. Each
/// is typed for what it is, so an interface never labels one with a reading it does not
/// have.
#[test]
fn slots_that_are_not_panel_knobs_are_not_typed_as_knobs() {
    let panel_knob = ControlKind::Knob(Unit::Panel10);

    let slot = ns2::Slot::field_specs();
    for midi in [
        "extern_midi_cc_number",
        "extern_midi_program",
        "extern_midi_bank_select_cc00",
        "extern_midi_bank_select_cc32",
    ] {
        assert_eq!(spec(&slot, midi).control, ControlKind::Number, "{midi}");
    }

    let panel = ns3::Panel::field_specs();
    for half in [
        "delay_tempo_lsw",
        "delay_tempo_wheel_lsw",
        "delay_tempo_aftertouch_lsw",
        "delay_tempo_ctrl_pedal_lsw",
    ] {
        assert_eq!(spec(&panel, half).control, ControlKind::Number, "{half}");
    }

    let voice = ns4::SynthVoice::field_specs();
    assert_eq!(
        spec(&voice, "filter_freq").control,
        ControlKind::Knob(Unit::Hertz),
    );
    assert_ne!(spec(&voice, "filter_freq").control, panel_knob);
}

/// The category is the whole id the header carries or nothing: a wider value names no
/// category rather than being truncated into one.
#[test]
fn a_program_category_reads_the_whole_aux_id() {
    let mut header = Header::new(ns3::program::FORMAT, (0, 0), 304);

    header.aux = 0x07;
    assert_eq!(ProgramCategory::of(&header), Some(ProgramCategory::Organ));

    header.aux = 0x0107;
    assert_eq!(ProgramCategory::of(&header), None, "0x0107 is not Organ");

    header.aux = 0xffff_ffff;
    assert_eq!(ProgramCategory::of(&header), None, "no category at all");
}