diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index f7bdfa1..d86bd0e 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -89,7 +89,7 @@ body: attributes: label: Version description: The release you flashed (e.g. from its file name), or the commit if you built it yourself. - placeholder: v0.8.2 + placeholder: v0.9.0 validations: required: true diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml index e66cefc..ec45be7 100644 --- a/.github/ISSUE_TEMPLATE/feature.yml +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -76,6 +76,6 @@ body: attributes: label: Version description: The release you are using, if the request is about something you've seen on hardware. - placeholder: v0.8.2 + placeholder: v0.9.0 validations: required: false diff --git a/LICENSES/MIT-Mutable-Instruments.txt b/LICENSES/MIT-Mutable-Instruments.txt index 313ddaa..7b5a2d3 100644 --- a/LICENSES/MIT-Mutable-Instruments.txt +++ b/LICENSES/MIT-Mutable-Instruments.txt @@ -1,5 +1,5 @@ Applies to: third_party/eurorack/ (Plaits, Marbles, stmlib), firmware/src/plaits_ovr/, -firmware/src/sp1_marbles_scales.inc, the build-time copies generated by +config/scales.cnfg (Marbles' preset scales), the build-time copies generated by firmware/CMakeLists.txt, and the portions of sp1_marbles.cc, sp1_plaits_ui.c and sp1_marbles_ui.c adapted from Plaits and Marbles (see NOTICE). diff --git a/LICENSES/README.md b/LICENSES/README.md index af6c133..06677d4 100644 --- a/LICENSES/README.md +++ b/LICENSES/README.md @@ -7,7 +7,7 @@ what was changed. | File | Holder | Covers | |---|---|---| -| `MIT-Mutable-Instruments.txt` | Emilie Gillet | `third_party/eurorack/` (Plaits, Marbles, stmlib), `firmware/src/plaits_ovr/`, `firmware/src/sp1_marbles_scales.inc`, the build-time copies made by `firmware/CMakeLists.txt`, and the adapted parts of `sp1_marbles.cc`, `sp1_plaits_ui.c`, `sp1_marbles_ui.c` and `sp1_midi.cc` (ported from Yarns) | +| `MIT-Mutable-Instruments.txt` | Emilie Gillet | `third_party/eurorack/` (Plaits, Marbles, stmlib), `firmware/src/plaits_ovr/`, `config/scales.cnfg` (Marbles' preset scales, written as Scala), the build-time copies made by `firmware/CMakeLists.txt`, and the adapted parts of `sp1_marbles.cc`, `sp1_plaits_ui.c`, `sp1_marbles_ui.c` and `sp1_midi.cc` (ported from Yarns) | | `MIT-feldd.txt` | Benjamin Reece | `third_party/feldd/` (the USB-MIDI 1.0 class and its packet parser) and the build-time patched copy of `usb_midi1.c` | | `MIT-sp1-tape-looper.txt` | chattock | the board definition, power-off and watchdog sequence, and codec bring-up adapted from chattock/sp1-tape-looper | | `MIT-SP-1-dev.txt` | Tim Knapen | the SP-1 pin map and hardware documentation from timknapen/SP-1-dev | diff --git a/NOTICE b/NOTICE index 336d87c..a47fc98 100644 --- a/NOTICE +++ b/NOTICE @@ -83,11 +83,10 @@ third_party/eurorack/ (marbles/random, marbles/ramp, resources), vendored unmodified in third_party/eurorack/marbles, same repository and licence. firmware/src/sp1_marbles.cc adapts marbles/marbles.cc's generator code - and copies its y-divider table; firmware/src/sp1_marbles_scales.inc - copies the preset scales from marbles/settings.cc; sp1_marbles_ui.c - copies the loop-length table from marbles.cc and Plaits' pot catch-up. - The seventh scale slot (sp1_free_scale in sp1_marbles.cc) is ours, written - in Marbles' own Scale format. Three changes to Marbles are applied at build + and copies its y-divider table; config/scales.cnfg holds the preset + scales from marbles/settings.cc, written in the Scala format (#44); + sp1_marbles_ui.c copies the loop-length table from marbles.cc and + Plaits' pot catch-up. Three changes to Marbles are applied at build time to generated copies, by firmware/CMakeLists.txt, leaving the vendored files unmodified: marbles/random/t_generator.h gains a master-phase setter so the clock can start on a beat (M4), marbles/random/x_y_generator.cc @@ -95,6 +94,11 @@ third_party/eurorack/ chosen per output channel (M4c), and marbles/random/t_generator.cc takes its external-clock ramp from MIDI clock instead of its ramp extractor (M5b) -- the policy behind those is ours, in firmware/src/sp1_marbles.cc. + For #44, marbles/random/output_channel.{h,cc} keep one quantizer per + channel instead of six (generated copies, as above), and + firmware/src/plaits_ovr/marbles/random/quantizer.{h,cc} are modified + copies of Marbles' quantizer holding 64 degrees instead of 16 (64-bit + masks); they keep Emilie Gillet's MIT header. MIDI (M5a): firmware/src/sp1_midi.cc ports the monophonic note handling of Mutable Instruments Yarns from the same eurorack commit -- the mono branches of yarns/part.cc (Part::InternalNoteOn/Off, its legato modes and hold diff --git a/README.md b/README.md index e4b73d3..262c4a0 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ The development of Wakes is unaffiliated with Teenage Engineering or Mutable Ins ## Status -**v0.8.2, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues). +**v0.9.0, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues). ## Flashing diff --git a/config/README.md b/config/README.md index efd2ada..274df5b 100644 --- a/config/README.md +++ b/config/README.md @@ -21,6 +21,7 @@ cannot read keeps its default and is named in the log (`WAKES/LOGS/`). | `engines.cnfg` | which Plaits engine sits in each of the 24 slots, and what every engine does | | `midi.cnfg` | MIDI over USB: channel, note priority, legato, portamento, which CC moves which parameter | | `audio.cnfg` | USB audio out: its level (parked or on VOL) and the speaker while a host records | +| `scales.cnfg` | the 7 scales Marbles' X and Plaits' FREQUENCY quantize to, in the Scala (.scl) format | | `logs.cnfg` | the log Wakes writes to its drive, and what goes in it | ## When to edit these diff --git a/config/logs.cnfg b/config/logs.cnfg index 88e02de..22f77b2 100644 --- a/config/logs.cnfg +++ b/config/logs.cnfg @@ -38,3 +38,7 @@ usb = off ; Storage drive logs: loading and saving presets (PRST), .logs files. storage = on + +; The scales scales.cnfg gave Wakes at every ON: each slot's scale, its degrees in cents and +; weights, and what Plaits plays. (A problem in scales.cnfg is always logged.) +scales = off diff --git a/config/scales.cnfg b/config/scales.cnfg new file mode 100644 index 0000000..d249264 --- /dev/null +++ b/config/scales.cnfg @@ -0,0 +1,472 @@ +; Format: scl blocks (Scala .scl scales, one per [slot]) +; ===================================================================================== +; Wakes — SCALES +; ===================================================================================== +; +; The scales MARBLES' X STPS quantizer (•• + FFWD / RWD on the X page) and PLAITS' FREQ +; quantizer (SETTINGS T2 / T3) choose from. Both modules use this one list. +; +; Wakes reads and applies this .cnfg file every time it turns ON. +; +; Lines starting with ; or # are comments. Delete this file to get the default back: +; Wakes writes it again at the next ON. +; +; ---- slots ---- +; There are 7 scale slots, [1] to [7]. A slot that is not in this file is empty, and the +; scale buttons skip it. A slot above [7] is dropped (the log says the file is overloaded). +; Every slot has its own glyph, so slot 2 always flashes ●●○○ whatever scale is in it. +; Presets (PRST) remember the scale SLOT: change what is in a slot and any preset that +; previously used that slot will play the new scale you've changed it to. +; +; ---- scales ---- +; Under a numbered [slot], a scale is written in the Scala format (.scl), the format of +; the Scala scale archive and of Scale Workshop (https://sevish.com/scaleworkshop/). Build +; a scale there, export it as a Scala file (.scl), open that in a text editor and paste it +; under a numbered [slot] section here, in place of any existing scales. +; To go back to the default scales.cnfg, just move the existing one off the storage or +; delete it, and Wakes will create a new copy from defaults. +; +; .scl format: +; lines starting with '!' are Scala-format comments +; the first other line is the scale's NAME (it can be empty) +; the next line is how many PITCHES comprise the scale +; then, one pitch designation appears per line, with the last one defining period/octave. +; +; In .scl format, the root (1/1, 0 cents) is not written: every scale starts on the root +; frequency, which is defined dynamically, based on the following factors: +; MARBLES' X: at 0 V. Routed to V/Oct, X is added to FREQUENCY, so the root is +; wherever FREQUENCY is set. +; PLAITS' quantizer: on C, or on the note you tune by ear (see tune_by_ear below). +; Pitches can be defined in CENTS or as RATIOS of the root. A pitch definition containing +; a "." is in CENTS (100.0 is a semitone); without one it is a RATIO (3/2, or 2 for 2/1). +; Write them in any order; each one must be above the root and below the period. Wakes +; takes 64 pitches at most, with the period included: enough for 31-EDO or 53-EDO. +; +; ---- Wakes' extras (other Scala programs ignore these) ---- +; +; You can define scales pretty simply using ratios and cents, but Wakes offers Mutable +; Instruments-derived features that let you play around with those scales. +; +; Note weight: a whole number 0-255 after a pitch defines its weight. +; Weights are how Marbles' STPS fader thins the scale out as it moves from its centre +; to 100%. Just up from centre, every degree of the scale is in: a scale written on all +; 12 semitones, like Marbles' major below, is chromatic there. Turning STPS further up +; drops the low-weight notes first, leaving the notes that define the scale, then fewer, +; until only the root (always 255) remains. Below the centre STPS does not quantize at +; all: X glides smoothly between values. A pitch without a weight gets 255 (it is always +; there). Any other text left in after a note's pitch definition is ignored. +; Important: Without note weights, Marbles cannot play around with which notes are +; available on the scale. As you define scales, remember which intervals sound good, and +; weight them to your taste. +; The period line (2/1 for the octave) never takes a weight: in Scala it marks where the +; scale ends and repeats, so it is the root again, one period up. A weight written there +; is ignored, for the same reason the root is never written and never weighted. The root +; is always 255 and never drops out: Marbles' quantizer always needs one note left to +; land on, even at the top of STPS. +; +; plaits = N (written above the scale's name, under its [slot]): PLAITS' quantizer plays +; the degrees with a weight of N or more. 0 (or leaving it out) = every degree. +; Marbles' scales below use 32 (pelog: 0). In the major scale, this makes Plaits' +; quantizer select the 7 notes of the major scale, not all 12 of its scale degrees, +; which would just be the chromatic scale. +; It helps to understand that, for example, if you wanted to use diatonic scales (musical +; modes), you would start with the chromatic definition Scala block (100.0, 200.0, etc.), +; and then set plaits = 32 and use the note weights to bring out the 7 actual intervals +; of the diatonic scale you are trying to create. The seven modes at the end of this +; file are written exactly that way. +; +; tune_by_ear = on / off (written above the scale's name, under its [slot]): Tune By Ear, +; for PLAITS' quantizer. On (or leaving it out): tune FREQUENCY by ear with the quantizer +; off (TRIG to listen), then turn the quantizer on (SETTINGS T3): the note FREQUENCY was +; playing becomes the scale's root, between semitones too. Stepping to another scale +; keeps that root; turning the quantizer off and on again takes a new one. Off: the +; scale stays on C, for scales whose notes belong to fixed pitches. Presets save the +; root with the scale. +; +; ---- if something is wrong ---- +; The log (WAKES/LOGS/) names every line Wakes cannot read. If ANY scale in this file has a +; problem, Wakes ignores the file and uses the default scales instead. +; Turn on "scales" in logs.cnfg to see which scales were loaded at every ON. +; +; Wakes' default scales.cnfg ships with slots [1]-[6] containing the original scales curated +; for Mutable Instruments' Marbles (marbles/settings.cc, Emilie Gillet, MIT), +; rewritten as Scala, and slot [7] with a whole-tone scale. Note names in the comments +; assume the root is C. + +[1] +plaits = 32 +tune_by_ear = on +! Marbles' major scale. Note names assume a root of C. +major +12 +! + 100.0 16 ; C# (root C) + 200.0 96 ; D (root C) + 300.0 24 ; D# (root C) + 400.0 128 ; E (root C) + 500.0 64 ; F (root C) + 600.0 8 ; F# (root C) + 700.0 192 ; G (root C) + 800.0 16 ; G# (root C) + 900.0 96 ; A (root C) +1000.0 24 ; A# (root C) +1100.0 128 ; B (root C) +2/1 + +[2] +plaits = 32 +tune_by_ear = on +! Marbles' minor scale. Note names assume a root of C. +minor +12 +! + 100.0 16 ; C# (root C) + 200.0 96 ; D (root C) + 300.0 128 ; Eb (root C) + 400.0 8 ; E (root C) + 500.0 64 ; F (root C) + 600.0 4 ; F# (root C) + 700.0 192 ; G (root C) + 800.0 96 ; G# (root C) + 900.0 16 ; A (root C) +1000.0 128 ; Bb (root C) +1100.0 16 ; B (root C) +2/1 + +[3] +plaits = 32 +tune_by_ear = on +! Marbles' pentatonic scale. Note names assume a root of C. +pentatonic +12 +! + 100.0 4 ; C# (root C) + 200.0 96 ; D (root C) + 300.0 4 ; Eb (root C) + 400.0 4 ; E (root C) + 500.0 140 ; F (root C) + 600.0 4 ; F# (root C) + 700.0 192 ; G (root C) + 800.0 4 ; G# (root C) + 900.0 96 ; A (root C) +1000.0 4 ; Bb (root C) +1100.0 4 ; B (root C) +2/1 + +[4] +plaits = 0 +tune_by_ear = off +! Pelog: seven degrees, all of them the scale. Note names assume a root of C +! (+ / - = a little sharp / flat of that note). +pelog +7 +! + 153.0 128 ; Db+ (root C) + 315.0 32 ; Eb- (root C) + 552.0 8 ; F#- (root C) + 705.96 192 ; G (root C) + 848.04 64 ; Ab (root C) +1058.04 16 ; Bb+ (root C) +2/1 + +[5] +plaits = 32 +tune_by_ear = off +! Raag Bhairav That, just intonation. Swara names, relative to Sa (the root). +bhairav +12 +! +256/243 128 ; Komal Re +9/8 4 ; Re +6/5 4 ; Komal Ga +5/4 128 ; Ga +4/3 64 ; Ma +45/32 4 ; Tivre Ma +3/2 192 ; Pa +128/81 64 ; Komal Dha +27/16 4 ; Dha +9/5 4 ; Komal Ni +15/8 64 ; Ni +2/1 + +[6] +plaits = 32 +tune_by_ear = off +! Raag Shri, just intonation. Swara names, relative to Sa (the root). +shri +12 +! +256/243 4 ; Komal Re +9/8 128 ; Re +6/5 64 ; Komal Ga +5/4 4 ; Ga +4/3 128 ; Ma +45/32 4 ; Tivre Ma +3/2 192 ; Pa +128/81 4 ; Komal Dha +27/16 64 ; Dha +9/5 128 ; Komal Ni +15/8 4 ; Ni +2/1 + + +[7] +tune_by_ear = on +! Whole tone. Six equal steps, Marbles note-elimination disabled. +whole-tone +6 +200.0 +400.0 +600.0 +800.0 +1000.0 +2/1 + +; ===================================================================================== +; THE SCALE LIBRARY: Wakes stops reading this file at the [scales_wiki] line below +; ===================================================================================== +; +; Everything under [scales_wiki] is a library of example scales. Wakes never reads it, +; so nothing there needs a ";" in front, and you can keep, edit or delete it as you like. +; Keep your own scales ABOVE the [scales_wiki] line: a slot below it is ignored (the log +; says so). +; +; To use one: copy the lines BETWEEN its two markers -- from the line below "vvvv copy +; from the line below vvvv" down to the line above "^^^^ copy down to the line above +; ^^^^" -- and paste them above [scales_wiki], under a slot line of your choice ([7] for +; example, replacing the scale that was there). The title and description lines above +; each block are for reading, not copying. +; +; The seven modes are each cut out of the chromatic scale with weights, the way Marbles' +; major scale is (Ionian below IS Marbles' major, note for note): +; the mode's notes root 255, 5th 192, 3rd 128, 7th 128, 2nd 96, 6th 96, 4th 64 +; the other 5 notes the 3rd or 7th the mode does NOT use 24, the tritone 8, others 16 +; So STPS keeps the root, fifth, third and seventh longest, and plaits = 32 gives Plaits +; each mode's 7 notes. + +[scales_wiki] + +; ---- Ionian (major): 1 2 3 4 5 6 7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +ionian +12 + 100.0 16 ; C# (root C) -- out + 200.0 96 ; D (root C) -- 2nd + 300.0 24 ; D# (root C) -- out, the other 3rd + 400.0 128 ; E (root C) -- 3rd + 500.0 64 ; F (root C) -- 4th + 600.0 8 ; F# (root C) -- out, tritone + 700.0 192 ; G (root C) -- 5th + 800.0 16 ; G# (root C) -- out + 900.0 96 ; A (root C) -- 6th +1000.0 24 ; A# (root C) -- out, the other 7th +1100.0 128 ; B (root C) -- 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- Dorian: 1 2 b3 4 5 6 b7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +dorian +12 + 100.0 16 ; C# (root C) -- out + 200.0 96 ; D (root C) -- 2nd + 300.0 128 ; Eb (root C) -- 3rd + 400.0 24 ; E (root C) -- out, the other 3rd + 500.0 64 ; F (root C) -- 4th + 600.0 8 ; F# (root C) -- out, tritone + 700.0 192 ; G (root C) -- 5th + 800.0 16 ; G# (root C) -- out + 900.0 96 ; A (root C) -- 6th +1000.0 128 ; Bb (root C) -- 7th +1100.0 24 ; B (root C) -- out, the other 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- Phrygian: 1 b2 b3 4 5 b6 b7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +phrygian +12 + 100.0 96 ; Db (root C) -- 2nd + 200.0 16 ; D (root C) -- out + 300.0 128 ; Eb (root C) -- 3rd + 400.0 24 ; E (root C) -- out, the other 3rd + 500.0 64 ; F (root C) -- 4th + 600.0 8 ; F# (root C) -- out, tritone + 700.0 192 ; G (root C) -- 5th + 800.0 96 ; Ab (root C) -- 6th + 900.0 16 ; A (root C) -- out +1000.0 128 ; Bb (root C) -- 7th +1100.0 24 ; B (root C) -- out, the other 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- Lydian: 1 2 3 #4 5 6 7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +lydian +12 + 100.0 16 ; C# (root C) -- out + 200.0 96 ; D (root C) -- 2nd + 300.0 24 ; D# (root C) -- out, the other 3rd + 400.0 128 ; E (root C) -- 3rd + 500.0 16 ; F (root C) -- out + 600.0 64 ; F# (root C) -- 4th (#4) + 700.0 192 ; G (root C) -- 5th + 800.0 16 ; G# (root C) -- out + 900.0 96 ; A (root C) -- 6th +1000.0 24 ; A# (root C) -- out, the other 7th +1100.0 128 ; B (root C) -- 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- Mixolydian: 1 2 3 4 5 6 b7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +mixolydian +12 + 100.0 16 ; C# (root C) -- out + 200.0 96 ; D (root C) -- 2nd + 300.0 24 ; D# (root C) -- out, the other 3rd + 400.0 128 ; E (root C) -- 3rd + 500.0 64 ; F (root C) -- 4th + 600.0 8 ; F# (root C) -- out, tritone + 700.0 192 ; G (root C) -- 5th + 800.0 16 ; G# (root C) -- out + 900.0 96 ; A (root C) -- 6th +1000.0 128 ; Bb (root C) -- 7th +1100.0 24 ; B (root C) -- out, the other 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- Aeolian (natural minor): 1 2 b3 4 5 b6 b7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +aeolian +12 + 100.0 16 ; C# (root C) -- out + 200.0 96 ; D (root C) -- 2nd + 300.0 128 ; Eb (root C) -- 3rd + 400.0 24 ; E (root C) -- out, the other 3rd + 500.0 64 ; F (root C) -- 4th + 600.0 8 ; F# (root C) -- out, tritone + 700.0 192 ; G (root C) -- 5th + 800.0 96 ; Ab (root C) -- 6th + 900.0 16 ; A (root C) -- out +1000.0 128 ; Bb (root C) -- 7th +1100.0 24 ; B (root C) -- out, the other 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- Locrian: 1 b2 b3 4 b5 b6 b7 +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +locrian +12 + 100.0 96 ; Db (root C) -- 2nd + 200.0 16 ; D (root C) -- out + 300.0 128 ; Eb (root C) -- 3rd + 400.0 24 ; E (root C) -- out, the other 3rd + 500.0 64 ; F (root C) -- 4th + 600.0 192 ; Gb (root C) -- 5th (b5) + 700.0 16 ; G (root C) -- out + 800.0 96 ; Ab (root C) -- 6th + 900.0 16 ; A (root C) -- out +1000.0 128 ; Bb (root C) -- 7th +1100.0 24 ; B (root C) -- out, the other 7th +2/1 +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- 31edo: Chromatic +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 0 +tune_by_ear = on +! 31edo: Chromatic +31edo +31 +! + 38.71 ; Superunison + 77.42 ; Augmented Unison + 116.13 ; Minor 2nd + 154.84 ; Neutral 2nd + 193.55 ; Major 2nd + 232.26 ; Supermajor 2nd + 270.97 ; Subminor 3rd + 309.68 ; Minor 3rd + 348.39 ; Neutral 3rd + 387.10 ; Major 3rd + 425.81 ; Supermajor 3rd + 464.52 ; Sub 4th + 503.23 ; Perfect 4th + 541.94 ; Super 4th + 580.65 ; Augmented 4th + 619.35 ; Diminished 5th + 658.06 ; Sub 5th + 696.77 ; Perfect 5th + 735.48 ; Super 5th + 774.19 ; Subminor 6th + 812.90 ; Minor 6th + 851.61 ; Neutral 6th + 890.32 ; Major 6th + 929.03 ; Supermajor 6th + 967.74 ; Subminor 7th + 1006.45 ; Minor 7th + 1045.16 ; Neutral 7th + 1083.87 ; Major 7th + 1122.58 ; Supermajor 7th + 1161.29 ; Sub-Octave + 2/1 ; Octave +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +; ---- 31edo: Mothra[6] +; Six notes of 31edo, each 6 steps (232.26 cents, close to 8/7) above the last: +; root, supermajor 2nd, sub 4th, perfect 5th, supermajor 6th, sub-octave +; (steps 6 6 6 6 6 1). STPS keeps the 5th longest, then the 2nd, then the rest. +; vvvvvvvvvvvvvvvvvvvvvvvvvvvv copy from the line below vvvvvvvvvvvvvvvvvvvvvvvvvvvv +plaits = 32 +tune_by_ear = on +! 31edo Mothra[6]: generator 6 steps of 31 (232.26 cents), steps 6 6 6 6 6 1 +31edo-mothra6 +31 +! + 38.71 16 ; Superunison -- out + 77.42 16 ; Augmented Unison -- out + 116.13 16 ; Minor 2nd -- out + 154.84 16 ; Neutral 2nd -- out + 193.55 16 ; Major 2nd -- out + 232.26 128 ; Supermajor 2nd -- Mothra: 1 generator + 270.97 16 ; Subminor 3rd -- out + 309.68 24 ; Minor 3rd -- out, the other 3rd/7th + 348.39 16 ; Neutral 3rd -- out + 387.10 24 ; Major 3rd -- out, the other 3rd/7th + 425.81 16 ; Supermajor 3rd -- out + 464.52 64 ; Sub 4th -- Mothra: 2 generators + 503.23 16 ; Perfect 4th -- out + 541.94 16 ; Super 4th -- out + 580.65 8 ; Augmented 4th -- out, tritone + 619.35 8 ; Diminished 5th -- out, tritone + 658.06 16 ; Sub 5th -- out + 696.77 192 ; Perfect 5th -- Mothra: 3 generators + 735.48 16 ; Super 5th -- out + 774.19 16 ; Subminor 6th -- out + 812.90 16 ; Minor 6th -- out + 851.61 16 ; Neutral 6th -- out + 890.32 16 ; Major 6th -- out + 929.03 96 ; Supermajor 6th -- Mothra: 4 generators + 967.74 16 ; Subminor 7th -- out + 1006.45 24 ; Minor 7th -- out, the other 3rd/7th + 1045.16 16 ; Neutral 7th -- out + 1083.87 24 ; Major 7th -- out, the other 3rd/7th + 1122.58 16 ; Supermajor 7th -- out + 1161.29 48 ; Sub-Octave -- Mothra: 5 generators + 2/1 ; Octave +; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ copy down to the line above ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/DEFAULTS.md b/docs/DEFAULTS.md index ed6f4d2..9e0295d 100644 --- a/docs/DEFAULTS.md +++ b/docs/DEFAULTS.md @@ -153,7 +153,7 @@ A ROTC on MARBLES now leaves the drive alone, deliberately. | X SHIFT F4 | LENGTH `[I]` | — | — | — | the same control as t SHIFT F4 | | T1 | diversity `[N]` | identical / bump / tilt | **identical** | **identical** | | | SETTINGS T4 | range `[J]`, **X and Y** | 0–2 V / 0–5 V / ±5 V / INTELLIGENT | **INTELLIGENT** | **INTELLIGENT** | M4c; ONE control for both groups since M4e. Per CHANNEL, so X1–X3 and Y can each be at a different range at once | -| `••`+FFWD/RWD | scale | 7 slots, 6 included | **major** | **major** | | +| `••`+FFWD/RWD | scale | 7 slots from `scales.cnfg` (#44), all 7 filled by default | **the first filled slot** (major) | **the first filled slot** (major) | | ### Y section (SETTINGS page) diff --git a/docs/MARBLES-SETTINGS.md b/docs/MARBLES-SETTINGS.md index 060e1ed..0594f4a 100644 --- a/docs/MARBLES-SETTINGS.md +++ b/docs/MARBLES-SETTINGS.md @@ -134,91 +134,131 @@ the value it is on (and, with STEPS smooth, ramps across the two). One clock tic ## Scales — `••` + FFWD / RWD on the X page Marbles puts scale selection on a long press of `[J]`; here it is the shifted FFWD / RWD rocker, -because there are no long presses in this UI (Adara, M4a). **No wrap**, and **excluded scales -are skipped**. Glyphs are those of engine slots 1–7, as Adara asked. Slot glyphs are fixed, so the two can't -drift apart. +because there are no long presses in this UI (Adara, M4a). **No wrap**, and **empty slots are +skipped**. Glyphs are those of engine slots 1–7, as Adara asked, and belong to the SLOT, not to +the scale in it. The scale is what X quantizes to when `STEPS` (X page F3) is above its centre. Below the centre X is smooth and the scale does nothing. -| # | Glyph | Scale | Degrees (volts above the root, weight 0–255) | On | -|---|---|---|---|---| -| 1 | `●○○○` | major | C 0.0000/255 · C♯ 0.0833/16 · D 0.1667/96 · D♯ 0.2500/24 · E 0.3333/128 · F 0.4167/64 · F♯ 0.5000/8 · G 0.5833/192 · G♯ 0.6667/16 · A 0.7500/96 · A♯ 0.8333/24 · B 0.9167/128 | yes | -| 2 | `●●○○` | minor | C 0.0000/255 · C♯ 0.0833/16 · D 0.1667/96 · E♭ 0.2500/128 · E 0.3333/8 · F 0.4167/64 · F♯ 0.5000/4 · G 0.5833/192 · G♯ 0.6667/96 · A 0.7500/16 · B♭ 0.8333/128 · B 0.9167/16 | yes | -| 3 | `●●●○` | pentatonic | C 0.0000/255 · C♯ 0.0833/4 · D 0.1667/96 · E♭ 0.2500/4 · E 0.3333/4 · F 0.4167/140 · F♯ 0.5000/4 · G 0.5833/192 · G♯ 0.6667/4 · A 0.7500/96 · B♭ 0.8333/4 · B 0.9167/4 | yes | -| 4 | `●●●●` | pelog | 7 degrees, Javanese tuning — not 12-tone | yes | -| 5 | `○●●●` | bhairav | Hindustani raga | yes | -| 6 | `○○●●` | shri | Hindustani raga | yes | -| 7 | `○○○●` | **free slot** | chromatic, every degree at 255 — **Adara's to replace** | **no** | - -Slots 1–6 are Marbles' own, verbatim in `firmware/src/sp1_marbles_scales.inc` (copied from -`marbles/settings.cc` and not to be edited). Slot 7 is ours, in `sp1_marbles.cc` as -`sp1_free_scale`. - -### Writing a custom scale - -```c -const Scale sp1_free_scale = { - 1.0f, // base_interval: how far up the pattern repeats, in VOLTS. - // 1.0 = one octave at 1 V/oct. 0.5 would repeat every tritone. - 12, // num_degrees: how many entries below are used. Up to 16. - { - { 0.0000f, 255 }, // { volts above the root, weight } - { 0.0833f, 16 }, - ... - } -}; +### The scales are a file: `scales.cnfg` (#44) + +Since #44 the seven slots come from **`WAKES/CNFG/scales.cnfg`** on Wakes' drive, read at every +ON; `config/scales.cnfg` in the repository is the built-in default (and the text Wakes writes to +the drive when the file is missing). The file explains its own format to users. In short: one +`[1]`–`[7]` section per slot, each holding a scale in the **Scala `.scl` format**, so a scale +built in [Scale Workshop](https://sevish.com/scaleworkshop/) and exported as `.scl` can be pasted +under a slot as it is. + +``` +[1] +plaits = 32 Wakes: Plaits plays the degrees of weight >= 32 (default 0: all) +tune_by_ear = on Wakes: Plaits' root is the note tuned by ear (default on; #30) +! a Scala comment +major the description: the scale's name in the log +12 pitches that follow, the period included (1-64) + 100.0 16 cents (has a ".") or a ratio (3/2, 2), then Wakes' WEIGHT 0-255 + ... +2/1 the last pitch is the period: 2/1 = the octave ``` -- **Volts, not semitones.** One semitone is `1/12 V = 0.0833333f`. Two semitones is - `0.1666667f`, and so on. Non-equal tunings are just other numbers — that is how pelog works. - Degrees must be in ascending order and below `base_interval`. -- **Weight is probability, not level.** It is how often the quantizer is willing to land on that - degree: 255 = always available, 0 = never chosen, and everything between biases the sequence. - It does **not** make that note louder. Marbles' own scales use it to make a scale *sound* like - itself — in `major`, the root is 255, the fifth 192, the third and seventh 128, and the - accidentals 4–24, so chromatic notes appear as occasional colour rather than as equals. -- A **flat** scale (every weight equal) is a chromatic run with no tonal centre. That is what - the free slot holds today, which is why it ships **off**: it is a placeholder, not a choice. -- After editing it, set its `On` to `yes` here **and** `scale_on[6]` to `true` in - `firmware/src/sp1_marbles_ui.c`. +- The root (1/1) is implicit, as in Scala, and always weight 255. Pitches may come in any order. +- A **weight** after a pitch is Wakes' extra (Scala tools ignore text after a pitch); a pitch + without one is 255. Any other text after a pitch is ignored. +- **64 pitches at most**, the period included: 31-EDO, 53-EDO fit. Upstream Marbles holds 16 + (`kMaxDegrees`, 16-bit masks); Wakes replaces its quantizer (`src/plaits_ovr/marbles/random/ + quantizer.{h,cc}`: 64 and 64-bit masks, nothing else changed) and keeps ONE quantizer per + output instead of six (generated override of `output_channel.{h,cc}`), which pays for the + bigger tables. The quantizer only runs when an output draws a new value (a clock tick), not + per sample, so a long scale costs no CPU to speak of. +- Any period, not only the octave: 3/1 (Bohlen-Pierce) works on both modules. +- **All or nothing**, like `engines.cnfg`: a problem anywhere in the file and Wakes uses the + built-in scales, every problem named in the log (`CNFG scales.cnfg line N: …`). The one + exception (Adara): a slot above `[7]` is **dropped** and the log says the file is + **overloaded**; the rest loads. +- **`[scales_wiki]` ends the scales.** Wakes reads nothing below that line, so the file's + library of examples (the seven modes, 31-EDO chromatic, 31-EDO Mothra[6]) sits there + uncommented, each between a "copy from the line below" and a "copy down to the line above" + marker, ready to paste under a slot above it. A `[n]` found below it is ignored with a note + in the log. The build checks that every example loads when pasted. +- **PRST stores the slot** (its tokens `major` … `free` mean slots 1–7, unchanged so every saved + preset still loads). Change what a slot holds and the presets that used it play the new scale. + A preset on a slot that is now empty: Marbles takes the first filled slot, Plaits' quantizer off. +- `logs.cnfg`'s `scales = on` logs the bank at every ON: each slot's name, period, degrees in + cents with their weights, and what Plaits plays (`SCALES …` lines). + +### The built-in bank + +Slots 1–6 are Marbles' own (`marbles/settings.cc`, Emilie Gillet, MIT), written as Scala. Slot 7 +holds a whole-tone scale (Adara): six equal 200-cent steps, every weight 255, so STEPS keeps +all six and Plaits plays all six; tune by ear on. + +| # | Glyph | Scale | Written as | Plaits plays | +|---|---|---|---|---| +| 1 | `●○○○` | major | 12-TET cents, Marbles' weights (C 255 · G 192 · E, B 128 · D, A 96 · F 64 · the rest 8–24) | weight ≥ 32 | +| 2 | `●●○○` | minor | 12-TET cents, Marbles' weights | weight ≥ 32 | +| 3 | `●●●○` | pentatonic | 12-TET cents, Marbles' weights | weight ≥ 32 | +| 4 | `●●●●` | pelog | Marbles' cents: 153 · 315 · 552 · 705.96 · 848.04 · 1058.04 | all | +| 5 | `○●●●` | bhairav | just ratios: 256/243 · 9/8 · 6/5 · 5/4 · 4/3 · 45/32 · 3/2 · 128/81 · 27/16 · 9/5 · 15/8 | weight ≥ 32 | +| 6 | `○○●●` | shri | the same ratios, shri's weights | weight ≥ 32 | +| 7 | `○○○●` | whole-tone | cents: 200 · 400 · 600 · 800 · 1000, no weights (all 255) | all | + +Marbles stores its scales as 4-decimal voltages (a semitone is `0.0833`, Komal Re `0.0752`). The +Scala form writes what those numbers stand for — 100 cents, 256/243 — so every degree moved by +**at most 0.12 cents** (9/5 in the ragas; 0.04 cents in the 12-TET scales). Inaudible, and +`cnfgtest` §7 checks the bound. + +### Weights and STEPS + +**Weight is how long a degree survives as STEPS goes up**, not loudness or probability of a +single note. Marbles' quantizer has seven levels, thresholds 0 · 16 · 32 · 64 · 128 · 192 · 255: +past STEPS' centre, turning it up raises the threshold, and the degrees whose weight falls below +it drop out, until only the root (255) is left. Marbles' own scales use this to make a scale +*sound* like itself — in `major`, the root is 255, the fifth 192, the third and seventh 128, and +the accidentals 4–24, so chromatic notes appear as occasional colour rather than as equals. + +A **flat** scale (every weight 255, which is what a pasted Scale Workshop scale is) stays whole at +every STEPS setting above the centre. ### Plaits borrows the same scales (M4b) The PLAITS SETTINGS page's T2 / T3 quantize **Plaits' FREQUENCY fader** to one of these -scales. Plaits keeps its **own** index into the table, so the two modules can be in different +scales. Plaits keeps its **own** index into the slots, so the two modules can be in different scales at once, and it runs on its own `marbles::Quantizer` instance in the main thread — nothing shared with the four the audio thread is using. **There is no "amount" control (Adara): each scale quantizes to the note set its NAME means.** That is not the same as "every degree in the table". Marbles stores major as *twelve* weighted degrees, so admitting all of them would quantize to a chromatic scale and make four of the six -scales sound identical. `scale_level` in `sp1_marbles.cc` picks the weight threshold per scale -that yields the named set. Measured by sweeping F1 across the full range and collecting the -distinct pitches, in semitones above the root: +scales sound identical. Each scale's **`plaits =`** weight picks the set; the quantizer is loaded +with only those degrees. Measured by sweeping F1 across the full range and collecting the +distinct pitches, in semitones above the root (`routetest`): -| scale | level | notes per octave | degrees (semitones) | +| scale | `plaits` | notes per period | degrees (semitones) | |---|---|---|---| -| major | 3 (≥32) | 7 | 0 · 2 · 4 · 5 · 7 · 9 · 11 | -| minor | 3 (≥32) | 7 | 0 · 2 · 3 · 5 · 7 · 8 · 10 | -| pentatonic | 3 (≥32) | 5 | 0 · 2 · 5 · 7 · 9 | -| pelog | 1 (all) | 7 | 0 · **1.53** · **3.15** · **5.52** · **7.06** · **8.48** · **10.58** | -| bhairav | 3 (≥32) | 7 | 0 · **0.90** · **3.86** · **4.98** · **7.02** · **7.92** · **10.88** | -| shri | 3 (≥32) | 7 | 0 · **2.04** · **3.16** · **4.98** · **7.02** · **9.06** · **10.17** | -| free slot | 1 (all) | 12 | every semitone, until you replace it | - -⚠️ **Pelog is the one that needs level 1**: its seven degrees *are* the scale, and at level 3 it -would lose two of them. ⚠️ **Level 1 on major, minor, bhairav or shri admits all twelve -degrees** — chromatic. Do not collapse `scale_level` to a single constant. +| major | 32 | 7 | 0 · 2 · 4 · 5 · 7 · 9 · 11 | +| minor | 32 | 7 | 0 · 2 · 3 · 5 · 7 · 8 · 10 | +| pentatonic | 32 | 5 | 0 · 2 · 5 · 7 · 9 | +| pelog | 0 (all) | 7 | 0 · **1.53** · **3.15** · **5.52** · **7.06** · **8.48** · **10.58** | +| bhairav | 32 | 7 | 0 · **0.90** · **3.86** · **4.98** · **7.02** · **7.92** · **10.88** | +| shri | 32 | 7 | 0 · **2.04** · **3.16** · **4.98** · **7.02** · **9.06** · **10.18** | + +⚠️ **Pelog needs 0**: its seven degrees *are* the scale, and at 32 it would lose two of them. +⚠️ **0 on major, minor, bhairav or shri admits all twelve degrees** — chromatic. + +Until #44 this was `scale_level` (a Marbles level per scale, 3 = weight ≥ 32, 1 = all) with the +whole scale loaded: the same notes, but only the seven level thresholds were possible. **Three of these are microtonal.** Pelog, bhairav and shri put degrees at 1.53, 0.90, 3.16… semitones — nowhere near the semitone grid. That is what they are for, and it means Plaits' -pitch will not be a MIDI note number when they are selected. +pitch will not be a MIDI note number when they are selected. Octave mode 9 with a scale steps +through the degrees across nine PERIODS (nine octaves for every built-in scale). -### Why there can be seven +### Why there can be seven, and how a new file takes effect Marbles gives every output channel six quantizer slots and preloads all six, so six is its -ceiling. We load **only the selected scale**, into slot 0 of all four channels, from the audio +ceiling. We load **only the selected scale**, into slot 0 of all four channels (since #44 the +only slot: the other five are overridden away), from the audio thread when the selection changes (`LoadScaleIfNeeded` in `sp1_marbles.cc`). The count is therefore ours to pick and costs one `Quantizer::Init` per change, which is a table recompute of about a thousand cycles for four channels. @@ -227,41 +267,13 @@ about a thousand cycles for four channels. three X channels, so M4 left Y's quantizer holding Marbles' empty default scale. Nothing showed, because Y STEPS defaults below its centre where Y uses the lag processor and never quantizes. -### Writing a scale of your own (Adara asked, M4e) +The bank (`sp1_scales.c`) keeps **two copies**: the ON job writes the one not in use and flips, +**once per ON job**, before PRST checks its slots — so no reader ever sees a scale half-written. +Every install bumps a generation number; the audio thread and Plaits' quantizer reload their slot +when it changes (one compare per audio block). Main then moves a selection off a slot the new +file emptied (`sp1_mui_scales_settle`, `sp1_pui_scales_settle`). -Slot 7, `sp1_free_scale` in `sp1_marbles.cc`, is yours. It ships as a chromatic placeholder with -`scale_on[6] = false`, so it exists and is skipped. - -⚠️ **Do not add to `sp1_marbles_scales.inc`** — that file is vendored verbatim from -`marbles/settings.cc` and must stay byte-identical to upstream. Edit `sp1_free_scale` instead. - -The format is Marbles' own `Scale` (`marbles/random/quantizer.h`): - -```c -{ - 1.0f, // base_interval: the octave, in VOLTS. 1.0 = 1 V/oct. - 12, // num_degrees: how many entries below are used (max 16) - { - { 0.0000f, 255 }, // { voltage within the interval, weight 0-255 } - { 0.0833f, 16 }, // 0.0833 V = one semitone at 1 V/oct - ... - } -} -``` - -- **Degrees are VOLTAGES, not semitones.** A semitone is 1/12 = 0.08333 V. That is exactly what - makes the microtonal scales above possible: pelog's degrees are not multiples of 1/12. -- **Weight is how strongly a degree attracts**, and a threshold decides which weights count at - all. That is why `scale_level` exists. **If you add a scale, give it a level too** — or the - simplest thing: weight every degree **255** and set its level to **1**, which means "all of - these, always" and is how to write a scale you want taken literally. -- To put it in the ring: `scale_on[6] = true` and give it a glyph in `scale_glyph[]` - (`sp1_marbles_ui.c`). Both are already wired. Going beyond seven means bumping - `SP1_MUI_SCALES` and `SP1_MARBLES_SCALES` and adding a row to each of those three tables. -- `tools/host-tests/uitest` fails if two glyphs collide, so a mistake there is caught before it - reaches hardware. - ---- +`tools/host-tests/uitest` fails if two slot glyphs collide. ## Y divider — SETTINGS F4 diff --git a/docs/UI-PAGES.md b/docs/UI-PAGES.md index 413ee03..a2b80b7 100644 --- a/docs/UI-PAGES.md +++ b/docs/UI-PAGES.md @@ -95,9 +95,11 @@ So the combination space is exactly: **`••` + one button**, on either ladder - **LEVEL below 5 % is DISCONNECTED**, which is not the same as zero: disconnected means TRIG plucks the note through the LPG, connected means the VCA is held open by LEVEL — the drone. - **OCTAVE range** is Plaits' own eleven modes, `plaits/ui.cc`, with one change: 0 = the full - range with **no centre detent** (Plaits' LFO range is gone, #18), 1–8 = one octave each - ±7 semitones, 9 = octaves quantized, 10 = the full 96-semitone range with the C4 detent (the - default). + range with **no centre detent** (Plaits' LFO range is gone, #18), 1–8 = two octaves around + each octave's C, **root an octave down at the bottom, an octave up at the top** (Plaits: + ±7 semitones; #44 — with a scale on, one of *its* periods either side of *its* root, so + both ends are roots whatever the scale), 9 = octaves quantized, 10 = the full + 96-semitone range with the C4 detent (the default). - Every layer keeps its own four values, and a fader that does not match the value it is showing **catches up** rather than jumping (Plaits' own `PotController` behaviour). - ⚠️ **Only BASE is ever seeded from the physical faders**, and only on the first ON after boot. @@ -171,8 +173,15 @@ Tap `••` to get back to the base page first. Restricts the notes F1 can select to one of the seven scales Marbles' X quantizer offers (`docs/MARBLES-SETTINGS.md` has the table, the glyphs and the exact note sets). Plaits keeps its **own** index into that table, so the two modules can be in different scales. `○○○○` = off, -first in the ring, and only *included* scales are reachable. No wrap. - +first in the ring, and only *filled* slots are reachable (`scales.cnfg`, #44). No wrap. + +- **Tune By Ear (#30).** Turning the quantizer ON (T3 from `○○○○`) takes the note F1 was + playing as the scale's **root** — any pitch, between semitones too. Tune F1 by ear with the + quantizer off (TRIG to check), then turn it on. Stepping between scales keeps the root; + off and on again takes a new one. A scale with `tune_by_ear = off` in `scales.cnfg` (pelog + and the ragas by default) stays on C. A preset saves the root with the scale + (`quantizer_root`, PRST format 2); a preset saved before it (format 1) loads on C. The + log's `QUANTIZE` line names the root. - **It composes with the OCTAVE range rather than replacing it.** The range decides the span F1 covers; the scale decides which notes inside that span exist. - **Three of the scales are microtonal** — pelog, bhairav and shri put their degrees at diff --git a/docs/Wakes - Manual.pdf b/docs/Wakes - Manual.pdf index 5be36a1..70e2b67 100644 Binary files a/docs/Wakes - Manual.pdf and b/docs/Wakes - Manual.pdf differ diff --git a/firmware/CMakeLists.txt b/firmware/CMakeLists.txt index b0f71ae..0596eed 100644 --- a/firmware/CMakeLists.txt +++ b/firmware/CMakeLists.txt @@ -88,6 +88,21 @@ add_custom_command( add_custom_target(sp1_logs_gen DEPENDS ${SP1_LOGS_H}) add_dependencies(app sp1_logs_gen) +# ---- the scales: config/scales.cnfg -> sp1_scales_gen.h (#44) ---- +# The built-in scale bank (Scala blocks, one per slot) the drive's WAKES/CNFG/scales.cnfg +# replaces, and the file's text for the drive. A bad default fails the build, naming the line. +set(SP1_SCALES_CNFG ${CMAKE_CURRENT_SOURCE_DIR}/../config/scales.cnfg) +set(SP1_SCALES_GEN ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_scales.py) +set(SP1_SCALES_H ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated/sp1_scales_gen.h) +add_custom_command( + OUTPUT ${SP1_SCALES_H} + COMMAND ${Python3_EXECUTABLE} ${SP1_SCALES_GEN} ${SP1_SCALES_CNFG} ${SP1_SCALES_H} + DEPENDS ${SP1_SCALES_CNFG} ${SP1_SCALES_GEN} + COMMENT "Generating the scale bank from config/scales.cnfg" +) +add_custom_target(sp1_scales_gen DEPENDS ${SP1_SCALES_H}) +add_dependencies(app sp1_scales_gen) + # ---- PRST (M6, #50): the slot file's field table, from tools/gen_prst.py ---- # No user input: the field list lives in the script. It also holds the format versions, and # FAILS the build if the field list changed without a new version (Adara, #50). @@ -346,6 +361,21 @@ if(CONFIG_SP1_PLAITS) sp1_plaits_override(marbles/random/t_generator.h " inline void set_model(TGeneratorModel model) {" " // wakes-sp1 (M4): PLAY starts the clock on a beat.\n inline void set_master_phase(float phase) {\n master_phase_ = phase;\n }\n\n inline void set_model(TGeneratorModel model) {") + # #44: scales.cnfg scales of up to 64 degrees (31-EDO, 53-EDO): the quantizer's degree + # arrays and active-degree masks, upstream 16 / uint16_t. Whole-file replacements, as + # three passages in the .cc and two in the .h are past one override per file. + sp1_plaits_replace(marbles/random/quantizer.h) + sp1_plaits_replace(marbles/random/quantizer.cc) + # #44: ONE quantizer per output channel, upstream six (one per stored scale). Wakes loads + # the selected scale into slot 0 and never selects another (sp1_marbles.cc, + # LoadScaleIfNeeded), so the other five were dead weight: 20 quantizers of ~0.4 KB each + # at 64 degrees. + sp1_plaits_override(marbles/random/output_channel.h + " Quantizer quantizer_[6];" + " Quantizer quantizer_[1]; // wakes-sp1 (#44): upstream 6, Wakes uses slot 0 only") + sp1_plaits_override(marbles/random/output_channel.cc + " for (int i = 0; i < 6; ++i) {" + " for (int i = 0; i < 1; ++i) { // wakes-sp1 (#44): one quantizer (output_channel.h)") # ⚠️ Remove any generated file that is no longer an override (issue #22). SP1_OVR is # FIRST on the include path, so a stale copy left by an earlier configure -- voice.h @@ -437,7 +467,7 @@ if(CONFIG_SP1_PLAITS) ) # A Zephyr library declared from the APPLICATION is not linked on its own. target_link_libraries(app PRIVATE sp1_plaits) - target_sources(app PRIVATE src/sp1_marbles_ui.c src/sp1_prst.c) + target_sources(app PRIVATE src/sp1_marbles_ui.c src/sp1_prst.c src/sp1_scales.c) target_include_directories(app PRIVATE src) # ---- M5a: USB-MIDI in (the MIDI script is generated above, with the engines) ---- diff --git a/firmware/VERSION b/firmware/VERSION index 98240f4..1552ff1 100644 --- a/firmware/VERSION +++ b/firmware/VERSION @@ -1,5 +1,5 @@ VERSION_MAJOR = 0 -VERSION_MINOR = 8 -PATCHLEVEL = 2 +VERSION_MINOR = 9 +PATCHLEVEL = 0 VERSION_TWEAK = 0 EXTRAVERSION = diff --git a/firmware/src/main.c b/firmware/src/main.c index bfbb85d..bc6c6a7 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -638,6 +638,28 @@ static const char *plaits_scale_name(void) return s < 0 ? "off (every semitone)" : sp1_marbles_scale_name(s); } +/* The scale's root for the log (Tune By Ear, #30): "root D#3 +12 cents (by ear)". */ +static const char *plaits_scale_root(char *b, size_t n) +{ + static const char *const NAME[12] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", + "A", "A#", "B" }; + if (sp1_pui_scale() < 0) { + b[0] = '\0'; + return b; + } + if (!sp1_pui_scale_by_ear()) { + snprintk(b, n, ", root C (this scale is not tuned by ear)"); + return b; + } + const float r = sp1_pui_scale_root(); + const int k = (int)(r + 1000.5f) - 1000; /* the nearest semitone */ + const float c = (r - (float)k) * 100.0f; /* -50 .. +50 */ + const int cents = (int)(c + (c < 0.0f ? -0.5f : 0.5f)); + const int pc = ((k % 12) + 12) % 12; + snprintk(b, n, ", root %s%d %+d cents (by ear)", NAME[pc], (k - pc) / 12 - 1, cents); + return b; +} + static void plaits_scale_glyph(uint8_t lv[4]) { const int s = sp1_pui_scale(); @@ -670,15 +692,16 @@ static void plaits_scale_step(int dir) * A quantizer and a Marbles output both deciding the pitch is never wanted. Turning * a scale ON therefore UNPATCHES every V/Oct route. (The other direction, routing to * V/Oct, turns the scale off and opens the range -- see marbles_buttons.) */ + char root[64]; if (s != SP1_PUI_SCALE_OFF) { const int n = sp1_mui_unpatch_voct(); if (n > 0) { - printk("QUANTIZE %s: unpatched %d V/Oct route%s\n", - plaits_scale_name(), n, n == 1 ? "" : "s"); + printk("QUANTIZE %s%s: unpatched %d V/Oct route%s\n", plaits_scale_name(), + plaits_scale_root(root, sizeof(root)), n, n == 1 ? "" : "s"); return; } } - printk("QUANTIZE %s\n", plaits_scale_name()); + printk("QUANTIZE %s%s\n", plaits_scale_name(), plaits_scale_root(root, sizeof(root))); } /* PLAITS module buttons, except PLAY, T4 (module) and FFWD's burst, which main handles for @@ -1459,6 +1482,16 @@ int main(void) } /* #52: the ON job may have installed a new engine stack (engines.cnfg). */ sp1_pui_stack_settle(); + /* #44: ...and a new scale bank (scales.cnfg): a selection on a slot it emptied + * moves (Marbles: the first filled slot; Plaits: off), and Plaits' quantizer takes + * its slot's new contents. Marbles' X reloads by itself (sp1_marbles.cc). */ + if (sp1_mui_scales_settle()) { + printk("SCALES Marbles' scale slot is empty now: %d (%s) instead\n", + sp1_mui_scale() + 1, sp1_marbles_scale_name(sp1_mui_scale())); + } + if (sp1_pui_scales_settle()) { + printk("SCALES Plaits' scale slot is empty now: its quantizer is off\n"); + } /* ...and read audio.cnfg and midi.cnfg: applied here, before the MIDI reset and * audio start below, so nothing runs on a half-applied script. */ { diff --git a/firmware/src/plaits_ovr/marbles/random/quantizer.cc b/firmware/src/plaits_ovr/marbles/random/quantizer.cc new file mode 100644 index 0000000..14f237d --- /dev/null +++ b/firmware/src/plaits_ovr/marbles/random/quantizer.cc @@ -0,0 +1,142 @@ +// Copyright 2015 Emilie Gillet. +// +// Author: Emilie Gillet (emilie.o.gillet@gmail.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// See http://creativecommons.org/licenses/MIT/ for more information. +// +// ----------------------------------------------------------------------------- +// +// Variable resolution quantizer. +// +// wakes-sp1 (#44): a whole-file replacement (firmware/CMakeLists.txt, sp1_plaits_replace). +// Up to 64 degrees instead of 16, so scales.cnfg can hold 31-EDO, 53-EDO and the like: the +// active-degree masks are 64-bit (Sp1DegreeMask). Nothing else differs from upstream. + +#include "marbles/random/quantizer.h" + +#include "stmlib/dsp/dsp.h" + +#include +#include + +namespace marbles { + +using namespace std; + +void Quantizer::Init(const Scale& scale) { + int n = scale.num_degrees; + + // We don't want garbage scale data here... + if (!n || n > kMaxDegrees || scale.base_interval == 0.0f) { + return; + } + + num_degrees_ = n; + base_interval_ = scale.base_interval; + base_interval_reciprocal_ = 1.0f / scale.base_interval; + + uint8_t second_largest_threshold = 0; + for (int i = 0; i < n; ++i) { + voltage_[i] = scale.degree[i].voltage; + if (scale.degree[i].weight != 255 && \ + scale.degree[i].weight >= second_largest_threshold) { + second_largest_threshold = scale.degree[i].weight; + } + } + + uint8_t thresholds_[kNumThresholds] = { + 0, 16, 32, 64, 128, 192, 255 + }; + + if (second_largest_threshold > 192) { + // Be more selective to only include the notes at rank 1 and 2 at + // the last but one position. + thresholds_[kNumThresholds - 2] = second_largest_threshold; + } + + for (int t = 0; t < kNumThresholds; ++t) { + Sp1DegreeMask bitmask = 0; + uint8_t first = 0xff; + uint8_t last = 0; + for (int i = 0; i < n; ++i) { + if (scale.degree[i].weight >= thresholds_[t]) { + bitmask |= Sp1DegreeMask(1) << i; + if (first == 0xff) first = i; + last = i; + } + } + level_[t].bitmask = bitmask; + level_[t].first = first; + level_[t].last = last; + } + + level_quantizer_.Init(); + fill(&feedback_[0], &feedback_[kNumThresholds], 0.0f); +} + +float Quantizer::Process(float value, float amount, bool hysteresis) { + int level = level_quantizer_.Process(amount, kNumThresholds + 1); + float quantized_voltage = value; + + if (level > 0) { + level -= 1; + float raw_value = value; + if (hysteresis) { + value += feedback_[level]; + } + + const float note = value * base_interval_reciprocal_; + MAKE_INTEGRAL_FRACTIONAL(note); + if (value < 0.0f) { + note_integral -= 1; + note_fractional += 1.0f; + } + note_fractional *= base_interval_; + + // Search for the tightest upper/lower bound in the set of available + // voltages. stl::upper_bound / stl::lower_bound wouldn't work here + // because some entries are masked. + Level l = level_[level]; + float a = voltage_[l.last] - base_interval_; + float b = voltage_[l.first] + base_interval_; + + Sp1DegreeMask bitmask = l.bitmask; + for (int i = 0; i < num_degrees_; ++i) { + if (bitmask & 1) { + float v = voltage_[i]; + if (note_fractional > v) { + a = v; + } else { + b = v; + break; + } + } + bitmask >>= 1; + } + + quantized_voltage = note_fractional < (a + b) * 0.5f ? a : b; + quantized_voltage += static_cast(note_integral) * base_interval_; + feedback_[level] = (quantized_voltage - raw_value) * 0.25f; + } + return quantized_voltage; +} + +} // namespace marbles diff --git a/firmware/src/plaits_ovr/marbles/random/quantizer.h b/firmware/src/plaits_ovr/marbles/random/quantizer.h new file mode 100644 index 0000000..fa7ba94 --- /dev/null +++ b/firmware/src/plaits_ovr/marbles/random/quantizer.h @@ -0,0 +1,127 @@ +// Copyright 2015 Emilie Gillet. +// +// Author: Emilie Gillet (emilie.o.gillet@gmail.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// See http://creativecommons.org/licenses/MIT/ for more information. +// +// ----------------------------------------------------------------------------- +// +// Variable resolution quantizer. +// +// wakes-sp1 (#44): a whole-file replacement (firmware/CMakeLists.txt, sp1_plaits_replace). +// Up to 64 degrees instead of 16, so scales.cnfg can hold 31-EDO, 53-EDO and the like: the +// active-degree masks are 64-bit (Sp1DegreeMask). Nothing else differs from upstream. + +#ifndef MARBLES_RANDOM_QUANTIZER_H_ +#define MARBLES_RANDOM_QUANTIZER_H_ + +#include "stmlib/stmlib.h" +#include "stmlib/dsp/hysteresis_quantizer.h" + +#include "marbles/random/distributions.h" +#include "marbles/random/quantizer.h" + +namespace marbles { + +const int kMaxDegrees = 64; // wakes-sp1 (#44): upstream 16 +typedef uint64_t Sp1DegreeMask; // wakes-sp1 (#44): upstream uint16_t +const int kNumThresholds = 7; + +struct Degree { + float voltage; + uint8_t weight; +}; + +struct Scale { + float base_interval; + int num_degrees; + Degree degree[kMaxDegrees]; + + inline float cell_voltage(int i) const { + float transposition = static_cast(i / num_degrees) * base_interval; + return degree[i % num_degrees].voltage + transposition; + } + + void Init() { + base_interval = 1.0f; + num_degrees = 1; + degree[0].voltage = 0.0f; + degree[0].weight = 0.0f; + } + + void InitMajor() { + const uint8_t major_scale_weights[] = { + 255, 16, 128, 16, 192, 64, 8, 224, 16, 96, 32, 160, + }; + + base_interval = 1.0f; + num_degrees = 12; + for (size_t i = 0; i < 12; ++i) { + degree[i].voltage = static_cast(i) * 0.0833333333f; + degree[i].weight = major_scale_weights[i]; + } + } + + void InitTenth() { + const uint8_t major_scale_weights[] = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 25 + }; + + base_interval = 1.0f; + num_degrees = 10; + for (size_t i = 0; i < 10; ++i) { + degree[i].voltage = static_cast(i) * 0.1f; + degree[i].weight = major_scale_weights[i]; + } + } +}; + +class Quantizer { + public: + Quantizer() { } + ~Quantizer() { } + + void Init(const Scale& scale); + + float Process(float value, float amount, bool hysteresis); + + private: + struct Level { + Sp1DegreeMask bitmask; // bitmask of active degrees. + uint8_t first; // index of the first active degree. + uint8_t last; // index of the last active degree. + }; + float voltage_[kMaxDegrees]; + + Level level_[kNumThresholds]; + float feedback_[kNumThresholds]; + + float base_interval_; + float base_interval_reciprocal_; + int num_degrees_; + stmlib::HysteresisQuantizer level_quantizer_; + + DISALLOW_COPY_AND_ASSIGN(Quantizer); +}; + +} // namespace marbles + +#endif // MARBLES_RANDOM_QUANTIZER_H_ diff --git a/firmware/src/sp1_cnfg.c b/firmware/src/sp1_cnfg.c index d9acc0a..09d2e06 100644 --- a/firmware/src/sp1_cnfg.c +++ b/firmware/src/sp1_cnfg.c @@ -7,6 +7,7 @@ #include "sp1_engines_gen.h" #include "sp1_audio_gen.h" +#include #include _Static_assert(SP1_ENGINE_SLOTS == SP1_CNFG_SLOTS, "engines.cnfg has 24 slots"); @@ -61,6 +62,25 @@ void sp1_cnfg_begin(struct sp1_cnfg_parser *p, sp1_cnfg_entry_fn entry, p->ctx = ctx; } +void sp1_cnfg_begin_lines(struct sp1_cnfg_parser *p, sp1_cnfg_line_fn raw, + sp1_cnfg_problem_fn problem, void *ctx) +{ + sp1_cnfg_begin(p, NULL, problem, ctx); + p->raw = raw; +} + +/* An inline comment: ; or # at the start or after whitespace (Python's configparser, which + * checks the ini defaults at build time, reads them the same way). */ +static void cut_comment(char *val) +{ + for (char *c = val; *c != '\0'; c++) { + if ((*c == ';' || *c == '#') && (c == val || space(c[-1]))) { + *c = '\0'; + break; + } + } +} + static void line_done(struct sp1_cnfg_parser *p) { p->line++; @@ -80,7 +100,13 @@ static void line_done(struct sp1_cnfg_parser *p) s += 3; } s = trim(s); - if (*s == '\0' || *s == ';' || *s == '#') { + if (*s == ';' || *s == '#') { + return; + } + if (*s == '\0') { + if (p->raw != NULL) { + p->raw(p->ctx, p->line, p->section, false, s); + } return; } if (*s == '[') { @@ -89,6 +115,9 @@ static void line_done(struct sp1_cnfg_parser *p) p->section[0] = '\0'; p->problem(p->ctx, p->line, s, "a section name needs a closing ]: the " "settings under it are ignored"); + if (p->raw != NULL) { + p->raw(p->ctx, p->line, p->section, true, p->section); + } return; } *end = '\0'; @@ -97,10 +126,21 @@ static void line_done(struct sp1_cnfg_parser *p) p->section[0] = '\0'; p->problem(p->ctx, p->line, name, "is not a section: the settings under it " "are ignored"); + if (p->raw != NULL) { + p->raw(p->ctx, p->line, p->section, true, p->section); + } return; } strcpy(p->section, name); lower_str(p->section); + if (p->raw != NULL) { + p->raw(p->ctx, p->line, p->section, true, p->section); + } + return; + } + if (p->raw != NULL) { + cut_comment(s); + p->raw(p->ctx, p->line, p->section, false, trim(s)); return; } char *eq = strchr(s, '='); @@ -111,14 +151,7 @@ static void line_done(struct sp1_cnfg_parser *p) *eq = '\0'; char *key = trim(s); char *val = eq + 1; - /* An inline comment: ; or # at the start of the value or after whitespace (Python's - * configparser, which checks the defaults at build time, reads them the same way). */ - for (char *c = val; *c != '\0'; c++) { - if ((*c == ';' || *c == '#') && (c == val || space(c[-1]))) { - *c = '\0'; - break; - } - } + cut_comment(val); val = trim(val); if (*key == '\0') { p->problem(p->ctx, p->line, "(nothing before the =)", "a setting needs a name: " @@ -162,6 +195,7 @@ static const struct { { "midi", SP1_LOG_MIDI }, { "usb", SP1_LOG_USB }, { "storage", SP1_LOG_STORAGE }, + { "scales", SP1_LOG_SCALES }, }; #define SEEN_ENABLED 0x80u @@ -434,6 +468,7 @@ static const struct { { "SPEAKER", SP1_LOG_USB }, { "STORE", SP1_LOG_STORAGE }, { "EMMC", SP1_LOG_STORAGE }, { "PRST", SP1_LOG_STORAGE }, { "LOG", SP1_LOG_STORAGE }, + { "SCALES", SP1_LOG_SCALES }, }; uint8_t sp1_log_category(const char *line, size_t n) @@ -1104,3 +1139,471 @@ int sp1_midi_reader_end(struct sp1_midi_reader *r, int *notes) } return r->problems; } + +/* ---------------------------------------------------------------- scales.cnfg (#44) */ + +#if defined(CONFIG_SP1_PLAITS) + +enum { SC_DESC = 0, SC_COUNT, SC_PITCH, SC_DONE }; +#define SC_NONE (-1) /* before the first [slot] */ +#define SC_ASIDE (-2) /* a section that is not a usable slot: skipped */ + +static void sc_report(struct sp1_scales_reader *r, int line, const char *what, const char *why) +{ + r->problems++; + r->problem(r->ctx, line, what, why); +} + +static void sc_problem(void *ctx, int line, const char *what, const char *why) +{ + struct sp1_scales_reader *r = ctx; + if (r->wiki) { + return; /* below [scales_wiki] nothing is read, long lines included */ + } + sc_report(r, line, what, why); +} + +/* "[n]" in r->what. */ +static const char *sc_head(struct sp1_scales_reader *r, int slot) +{ + struct msg m = { r->what, sizeof(r->what), 0u }; + msg_s(&m, "["); + msg_i(&m, slot + 1); + msg_s(&m, "]"); + return r->what; +} + +/* A run of digits, at most 2^31 - 1 (Scala: "at least 2147483647" must be supported). */ +static bool sc_digits(const char *s, size_t n, uint32_t *out) +{ + uint32_t v = 0u; + if (n == 0u) { + return false; + } + for (size_t i = 0u; i < n; i++) { + if (s[i] < '0' || s[i] > '9') { + return false; + } + if (v > (0x7FFFFFFFu - 9u) / 10u) { + return false; + } + v = v * 10u + (uint32_t)(s[i] - '0'); + } + *out = v; + return true; +} + +bool sp1_scl_pitch(const char *s, size_t n, float *volts) +{ + bool dot = false; + for (size_t i = 0u; i < n; i++) { + dot = dot || s[i] == '.'; + } + if (dot) { + /* Cents: [+|-]digits.digits, either side may be empty but not both. */ + size_t i = 0u; + bool neg = false; + if (i < n && (s[i] == '-' || s[i] == '+')) { + neg = s[i] == '-'; + i++; + } + uint32_t ip = 0u, fp = 0u, fd = 1u; + int digits = 0; + bool after = false; + for (; i < n; i++) { + if (s[i] == '.') { + if (after) { + return false; + } + after = true; + continue; + } + if (s[i] < '0' || s[i] > '9') { + return false; + } + digits++; + const uint32_t d = (uint32_t)(s[i] - '0'); + if (!after) { + if (ip > 10000000u) { + return false; /* far past any period */ + } + ip = ip * 10u + d; + } else if (fd < 10000000u) { + fp = fp * 10u + d; /* digits past 1e-7 cents dropped */ + fd *= 10u; + } + } + if (digits == 0) { + return false; + } + const float c = (float)ip + (float)fp / (float)fd; + *volts = (neg ? -c : c) / 1200.0f; + return true; + } + /* A ratio: a/b, or a alone (= a/1). */ + size_t k = 0u; + while (k < n && s[k] != '/') { + k++; + } + uint32_t a, b = 1u; + if (!sc_digits(s, k, &a)) { + return false; + } + if (k < n && !sc_digits(s + k + 1u, n - k - 1u, &b)) { + return false; + } + if (a == 0u || b == 0u) { + return false; /* "meaningless" (Scala) */ + } + *volts = log2f((float)a / (float)b); + return true; +} + +/* ` = value` -> true, with *value set to the text after the =. `key` lowercase. */ +static bool sc_key(const char *text, const char *key, const char **value) +{ + const size_t k = strlen(key); + for (size_t i = 0u; i < k; i++) { + if (lower(text[i]) != key[i]) { + return false; + } + } + const char *s = text + k; + while (space(*s)) { + s++; + } + if (*s != '=') { + return false; + } + s++; + while (space(*s)) { + s++; + } + *value = s; + return true; +} + +/* The section before a new one (or the end of the file): a scale left half-written. A + * section with no scale in it at all is an empty slot, not a problem. */ +static void sc_close(struct sp1_scales_reader *r, int line) +{ + if (r->slot < 0) { + return; + } + struct msg m = { r->why, sizeof(r->why), 0u }; + switch (r->state) { + case SC_COUNT: + msg_s(&m, "has a scale name but no pitch count after it"); + break; + case SC_PITCH: + msg_s(&m, "ends early: its count says "); + msg_i(&m, r->count); + msg_s(&m, " pitches, only "); + msg_i(&m, r->got); + msg_s(&m, " are here"); + break; + default: + return; /* nothing yet, or complete */ + } + sc_report(r, line, sc_head(r, r->slot), r->why); +} + +/* The last pitch is in: check the scale and put it in its slot. */ +static void sc_finish(struct sp1_scales_reader *r) +{ + const int n = r->count; + const float period = r->pitch[n - 1]; + const int before = r->problems; + if (!(period > 0.0f)) { + sc_report(r, r->pl[n - 1], sc_head(r, r->slot), "its last pitch is the period, and " + "it must be above the root (2/1 for an octave)"); + return; + } + /* Rising order, weights and lines along (Scala does not say pitches must be sorted). */ + for (int i = 1; i < n - 1; i++) { + for (int j = i; j > 0 && r->pitch[j] < r->pitch[j - 1]; j--) { + const float t = r->pitch[j]; r->pitch[j] = r->pitch[j - 1]; r->pitch[j - 1] = t; + const uint8_t w = r->pw[j]; r->pw[j] = r->pw[j - 1]; r->pw[j - 1] = w; + const int l = r->pl[j]; r->pl[j] = r->pl[j - 1]; r->pl[j - 1] = l; + } + } + for (int i = 0; i < n - 1; i++) { + if (!(r->pitch[i] > 0.0f)) { + sc_report(r, r->pl[i], sc_head(r, r->slot), "has a pitch at or below the root " + "(every pitch is above 1/1, which is not written)"); + } else if (!(r->pitch[i] < period)) { + sc_report(r, r->pl[i], sc_head(r, r->slot), "has a pitch at or above the period " + "(the last pitch)"); + } else if (i > 0 && r->pitch[i] == r->pitch[i - 1]) { + sc_report(r, r->pl[i], sc_head(r, r->slot), "has the same pitch twice"); + } + } + if (r->problems != before) { + return; + } + struct sp1_scale *s = &r->bank->s[r->slot]; + s->period = period; + s->n = (uint8_t)n; /* the root, plus every pitch but the period */ + s->volts[0] = 0.0f; + s->weight[0] = 255u; + for (int i = 0; i < n - 1; i++) { + s->volts[i + 1] = r->pitch[i]; + s->weight[i + 1] = r->pw[i]; + } + r->filled++; +} + +static void sc_header(struct sp1_scales_reader *r, int line, const char *name) +{ + sc_close(r, line); + r->state = SC_DESC; + r->bang = false; + r->plaits_set = false; + r->by_ear_set = false; + r->got = 0u; + r->head_line = line; + r->slot = SC_ASIDE; + if (name[0] == '\0') { + return; /* the parser reported it */ + } + int v; + /* [scales_wiki]: the scale library. Nothing below it is read (Adara, #44), so its + * examples need no "; " in front; a slot down there is ignored with a note. */ + if (r->wiki) { + if (parse_uint(name, 9999, &v)) { + r->wiki_notes++; + r->problem(r->ctx, line, name, "is below [scales_wiki], which Wakes does not " + "read: move it above [scales_wiki] to use it"); + } + return; + } + if (strcmp(name, "scales_wiki") == 0) { + r->wiki = true; + return; + } + if (!parse_uint(name, 9999, &v) || v < 1) { + sc_report(r, line, name, "is not a scale slot ([1] to [7]): its scale is ignored"); + return; + } + if (v > SP1_SCALE_SLOTS) { + /* Adara (#44): the scales above 7 are dropped, the rest still loads. A note, not + * a problem. */ + r->dropped++; + struct msg m = { r->what, sizeof(r->what), 0u }; + msg_s(&m, "["); + msg_i(&m, v); + msg_s(&m, "]"); + r->problem(r->ctx, line, r->what, "Wakes has 7 scale slots: this scale is dropped " + "(scales.cnfg is overloaded)"); + return; + } + if (r->seen & (1u << (v - 1))) { + sc_report(r, line, sc_head(r, v - 1), "is there twice"); + return; + } + r->seen |= (uint8_t)(1u << (v - 1)); + r->slot = v - 1; + r->at = r->problems; + memset(&r->bank->s[r->slot], 0, sizeof(r->bank->s[r->slot])); + r->bank->s[r->slot].by_ear = 1u; /* Tune By Ear unless the scale says off */ +} + +static void sc_plaits(struct sp1_scales_reader *r, int line, const char *value) +{ + int v; + if (r->plaits_set) { + sc_report(r, line, "plaits", "is set twice for this scale"); + } else if (!parse_uint(value, 255, &v)) { + sc_report(r, line, "plaits", "must be a weight, 0-255"); + } else { + r->bank->s[r->slot].plaits = (uint8_t)v; + } + r->plaits_set = true; +} + +static void sc_by_ear(struct sp1_scales_reader *r, int line, const char *value) +{ + if (r->by_ear_set) { + sc_report(r, line, "tune_by_ear", "is set twice for this scale"); + } else if (same(value, "on") || same(value, "off")) { + r->bank->s[r->slot].by_ear = same(value, "on") ? 1u : 0u; + } else { + sc_report(r, line, "tune_by_ear", "must be on or off"); + } + r->by_ear_set = true; +} + +static void sc_pitch(struct sp1_scales_reader *r, int line, const char *text) +{ + size_t k = 0u; + while (text[k] != '\0' && !space(text[k])) { + k++; + } + float v; + if (!sp1_scl_pitch(text, k, &v)) { + sc_report(r, line, text, "is not a pitch: cents with a \".\" (100.0) or a ratio " + "(3/2)"); + r->got++; /* keep counting: one problem, not N */ + r->state = r->got == r->count ? SC_DONE : SC_PITCH; + return; + } + /* What follows: a weight if it is a whole number, otherwise a comment (Scala ignores + * anything after the pitch). */ + const char *rest = text + k; + while (space(*rest)) { + rest++; + } + int w = 255; + bool digits = rest[0] != '\0'; + for (const char *c = rest; *c != '\0'; c++) { + digits = digits && *c >= '0' && *c <= '9'; + } + if (digits && !parse_uint(rest, 255, &w)) { + sc_report(r, line, text, "has a weight above 255 (weights are 0-255)"); + w = 255; + } + r->pitch[r->got] = v; + r->pw[r->got] = (uint8_t)w; + r->pl[r->got] = line; + r->got++; + if (r->got == r->count) { + r->state = SC_DONE; + if (r->problems == r->at) { /* nothing wrong in THIS scale */ + sc_finish(r); + } + } +} + +static void sc_line(void *ctx, int line, const char *section, bool header, const char *text) +{ + struct sp1_scales_reader *r = ctx; + (void)section; + if (header) { + sc_header(r, line, text); + return; + } + if (text[0] == '!') { /* Scala's comment lines */ + if (r->slot >= 0 && r->state == SC_DESC) { + r->bang = true; + } + return; + } + if (r->slot == SC_ASIDE) { + return; + } + if (r->slot == SC_NONE) { + if (text[0] != '\0' && !r->loose) { + r->loose = true; + sc_report(r, line, text, "is not under a scale slot ([1] to [7])"); + } + return; + } + const char *value; + if (r->state == SC_DESC || r->state == SC_DONE) { + if (sc_key(text, "plaits", &value)) { + sc_plaits(r, line, value); + return; + } + if (sc_key(text, "tune_by_ear", &value)) { + sc_by_ear(r, line, value); + return; + } + } + switch (r->state) { + case SC_DESC: { + /* The description: the first line after the comments -- an EMPTY one too, once a + * pasted .scl has begun (Scala: "if there is no description, there should be an + * empty line"). Blank lines straight after [n] are just spacing. */ + if (text[0] == '\0' && !r->bang) { + return; + } + char *name = r->bank->s[r->slot].name; + size_t n = strlen(text); + if (n > SP1_SCALE_NAME_MAX - 1u) { + n = SP1_SCALE_NAME_MAX - 1u; + while (n > 0u && ((unsigned char)text[n] & 0xC0u) == 0x80u) { + n--; /* never cut a UTF-8 character */ + } + } + memcpy(name, text, n); + name[n] = '\0'; + r->state = SC_COUNT; + return; + } + case SC_COUNT: { + if (text[0] == '\0') { + return; + } + int c; + if (!parse_uint(text, 9999, &c)) { + sc_report(r, line, text, "should be the number of pitches in the scale"); + r->slot = SC_ASIDE; /* the rest of this section is skipped */ + } else if (c < 1) { + sc_report(r, line, text, "pitches: a scale needs at least its period (2/1)"); + r->slot = SC_ASIDE; /* the rest of this section is skipped */ + } else if (c > SP1_SCALE_DEGREES) { + struct msg m = { r->why, sizeof(r->why), 0u }; + msg_s(&m, "pitches: Wakes takes "); + msg_i(&m, SP1_SCALE_DEGREES); + msg_s(&m, " at most, the period included"); + sc_report(r, line, text, r->why); + r->slot = SC_ASIDE; /* the rest of this section is skipped */ + } else { + r->count = (uint8_t)c; + r->got = 0u; + r->state = SC_PITCH; + } + return; + } + case SC_PITCH: + if (text[0] != '\0') { + sc_pitch(r, line, text); + } + return; + default: /* SC_DONE */ + if (text[0] != '\0') { + sc_report(r, line, text, "comes after the scale's last pitch (is the count " + "right?)"); + } + return; + } +} + +void sp1_scales_begin(struct sp1_scales_reader *r, struct sp1_scale_bank *out, + sp1_cnfg_problem_fn problem, void *ctx) +{ + memset(r, 0, sizeof(*r)); + memset(out, 0, sizeof(*out)); + r->bank = out; + r->problem = problem; + r->ctx = ctx; + r->slot = SC_NONE; + sp1_cnfg_begin_lines(&r->p, sc_line, sc_problem, r); +} + +void sp1_scales_feed(struct sp1_scales_reader *r, const char *text, size_t n) +{ + sp1_cnfg_feed(&r->p, text, n); +} + +int sp1_scales_end(struct sp1_scales_reader *r, int *filled, int *dropped) +{ + sp1_cnfg_end(&r->p); + sc_close(r, r->p.line); + if (r->problems == 0 && r->filled == 0) { + sc_report(r, r->p.line, "(the whole file)", "has no scale: Marbles' X needs one " + "to quantize to"); + } + if (r->problems != 0) { + sp1_scales_defaults(r->bank); + } + int n = 0; + for (int i = 0; i < SP1_SCALE_SLOTS; i++) { + n += r->bank->s[i].n != 0u; + } + *filled = n; + *dropped = r->dropped; + return r->problems; +} + +#endif /* CONFIG_SP1_PLAITS */ diff --git a/firmware/src/sp1_cnfg.h b/firmware/src/sp1_cnfg.h index 124f793..fed3b38 100644 --- a/firmware/src/sp1_cnfg.h +++ b/firmware/src/sp1_cnfg.h @@ -39,8 +39,16 @@ typedef void (*sp1_cnfg_problem_fn)(void *ctx, int line, const char *what, const typedef void (*sp1_cnfg_entry_fn)(void *ctx, int line, const char *section, const char *key, const char *value); +/* LINE MODE (scales.cnfg, #44): every line that is not a ; / # comment, as it is -- trimmed, + * an inline comment removed, and BLANK lines included (a Scala description may be empty). + * `header` is true for a [section] line, with `text` = its name; a [section] that cannot be + * read is reported and then delivered as header "" so the reader stops the section before. */ +typedef void (*sp1_cnfg_line_fn)(void *ctx, int line, const char *section, bool header, + const char *text); + struct sp1_cnfg_parser { sp1_cnfg_entry_fn entry; + sp1_cnfg_line_fn raw; /* set: line mode, `entry` unused */ sp1_cnfg_problem_fn problem; void *ctx; char section[SP1_CNFG_NAME_MAX]; @@ -52,6 +60,8 @@ struct sp1_cnfg_parser { void sp1_cnfg_begin(struct sp1_cnfg_parser *p, sp1_cnfg_entry_fn entry, sp1_cnfg_problem_fn problem, void *ctx); +void sp1_cnfg_begin_lines(struct sp1_cnfg_parser *p, sp1_cnfg_line_fn raw, + sp1_cnfg_problem_fn problem, void *ctx); void sp1_cnfg_feed(struct sp1_cnfg_parser *p, const char *text, size_t n); void sp1_cnfg_end(struct sp1_cnfg_parser *p); @@ -63,7 +73,8 @@ void sp1_cnfg_end(struct sp1_cnfg_parser *p); #define SP1_LOG_MIDI 0x04u #define SP1_LOG_USB 0x08u #define SP1_LOG_STORAGE 0x10u -#define SP1_LOG_ALL 0x1Fu +#define SP1_LOG_SCALES 0x20u /* scales.cnfg: what each ON loaded (#44) */ +#define SP1_LOG_ALL 0x3Fu struct sp1_logs_cfg { bool enabled; @@ -89,8 +100,8 @@ void sp1_logs_begin(struct sp1_logs_reader *r, struct sp1_logs_cfg *c, void sp1_logs_feed(struct sp1_logs_reader *r, const char *text, size_t n); int sp1_logs_end(struct sp1_logs_reader *r); -/* The categories as words, for the log: "performance controls midi usb storage" or "none". - * buf of at least 48 bytes. */ +/* The categories as words, for the log: "performance controls midi usb storage scales" or + * "none". buf of at least 48 bytes. */ const char *sp1_logs_describe(uint8_t cats, char *buf, size_t size); /* Which category a log line belongs to, from its tag -- the first word after the @@ -252,4 +263,70 @@ void sp1_midi_reader_feed(struct sp1_midi_reader *r, const char *text, size_t n) /* Problems; `*notes` = defaults that gave up their CC to one of your lines. */ int sp1_midi_reader_end(struct sp1_midi_reader *r, int *notes); +/* ---------------------------------------------------------------- scales.cnfg */ + +#include "sp1_scales.h" + +/* scales.cnfg (#44): a [1]-[7] section per slot, each holding one Scala (.scl) scale + * (config/scales.cnfg explains the format to users; tools/gen_scales.py reads it the same way + * at build time): + * + * [3] + * plaits = 32 Wakes: Plaits plays the degrees of weight >= 32 (default 0, all) + * tune_by_ear = off Wakes: Plaits' root stays C (default on: Tune By Ear, #30) + * ! comment Scala's comment lines + * name the description: the first other line (may be blank after a !) + * 12 how many pitches follow, the period included (1-64) + * 100.0 16 cents (has a "."), or a ratio (3/2, 2); then a WEIGHT 0-255 + * ... (Wakes: missing = 255; any other text after the pitch ignored) + * 2/1 the last pitch is the period + * + * The root is implicit (0 V, weight 255). Pitches may come in any order; each must lie + * strictly between the root and the period, and two may not be equal. + * + * ALL OR NOTHING, like engines.cnfg: any problem in any scale -> the built-in bank, every + * problem named. The one exception (Adara): a slot above [7] is DROPPED with a note that the + * file is overloaded, and the rest still loads. + * + * [scales_wiki] ends the scales (Adara, #44): NOTHING below it is read -- the scale library + * lives there uncommented, between copy markers, ready to paste above it. A [n] found below + * it is a note ("move it above"), never a problem; long lines there are not reported. */ +struct sp1_scales_reader { + struct sp1_cnfg_parser p; + sp1_cnfg_problem_fn problem; + void *ctx; + struct sp1_scale_bank *bank; + float pitch[SP1_SCALE_DEGREES]; /* this scale's pitches as read, in volts */ + uint8_t pw[SP1_SCALE_DEGREES]; /* ...their weights */ + int pl[SP1_SCALE_DEGREES]; /* ...their lines */ + int slot; /* the section's slot 0-6; -1 none yet, -2 set aside */ + int head_line; /* the section's [n] line */ + int at; /* problems before this section: its own start from here */ + uint8_t state; + bool bang; /* a ! line came before the description */ + bool plaits_set; + bool by_ear_set; + uint8_t count; /* pitches the count line promised */ + uint8_t got; + uint8_t seen; /* slots with a section, bit per slot */ + bool loose; /* a line outside any slot has been reported */ + bool wiki; /* below [scales_wiki]: nothing more is read (#44) */ + int wiki_notes; /* slots found below it, reported as notes */ + char what[SP1_CNFG_LINE_MAX + 8]; + char why[112]; + int problems; + int dropped; /* slots above [7] */ + int filled; +}; +void sp1_scales_begin(struct sp1_scales_reader *r, struct sp1_scale_bank *out, + sp1_cnfg_problem_fn problem, void *ctx); +void sp1_scales_feed(struct sp1_scales_reader *r, const char *text, size_t n); +/* The number of problems. *out is the file's bank when there were none, otherwise the built-in + * one. `*filled` = scales in *out, `*dropped` = slots above [7] that were left out. */ +int sp1_scales_end(struct sp1_scales_reader *r, int *filled, int *dropped); + +/* A pitch as Scala writes it -- "100.0" (cents) or "3/2" / "2" (a ratio) -- in volts at + * 1 V/oct. False if it is not one (a negative or zero ratio included). */ +bool sp1_scl_pitch(const char *s, size_t n, float *volts); + #endif /* SP1_CNFG_H */ diff --git a/firmware/src/sp1_marbles.cc b/firmware/src/sp1_marbles.cc index b493f02..46c1682 100644 --- a/firmware/src/sp1_marbles.cc +++ b/firmware/src/sp1_marbles.cc @@ -4,8 +4,9 @@ // Marbles, Emilie Gillet, MIT), vendored in third_party/eurorack/marbles. What this // file does is what marbles/marbles.cc's Process() does for the module, minus every // input: no CV reader, no clock inputs, no self-patching detector, no scale recorder. -// The y-divider ratios below are copied from marbles.cc; the preset scales from -// marbles/settings.cc (sp1_marbles_scales.inc). Attributed in NOTICE. +// The y-divider ratios below are copied from marbles.cc. The scales are the bank's +// (sp1_scales.h, #44): config/scales.cnfg ships Marbles' presets from marbles/settings.cc, +// written as Scala. Attributed in NOTICE. // // Deliberately includes NO Zephyr headers: the DSP layer stays framework-agnostic. @@ -14,6 +15,7 @@ * same reason -- the destination list is UI vocabulary that the DSP glue has to act on. */ #include "sp1_marbles_ui.h" #include "sp1_synth.h" // SP1_SYNTH_BLOCK: one Marbles sample per Plaits block (#32) +#include "sp1_scales.h" // the seven scale slots (#44) #include #include @@ -23,42 +25,6 @@ #include "marbles/random/t_generator.h" #include "marbles/random/x_y_generator.h" -namespace marbles { -#include "sp1_marbles_scales.inc" - -// ---- the seventh scale: Adara's slot (M4a) ---- -// sp1_marbles_scales.inc is verbatim from marbles/settings.cc and stays that way, so -// the free slot lives here. Chromatic, every degree equally likely -- safe and useful -// as it stands, and marked OFF in docs/MARBLES-SETTINGS.md until it is replaced. The -// format: base_interval in volts (1.0 = an octave at 1 V/oct), how many degrees, then -// each degree as { volts above the root, weight 0-255 }. Weight is how often the STEPS -// quantizer picks that degree, NOT a level: 255 = always available, 0 = never. One -// semitone = 1/12 V = 0.0833333f. -const Scale sp1_free_scale = { - 1.0f, - 12, - { - { 0.0000f, 255 }, // C - { 0.0833f, 255 }, // C# - { 0.1667f, 255 }, // D - { 0.2500f, 255 }, // D# - { 0.3333f, 255 }, // E - { 0.4167f, 255 }, // F - { 0.5000f, 255 }, // F# - { 0.5833f, 255 }, // G - { 0.6667f, 255 }, // G# - { 0.7500f, 255 }, // A - { 0.8333f, 255 }, // A# - { 0.9167f, 255 }, // B - } -}; - -const Scale* const sp1_scales[SP1_MARBLES_SCALES] = { - &preset_scales[0], &preset_scales[1], &preset_scales[2], - &preset_scales[3], &preset_scales[4], &preset_scales[5], - &sp1_free_scale, -}; -} namespace { @@ -111,7 +77,11 @@ float frame_ramp[kN]; // scale) only walks the three X channels, so M4 left Y's quantizer holding Marbles' // empty default scale -- invisible only because Y STEPS defaults below its centre, // where Y uses the lag processor and never quantizes. +// +// #44: the scales come from the bank (scales.cnfg), which the ON job can replace, so a slot +// can hold another scale than it did: `loaded_gen` reloads on sp1_scales_gen() too. int loaded_scale = -1; // -1 = nothing loaded yet +uint32_t loaded_gen; // Deferred re-seed (M4d): main records, the audio thread performs. See sp1_marbles.h. volatile uint32_t reseed_val; @@ -121,24 +91,43 @@ uint32_t reseed_seen; // audio thread // ---- the scale Plaits' FREQUENCY quantizes to (MAIN thread only, M4b) ---- // Its own Quantizer instance, so it shares no state with the four the audio thread uses. // -// `scale_level` picks how selective the quantizer is, per scale. marbles::Quantizer takes -// an `amount` that chooses a weight threshold from {0, 16, 32, 64, 128, 192, 255} (level 1 -// .. 7; level 0 is no quantization at all), and a scale's own weights decide which of its -// degrees survive. Level 3 (weight >= 32) is what yields the note set each scale's NAME -// means -- verified against the tables: +// Each scale says which of its degrees Plaits plays: those of weight >= its `plaits` value +// (scales.cnfg, #44). That is what yields the note set each scale's NAME means -- weight +// >= 32 on Marbles' scales: // major 7 C D E F G A B // minor 7 C D Eb F G Ab Bb // pentatonic 5 C D F G A // bhairav 7 and shri 7, both their own seven-degree ragas -// Pelog and the free slot are the exceptions: their degrees are already exactly the scale, -// so they take level 1 (every degree) -- at level 3 pelog would lose two of its seven. -// ⚠️ Level 1 on major/minor/bhairav/shri would admit all twelve degrees, i.e. quantize to -// a chromatic scale and make four of the six scales sound identical. Do not "simplify" -// this to one constant. -const int scale_level[SP1_MARBLES_SCALES] = { 3, 3, 3, 1, 3, 3, 1 }; -const uint8_t scale_threshold[8] = { 0, 0, 16, 32, 64, 128, 192, 255 }; // by level +// and 0 (every degree) on pelog, whose seven degrees ARE the scale. +// ⚠️ Every degree of major/minor/bhairav/shri would be a chromatic scale and make four of +// the six sound identical -- the reason the value is per scale. +// +// The quantizer is loaded with ONLY those degrees and run at its least selective level +// (every degree it holds). Until #44 it held the whole scale and was run at the Marbles +// level whose threshold matched (3 = weight >= 32, 1 = all): the same notes, but the levels +// only offer 0/16/32/64/128/192/255, and a file can now ask for any weight. marbles::Quantizer plaits_quantizer; int plaits_scale = -1; +uint32_t plaits_gen; +marbles::Scale plaits_degrees; // what plaits_quantizer holds + +// A bank scale as Marbles' Scale: the degrees of weight >= `min` (0 = all), weights kept. +// The root is weight 255, so there is always one. +static_assert(SP1_SCALE_DEGREES == marbles::kMaxDegrees, + "the bank and Marbles' quantizer hold the same number of degrees " + "(src/plaits_ovr/marbles/random/quantizer.h)"); +void ToMarbles(const sp1_scale& s, uint8_t min, marbles::Scale* out) { + out->base_interval = s.period; + int n = 0; + for (int i = 0; i < s.n && i < marbles::kMaxDegrees; ++i) { + if (s.weight[i] >= min) { + out->degree[n].voltage = s.volts[i]; + out->degree[n].weight = s.weight[i]; + ++n; + } + } + out->num_degrees = n; +} // ---- main -> audio hand-off (same scheme as sp1_synth) ---- sp1_marbles_params buf[2]; @@ -269,17 +258,24 @@ void InitGenerators() { // Audio thread. Put scale `s` in slot 0 of all four channels if it is not there // already. Quantizer::Init is a table recompute -- no allocation, ~a thousand cycles // for four channels -- and only runs when the selection changes. +// #44: also when the bank changed (a new scales.cnfg at ON). An empty slot -- only between +// an install and main moving the selection off it -- plays the first filled one. void LoadScaleIfNeeded(int s) { - if (s < 0 || s >= SP1_MARBLES_SCALES) { - s = 0; - } - if (s == loaded_scale) { + const uint32_t gen = sp1_scales_gen(); + if (s == loaded_scale && gen == loaded_gen) { return; } + const sp1_scale* sc = sp1_scale_at(s); + if (sc == nullptr) { + sc = sp1_scale_at(sp1_scale_first()); + } + static marbles::Scale m; // 520 B at 64 degrees: off the audio stack + ToMarbles(*sc, 0u, &m); for (int ch = 0; ch < 4; ++ch) { - xy_generator.LoadScale(ch, 0, *marbles::sp1_scales[s]); + xy_generator.LoadScale(ch, 0, m); } loaded_scale = s; + loaded_gen = gen; } } // namespace @@ -707,50 +703,68 @@ extern "C" void sp1_marbles_reseed(uint32_t seed) { reseed_req = reseed_req + 1u; // main thread is the only writer } +// Load the slot's Plaits degrees; false (quantizer off) if the slot is empty. +static bool PlaitsLoad(int s) { + const sp1_scale* sc = sp1_scale_at(s); + plaits_gen = sp1_scales_gen(); + if (sc == nullptr) { + plaits_scale = -1; + return false; + } + ToMarbles(*sc, sc->plaits, &plaits_degrees); + plaits_quantizer.Init(plaits_degrees); + plaits_scale = s; + return true; +} + +// The bank changed since the quantizer was loaded (#44): the same slot, its new contents. +static bool PlaitsCurrent() { + if (plaits_scale < 0) { + return false; + } + return plaits_gen == sp1_scales_gen() || PlaitsLoad(plaits_scale); +} + extern "C" void sp1_marbles_plaits_scale(int s) { if (s < 0 || s >= SP1_MARBLES_SCALES) { plaits_scale = -1; return; } - if (s == plaits_scale) { + if (s == plaits_scale && plaits_gen == sp1_scales_gen()) { return; } - plaits_quantizer.Init(*marbles::sp1_scales[s]); - plaits_scale = s; + (void)PlaitsLoad(s); } extern "C" float sp1_marbles_plaits_quantize(float semitones) { - if (plaits_scale < 0) { + if (!PlaitsCurrent()) { return semitones; } // Marbles' quantizer works in VOLTS at 1 V/octave, Plaits' note is in semitones. // `hysteresis` true, unlike the X/Y channels: this is a fader under a finger, and - // without it a note parked on a boundary flickers between two degrees. - const float amount = - static_cast(scale_level[plaits_scale]) / 7.0f; // -> that level exactly - return plaits_quantizer.Process(semitones * (1.0f / 12.0f), amount, true) * 12.0f; + // without it a note parked on a boundary flickers between two degrees. Amount 1/7 = + // level 1, every degree the quantizer holds (see plaits_quantizer). + return plaits_quantizer.Process(semitones * (1.0f / 12.0f), 1.0f / 7.0f, true) * 12.0f; } extern "C" int sp1_marbles_plaits_degrees(float* semitones, int max) { - if (plaits_scale < 0 || max <= 0) { + if (max <= 0 || !PlaitsCurrent()) { return 0; } - const marbles::Scale& sc = *marbles::sp1_scales[plaits_scale]; - const uint8_t t = scale_threshold[scale_level[plaits_scale]]; int n = 0; - for (int i = 0; i < sc.num_degrees && n < max; ++i) { - if (sc.degree[i].weight >= t) { - semitones[n++] = sc.degree[i].voltage * 12.0f; - } + for (int i = 0; i < plaits_degrees.num_degrees && n < max; ++i) { + semitones[n++] = plaits_degrees.degree[i].voltage * 12.0f; } return n; } +extern "C" float sp1_marbles_plaits_period(void) { + return PlaitsCurrent() ? plaits_degrees.base_interval * 12.0f : 12.0f; +} + extern "C" const char* sp1_marbles_scale_name(int s) { - static const char* const names[SP1_MARBLES_SCALES] = { - "major", "minor", "pentatonic", "pelog", "bhairav", "shri", "free slot", - }; - return (s >= 0 && s < SP1_MARBLES_SCALES) ? names[s] : "?"; + const char* n = sp1_scale_name(s); + return n[0] != '\0' ? n : (sp1_scale_filled(s) ? "(no name)" : "(empty slot)"); } // The generators take the sample rate as a parameter; only the external-clock code diff --git a/firmware/src/sp1_marbles.h b/firmware/src/sp1_marbles.h index 4a7c69d..3ca7675 100644 --- a/firmware/src/sp1_marbles.h +++ b/firmware/src/sp1_marbles.h @@ -41,10 +41,11 @@ extern "C" { /* Marbles samples rendered per audio block: one per Plaits block. */ #define SP1_MARBLES_MAX_FRAMES 20u -/* Selectable scales: Marbles' six presets plus one free slot for a user scale - * (docs/MARBLES-SETTINGS.md). Not Marbles' own limit of six -- only the SELECTED scale - * is loaded into a quantizer, so this number is ours to choose (sp1_marbles.cc). */ -#define SP1_MARBLES_SCALES 7 +/* Selectable scales: the slots of the scale bank (sp1_scales.h, #44: config/scales.cnfg, + * Marbles' six presets by default). Not Marbles' own limit of six -- only the SELECTED + * scale is loaded into a quantizer, so this number is ours to choose (sp1_marbles.cc). */ +#include "sp1_scales.h" +#define SP1_MARBLES_SCALES SP1_SCALE_SLOTS /* X/Y voltage ranges ([J]). The first three are Marbles': 0..2 V, 0..5 V, -5..+5 V. * @@ -210,14 +211,19 @@ const char *sp1_marbles_scale_name(int scale); * ⚠️ There is no "amount" control (Adara): each scale is quantized to the note set its * NAME means. That is not the same as every degree in the table -- Marbles stores major * as twelve weighted degrees, so admitting all of them would quantize to a chromatic - * scale. The per-scale weight threshold that yields the named set is in sp1_marbles.cc - * (`scale_level`), with the resulting note sets written out in - * docs/MARBLES-SETTINGS.md. */ -void sp1_marbles_plaits_scale(int scale); /* load; -1 or out of range = none */ + * scale. Each scale's `plaits` weight (config/scales.cnfg, #44) picks the named set, and + * the note sets are written out in docs/MARBLES-SETTINGS.md. + * + * #44: when the ON job installs a new bank, the loaded slot is reloaded with its new + * contents at the next call; an emptied slot quantizes nothing (main moves the selection + * off it, sp1_pui_scales_settle). */ +void sp1_marbles_plaits_scale(int scale); /* load; -1, out of range, empty = none */ float sp1_marbles_plaits_quantize(float semitones); /* identity if none is loaded */ /* The loaded scale's degrees as semitones above the root, ascending. Returns how many * were written, or 0 if no scale is loaded. For the octave-mode-9 degree sweep. */ int sp1_marbles_plaits_degrees(float *semitones, int max); +/* ...and its period in semitones (12 for an octave; 12 when none is loaded). */ +float sp1_marbles_plaits_period(void); #ifdef __cplusplus } diff --git a/firmware/src/sp1_marbles_scales.inc b/firmware/src/sp1_marbles_scales.inc deleted file mode 100644 index 5bdf475..0000000 --- a/firmware/src/sp1_marbles_scales.inc +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2015 Emilie Gillet. -// -// Author: Emilie Gillet (emilie.o.gillet@gmail.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// -// See http://creativecommons.org/licenses/MIT/ for more information. -// -// ----------------------------------------------------------------------------- -// -// wakes-sp1 (M4): Marbles' six preset scales, copied verbatim from -// marbles/settings.cc (Emilie Gillet, MIT, above) -- the only part of that file -// we use; the rest is the module's flash storage. Included once, by -// sp1_marbles.cc, inside namespace marbles. - -const Scale preset_scales[6] = { - // C major - { - 1.0f, - 12, - { - { 0.0000f, 255 }, // C - { 0.0833f, 16 }, // C# - { 0.1667f, 96 }, // D - { 0.2500f, 24 }, // D# - { 0.3333f, 128 }, // E - { 0.4167f, 64 }, // F - { 0.5000f, 8 }, // F# - { 0.5833f, 192 }, // G - { 0.6667f, 16 }, // G# - { 0.7500f, 96 }, // A - { 0.8333f, 24 }, // A# - { 0.9167f, 128 }, // B - } - }, - - // C minor - { - 1.0f, - 12, - { - { 0.0000f, 255 }, // C - { 0.0833f, 16 }, // C# - { 0.1667f, 96 }, // D - { 0.2500f, 128 }, // Eb - { 0.3333f, 8 }, // E - { 0.4167f, 64 }, // F - { 0.5000f, 4 }, // F# - { 0.5833f, 192 }, // G - { 0.6667f, 96 }, // G# - { 0.7500f, 16 }, // A - { 0.8333f, 128 }, // Bb - { 0.9167f, 16 }, // B - } - }, - - // Pentatonic - { - 1.0f, - 12, - { - { 0.0000f, 255 }, // C - { 0.0833f, 4 }, // C# - { 0.1667f, 96 }, // D - { 0.2500f, 4 }, // Eb - { 0.3333f, 4 }, // E - { 0.4167f, 140 }, // F - { 0.5000f, 4 }, // F# - { 0.5833f, 192 }, // G - { 0.6667f, 4 }, // G# - { 0.7500f, 96 }, // A - { 0.8333f, 4 }, // Bb - { 0.9167f, 4 }, // B - } - }, - - // Pelog - { - 1.0f, - 7, - { - { 0.0000f, 255 }, // C - { 0.1275f, 128 }, // Db+ - { 0.2625f, 32 }, // Eb- - { 0.4600f, 8 }, // F#- - { 0.5883f, 192 }, // G - { 0.7067f, 64 }, // Ab - { 0.8817f, 16 }, // Bb+ - } - }, - - // Raag Bhairav That - { - 1.0f, - 12, - { - { 0.0000f, 255 }, // ** Sa - { 0.0752f, 128 }, // ** Komal Re - { 0.1699f, 4 }, // Re - { 0.2630f, 4 }, // Komal Ga - { 0.3219f, 128 }, // ** Ga - { 0.4150f, 64 }, // ** Ma - { 0.4918f, 4 }, // Tivre Ma - { 0.5850f, 192 }, // ** Pa - { 0.6601f, 64 }, // ** Komal Dha - { 0.7549f, 4 }, // Dha - { 0.8479f, 4 }, // Komal Ni - { 0.9069f, 64 }, // ** Ni - } - }, - - // Raag Shri - { - 1.0f, - 12, - { - { 0.0000f, 255 }, // ** Sa - { 0.0752f, 4 }, // Komal Re - { 0.1699f, 128 }, // ** Re - { 0.2630f, 64 }, // ** Komal Ga - { 0.3219f, 4 }, // Ga - { 0.4150f, 128 }, // ** Ma - { 0.4918f, 4 }, // Tivre Ma - { 0.5850f, 192 }, // ** Pa - { 0.6601f, 4 }, // Komal Dha - { 0.7549f, 64 }, // ** Dha - { 0.8479f, 128 }, // ** Komal Ni - { 0.9069f, 4 }, // Ni - } - }, -}; diff --git a/firmware/src/sp1_marbles_ui.c b/firmware/src/sp1_marbles_ui.c index 4338d6a..01b27d1 100644 --- a/firmware/src/sp1_marbles_ui.c +++ b/firmware/src/sp1_marbles_ui.c @@ -66,26 +66,18 @@ static const uint8_t model_glyph[SP1_MUI_MODELS] = { }; /* ---- the scales ---- - * Marbles ships six (sp1_marbles_scales.inc, from marbles/settings.cc); slot 7 is the - * free one for Adara to fill. Glyphs are those of engine slots 1-7 (SLOT_GLYPHS in - * tools/gen_engines.py), as she asked; a copy. "on" is the inclusion column of - * docs/MARBLES-SETTINGS.md. - * - * ⚠️ This table and that document must agree; the document is the authority and - * explains the degree / weight format so a custom scale can be written. Unlike the - * engine list it is NOT build-generated -- if it grows a third consumer, generate it. */ + * Seven slots, filled from the scale bank (sp1_scales.h, #44): config/scales.cnfg, or the + * drive's copy. A slot the file leaves out is empty and skipped. Glyphs belong to the + * SLOTS (as the engine glyphs do): those of engine slots 1-7 (SLOT_GLYPHS in + * tools/gen_engines.py), as Adara asked; a copy. docs/MARBLES-SETTINGS.md lists them. */ static const uint8_t scale_glyph[SP1_MUI_SCALES] = { - 0x8u, /* ●○○○ 1 major */ - 0xCu, /* ●●○○ 2 minor */ - 0xEu, /* ●●●○ 3 pentatonic */ - 0xFu, /* ●●●● 4 pelog */ - 0x7u, /* ○●●● 5 bhairav */ - 0x3u, /* ○○●● 6 shri */ - 0x1u, /* ○○○● 7 free slot */ -}; -static const bool scale_on[SP1_MUI_SCALES] = { - true, true, true, true, true, true, - false, /* the free slot: chromatic until Adara defines it (M4a) */ + 0x8u, /* ●○○○ 1 (major) */ + 0xCu, /* ●●○○ 2 (minor) */ + 0xEu, /* ●●●○ 3 (pentatonic) */ + 0xFu, /* ●●●● 4 (pelog) */ + 0x7u, /* ○●●● 5 (bhairav) */ + 0x3u, /* ○○●● 6 (shri) */ + 0x1u, /* ○○○● 7 (empty) */ }; /* ---- defaults ---- @@ -268,7 +260,7 @@ static void defaults_pages(struct sp1_mui_patch *p) p->t_range = 1; p->range = DEF_RANGE; p->diversity = 0; - p->scale = 0; /* major */ + p->scale = sp1_scale_first(); /* major, by default */ /* [F] and [G]: Marbles applies DEJA VU to both sections unless you turn one off. */ p->dv_t = 1; p->dv_x = 1; @@ -694,7 +686,16 @@ uint8_t sp1_mui_unpatch_x(int out) bool sp1_mui_scale_included(int s) { - return s >= 0 && s < SP1_MUI_SCALES && scale_on[s]; + return sp1_scale_filled(s); +} + +bool sp1_mui_scales_settle(void) +{ + if (sp1_scale_filled(scale)) { + return false; + } + scale = sp1_scale_first(); + return true; } void sp1_mui_scale_glyph(int s, uint8_t lv[4]) @@ -713,7 +714,7 @@ bool sp1_mui_scale_step(int dir) if (s < 0 || s >= SP1_MUI_SCALES) { return false; /* no wrap, like [B] (Adara) */ } - if (scale_on[s]) { + if (sp1_scale_filled(s)) { scale = s; return true; } diff --git a/firmware/src/sp1_marbles_ui.h b/firmware/src/sp1_marbles_ui.h index 10a30cc..3efeb83 100644 --- a/firmware/src/sp1_marbles_ui.h +++ b/firmware/src/sp1_marbles_ui.h @@ -144,14 +144,18 @@ uint8_t sp1_mui_unpatch_x(int out); /* out = 0..2 X1-X3, 3 = Y int sp1_mui_unpatch_dest(uint8_t dest); /* The scale table, for the PLAITS SETTINGS page's own scale selector (M4b). Plaits keeps - * its OWN index into the same seven scales, so the two modules can disagree. */ + * its OWN index into the same seven scales, so the two modules can disagree. + * #44: INCLUDED = a slot that holds a scale in the bank in use (scales.cnfg); the glyphs + * belong to the slots. */ bool sp1_mui_scale_included(int scale); void sp1_mui_scale_glyph(int scale, uint8_t lv[4]); -#define SP1_MUI_SCALES 7 +#define SP1_MUI_SCALES SP1_SCALE_SLOTS /* "••" + FFWD / RWD on the X page: the next / previous INCLUDED scale, no wrap. - * Returns true if it moved (false at either end). docs/MARBLES-SETTINGS.md owns the - * table -- which scales exist, their glyphs and which are included. */ + * Returns true if it moved (false at either end). */ bool sp1_mui_scale_step(int dir); +/* Main, at ON entry after the ON job (#44): a scale left on a slot the new bank emptied + * moves to the first filled slot. True if it moved. */ +bool sp1_mui_scales_settle(void); /* "••" + PLAY held 3 s on MARBLES: a **FULL WIPE** of the module (Adara, M4d -- * docs/DEFAULTS.md is the spec). * diff --git a/firmware/src/sp1_plaits_ui.c b/firmware/src/sp1_plaits_ui.c index 82ca5b6..3e65ceb 100644 --- a/firmware/src/sp1_plaits_ui.c +++ b/firmware/src/sp1_plaits_ui.c @@ -120,6 +120,10 @@ static int oct_q = 4; /* hysteresis state, octave mode 9 static int deg_q; /* ... and for its degree sweep (M4b) */ static int scale = SP1_PUI_SCALE_OFF; static bool level_was; +/* Tune By Ear (#30): the last note FREQUENCY played with the quantizer off, and the root it + * became when the quantizer went on. Semitones (MIDI note numbers, fractions allowed). */ +static float free_note = 60.0f; +static float by_ear_root; /* The MIDI destination behind each fader of each layer, for pickup shared / takeover * (sp1_midi.h): there the CC moves the stored value itself, as a second hand on the fader. */ @@ -138,6 +142,12 @@ static float clamp01(float x) return x < 0.0f ? 0.0f : (x > 1.0f ? 1.0f : x); } +/* The note nearest `target` that is a root: root + k * period (#44). */ +static float nearest_root(float target, float root, float period) +{ + return root + period * roundf((target - root) / period); +} + /* ---- engines, listed or not (#50) ---- */ static bool offlist(int s) { @@ -488,11 +498,25 @@ void sp1_pui_params(struct sp1_synth_params *p) /* ---- FREQUENCY: Plaits' range modes, plaits/ui.cc ---- * 0 full range, free 60 + 48t (NO detent -- Wakes, issue #18) - * 1..8 one octave, +-7 st 12*oct + 7t (detent: the octave's C) + * 1..8 two octaves 12*oct + 12t (detent: the octave's C) * 9 quantized octaves 53 + 14*fine + 12(q-4) (F1 is a switch: no detent) * 10 full range (dflt) 60 + 48t (detent: C4 = MIDI 60) * where t = 2*F1 - 1. * + * Modes 1-8 were Plaits' +-7 semitones until #44 (Adara): now one PERIOD either side of + * the root, so both ends of F1 are the root an octave down / up -- and with a scale on, + * the root of THAT scale (tuned by ear or C) one of ITS periods down / up, so the ends + * land on roots whatever the scale (a 3/1 tritave included). The centre is the scale's + * root nearest the octave's C. + * + * ---- Tune By Ear (#30, Adara) ---- + * Turning the quantizer ON (off -> a scale, SETTINGS T3) takes the note FREQUENCY was + * playing just before as the scale's ROOT (`by_ear_root`, any pitch, not only a + * semitone): tune F1 by ear, check it with TRIG, then switch the scale on. Every scale + * with `tune_by_ear = on` (scales.cnfg) is then quantized around that root; a scale with + * it off keeps C. Stepping between scales keeps the root; turning the quantizer off and + * on again takes a new one. + * * ⚠️ Mode 0 is NOT Plaits' mode 0 (the LFO range, -48.37 + 60t). Adara removed it in * issue #18: at the bottom of OCTV it was easy to land in by accident and left the * voice at sub-audio rates. In its place is mode 10 with the centre detent off, so F1 @@ -508,14 +532,18 @@ void sp1_pui_params(struct sp1_synth_params *p) const int oct = sp1_pui_octave_mode(); /* The scale, if one is selected (M4b). Fetched once: it also decides what mode 9 * means. `degrees` is empty when no scale is on. */ - float degrees[16]; - const int n_deg = quantize ? sp1_marbles_plaits_degrees(degrees, 16) : 0; + static float degrees[SP1_SCALE_DEGREES]; /* 256 B: off main's stack (main only) */ + const int n_deg = quantize ? sp1_marbles_plaits_degrees(degrees, SP1_SCALE_DEGREES) : 0; /* MIDI's FREQUENCY CC (M5a). Mode 9 makes F1 a switch, so there the CC moves the * position BEFORE it is quantized and steps like the fader does; everywhere else the * audio thread adds it, smoothed, at freq_per_travel semitones per unit of travel. */ const float f1 = (oct == 9) ? clamp01(b[0] + sp1_midi_offset(SP1_MIDI_D_FREQUENCY)) : b[0]; - p->freq_per_travel = oct == 9 ? 0.0f : ((oct == 0 || oct == 10) ? 96.0f : 14.0f); + /* The root and the period the notes are placed around: the scale's (Tune By Ear), or + * C and the octave with no scale. */ + const float period = n_deg > 0 ? sp1_marbles_plaits_period() : 12.0f; + const float root = n_deg > 0 ? sp1_pui_scale_root() : 0.0f; + p->freq_per_travel = oct == 9 ? 0.0f : ((oct == 0 || oct == 10) ? 96.0f : 2.0f * period); float note; if (oct == 9 && n_deg > 0) { /* ---- mode 9 with a scale: sweep SCALE DEGREES across the nine octaves ---- @@ -523,14 +551,17 @@ void sp1_pui_params(struct sp1_synth_params *p) * would be a no-op (an octave is degree 0 of every scale), so the mode * becomes what it should be: F1 steps through every degree of the scale, in * order, across the same nine octaves. Seven degrees gives 63 steps, about - * 59 fader counts each. Same asymmetric hysteresis as the octave version. */ + * 59 fader counts each. Same asymmetric hysteresis as the octave version. + * #44: nine PERIODS -- a scales.cnfg scale may repeat at 3/1, not 2/1. */ const int steps = 9 * n_deg; const float v = f1 * (float)steps - 0.5f; const float h = v > (float)deg_q ? -0.01f : 0.01f; int q = (int)(v + h + 0.5f); q = q < 0 ? 0 : (q > steps - 1 ? steps - 1 : q); deg_q = q; - note = 60.0f + 12.0f * (float)(q / n_deg - 4) + degrees[q % n_deg]; + /* Centred on the scale's root nearest C4 (C4 itself unless tuned by ear). */ + note = nearest_root(60.0f, root, period) + period * (float)(q / n_deg - 4) + + degrees[q % n_deg]; } else if (oct == 9) { /* stmlib HysteresisQuantizer2(9 steps, 0.01, asymmetric) */ const float v = f1 * 9.0f - 0.5f; @@ -544,13 +575,19 @@ void sp1_pui_params(struct sp1_synth_params *p) ? 2.0f * clamp01(b[0]) - 1.0f : 2.0f * detent(b[0], sp1_midi_active() ? DETENT_FREQ_MIDI : DETENT_FREQ) - 1.0f; - note = (oct == 0 || oct == 10) ? 60.0f + t * 48.0f : t * 7.0f + (float)oct * 12.0f; + note = (oct == 0 || oct == 10) + ? 60.0f + t * 48.0f + : nearest_root(12.0f * (float)oct, root, period) + t * period; if (n_deg > 0) { /* Modes 0-8 and 10: the range decides the SPAN, the scale decides - * which notes inside it exist. They compose (Adara). */ - note = sp1_marbles_plaits_quantize(note); + * which notes inside it exist. They compose (Adara). The quantizer's + * root is 0 V = C; Tune By Ear shifts the scale onto `root`. */ + note = sp1_marbles_plaits_quantize(note - root) + root; } } + if (!quantize) { + free_note = note; /* what Tune By Ear takes when the scale goes on */ + } p->note = note; /* ---- and ask the audio thread to HOLD it between TRIGs (M4e, Adara) ---- * Only while a scale is selected. The latch itself is in sp1_synth.cc because that is @@ -624,12 +661,41 @@ int sp1_pui_slot(void) { return slot; } uint8_t sp1_pui_engine_centre(void) { return centre_of(eslot()); } int sp1_pui_scale(void) { return scale; } -void sp1_pui_set_scale(int s) +/* `by_ear`: an off -> on change takes the root from FREQUENCY (Tune By Ear, #30). */ +static void set_scale(int s, bool by_ear) { - scale = (s >= 0 && s < SP1_MARBLES_SCALES) ? s : SP1_PUI_SCALE_OFF; + const int was = scale; + scale = sp1_scale_filled(s) ? s : SP1_PUI_SCALE_OFF; /* an empty slot (#44): off */ + if (by_ear && was == SP1_PUI_SCALE_OFF && scale != SP1_PUI_SCALE_OFF) { + by_ear_root = free_note; + } sp1_marbles_plaits_scale(scale); } +void sp1_pui_set_scale(int s) +{ + set_scale(s, true); +} + +bool sp1_pui_scales_settle(void) +{ + const int was = scale; + set_scale(scale, false); /* reloads the slot's new contents, or turns off */ + return scale != was; +} + +float sp1_pui_scale_root(void) +{ + const struct sp1_scale *s = sp1_scale_at(scale); + return (s != NULL && s->by_ear) ? by_ear_root : 0.0f; +} + +bool sp1_pui_scale_by_ear(void) +{ + const struct sp1_scale *s = sp1_scale_at(scale); + return s != NULL && s->by_ear; +} + void sp1_pui_set_octave_max(void) { /* Mode 10, Plaits' full 96-semitone range -- and the value Plaits itself stores @@ -687,6 +753,7 @@ void sp1_pui_rip_patch(int s, struct sp1_pui_patch *p) p->v[SP1_PUI_SETTINGS][i] = kSettings[i]; } p->scale = SP1_PUI_SCALE_OFF; /* quantizer off */ + p->root = 0.0f; /* Tune By Ear: C */ } void sp1_pui_get(struct sp1_pui_patch *p) @@ -698,6 +765,7 @@ void sp1_pui_get(struct sp1_pui_patch *p) } } p->scale = scale; + p->root = by_ear_root; } void sp1_pui_put(const struct sp1_pui_patch *p) @@ -709,7 +777,10 @@ void sp1_pui_put(const struct sp1_pui_patch *p) stored[l][i] = isfinite(x) ? clamp01(x) : 0.0f; } } - sp1_pui_set_scale(p->scale); /* anything unknown -> off */ + /* Anything unknown -> off. A preset is not a turn-on by ear: it brings its own root + * (PRST format 2, #30; a format-1 preset's is C). */ + by_ear_root = (isfinite(p->root) && p->root >= 0.0f && p->root <= 127.0f) ? p->root : 0.0f; + set_scale(p->scale, false); base_seeded = true; pickup_all(); } diff --git a/firmware/src/sp1_plaits_ui.h b/firmware/src/sp1_plaits_ui.h index 42261ef..17489aa 100644 --- a/firmware/src/sp1_plaits_ui.h +++ b/firmware/src/sp1_plaits_ui.h @@ -150,6 +150,18 @@ int sp1_pui_octave_mode(void); #define SP1_PUI_SCALE_OFF (-1) void sp1_pui_set_scale(int scale); int sp1_pui_scale(void); +/* Main, at ON entry after the ON job (#44): the quantizer reloads its slot from the new + * scale bank, or turns off if that slot is now empty. True if it turned off. */ +bool sp1_pui_scales_settle(void); +/* ---- Tune By Ear (#30, Adara) ---- + * sp1_pui_set_scale() from OFF to a scale takes the note FREQUENCY was playing as the root + * (semitones, MIDI numbering, fractions kept): every scale with `tune_by_ear = on` in + * scales.cnfg is quantized around it until the quantizer is turned off. A scale with it off, + * sits on C. A preset brings its own root (sp1_pui_patch.root, PRST format 2; format 1 = C). + * The root of the scale in use (0 = C, or none): + */ +float sp1_pui_scale_root(void); +bool sp1_pui_scale_by_ear(void); /* the scale in use follows the root */ /* Open the FREQUENCY range fully (mode 10). Called when something is routed to V/Oct. */ void sp1_pui_set_octave_max(void); bool sp1_pui_catching(int fader); /* in the active layer */ @@ -193,6 +205,7 @@ struct sp1_pui_patch { int slot; /* engine: position in config/engines.cnfg */ float v[SP1_PUI_LAYERS][4]; /* stored values, pot space 0..1 */ int scale; /* FREQUENCY quantizer, SP1_PUI_SCALE_OFF */ + float root; /* Tune By Ear's root, semitones (#30) */ }; void sp1_pui_get(struct sp1_pui_patch *p); /* Load a patch: the faders do not move, pickup catches them up (Adara, as after a rip). diff --git a/firmware/src/sp1_prst.c b/firmware/src/sp1_prst.c index 58f7d34..d374b69 100644 --- a/firmware/src/sp1_prst.c +++ b/firmware/src/sp1_prst.c @@ -19,6 +19,7 @@ struct sp1_prst_field { const struct sp1_prst_choice *ch; /* the tokens, for SP1_PRST_K_CHOICE */ uint8_t n_ch; uint16_t off; /* into struct sp1_prst */ + uint8_t since; /* the format that added it (#30) */ }; #include "sp1_prst_gen.h" @@ -123,6 +124,12 @@ int sp1_prst_write(const struct sp1_prst *p, char *buf, size_t size) const int k = (int)(v * 10000.0f + 0.5f); n = snprintf(buf + at, size - at, "%s = %d.%04d\n", f->key, k / 10000, k % 10000); + } else if (f->kind == SP1_PRST_K_NOTE) { + float v = *pos_at(q, f); + v = isfinite(v) ? (v < 0.0f ? 0.0f : (v > 127.0f ? 127.0f : v)) : 0.0f; + const long k = (long)(v * 10000.0f + 0.5f); + n = snprintf(buf + at, size - at, "%s = %ld.%04ld\n", f->key, k / 10000L, + k % 10000L); } else if (f->kind == SP1_PRST_K_ENGINE) { n = snprintf(buf + at, size - at, "%s = %s\n", f->key, sp1_pui_slot_name(*int_at(q, f))); @@ -153,7 +160,7 @@ int sp1_prst_write(const struct sp1_prst *p, char *buf, size_t size) /* A fader value: a plain decimal number in 0..1 -- digits, at most one point, nothing else. * No sign, no exponent, no "nan" or "inf": anything strtof would accept beyond that is a * value no Wakes ever wrote, so it is treated as corrupt rather than guessed at. */ -static bool parse_pos(struct span s, float *out) +static bool parse_num(struct span s, float max, float *out) { int i = 0, idig = 0, fdig = 0; uint32_t ip = 0u, fnum = 0u, fden = 1u; @@ -179,13 +186,18 @@ static bool parse_pos(struct span s, float *out) return false; } const float v = (float)ip + (float)fnum / (float)fden; - if (!(v >= 0.0f && v <= 1.0f)) { + if (!(v >= 0.0f && v <= max)) { return false; } *out = v; return true; } +static bool parse_pos(struct span s, float *out) +{ + return parse_num(s, 1.0f, out); +} + static bool check_ok(uint8_t check, int v) { switch (check) { @@ -282,9 +294,12 @@ void sp1_prst_parse(const char *text, size_t len, struct sp1_prst *out, } } - /* ---- a format this firmware does not know: the whole slot is the defaults ---- */ + /* ---- a format this firmware does not know: the whole slot is the defaults ---- + * An OLDER format is known when the only change since was fields added + * (tools/gen_prst.py, readable_formats): format 1 is read, its slots get the newer + * fields' defaults (#30: the Tune By Ear root on C). */ rep->format = have_fmt ? parse_format(fmt) : -1; - if (rep->format != SP1_PRST_FORMAT) { + if (!(SP1_PRST_READABLE(rep->format))) { sp1_prst_rip(out, -1); rep->defaulted = SP1_PRST_NFIELDS; return; @@ -317,11 +332,20 @@ void sp1_prst_parse(const char *text, size_t len, struct sp1_prst *out, continue; } if (!have[i]) { - rep->defaulted++; + /* A field newer than the file's format is not missing: it did not exist. */ + if (f->since <= rep->format) { + rep->defaulted++; + } continue; } bool ok; - if (f->kind == SP1_PRST_K_POS) { + if (f->kind == SP1_PRST_K_NOTE) { + float v; + ok = parse_num(val[i], 127.0f, &v); + if (ok) { + *pos_at(out, f) = v; + } + } else if (f->kind == SP1_PRST_K_POS) { float v; ok = parse_pos(val[i], &v); if (ok) { diff --git a/firmware/src/sp1_prst.h b/firmware/src/sp1_prst.h index 5176bfc..4b4fde3 100644 --- a/firmware/src/sp1_prst.h +++ b/firmware/src/sp1_prst.h @@ -17,7 +17,7 @@ * Sections and keys from ONE table, tools/gen_prst.py (generated into sp1_prst_gen.h): * * [wakes] - * format = 1 + * format = 2 * [plaits] * engine = virtual analog * timbre = 0.5000 @@ -43,6 +43,14 @@ * that was LOADED (Adara: what a rip on that engine gives). * A format version this firmware does not know, or none at all, loads the WHOLE slot from * defaults: a newer format's keys could mean something else here. + * + * ---- format 2 (#30) and older files ---- + * Format 2 adds `quantizer_root` to [plaits]: Tune By Ear's root, in semitones (MIDI + * numbering, 0..127, four decimals). An OLDER format is read when the only change since was + * fields added -- tools/gen_prst.py checks that from the fingerprints and generates + * SP1_PRST_READABLE -- so a format-1 slot (v0.8.0 - v0.8.2) loads in full, its root on C, and + * the root does not count as defaulted. Firmware older than format 2 loads a format-2 slot + * as defaults (it does not know the version). */ #ifndef SP1_PRST_H #define SP1_PRST_H diff --git a/firmware/src/sp1_scales.c b/firmware/src/sp1_scales.c new file mode 100644 index 0000000..fe873bd --- /dev/null +++ b/firmware/src/sp1_scales.c @@ -0,0 +1,78 @@ +/* wakes-sp1 — the scale bank (#44). See sp1_scales.h. */ +#include "sp1_scales.h" +#include "sp1_scales_gen.h" + +#include + +_Static_assert(SP1_SCALES_GEN_SLOTS == SP1_SCALE_SLOTS, "scales.cnfg has 7 slots"); +_Static_assert(SP1_SCALES_GEN_DEGREES == SP1_SCALE_DEGREES, "64 degrees a scale"); + +static const struct sp1_scale_bank builtin = SP1_SCALES_DEFAULTS; + +/* Zeroed (.bss: no 2 x 2.5 KB initialiser in flash). Until the first install -- the first ON + * job -- every reader gets `builtin` (gen 0). */ +static struct sp1_scale_bank banks[2]; +static int live; +static uint32_t gen; + +static const struct sp1_scale_bank *bank(void) +{ + if (__atomic_load_n(&gen, __ATOMIC_ACQUIRE) == 0u) { + return &builtin; + } + return &banks[__atomic_load_n(&live, __ATOMIC_ACQUIRE) & 1]; +} + +void sp1_scales_defaults(struct sp1_scale_bank *b) +{ + memcpy(b, &builtin, sizeof(*b)); +} + +void sp1_scales_install(const struct sp1_scale_bank *b) +{ + const int next = (__atomic_load_n(&live, __ATOMIC_ACQUIRE) & 1) ^ 1; + bool any = false; + for (int i = 0; i < SP1_SCALE_SLOTS; i++) { + any = any || b->s[i].n != 0u; + } + memcpy(&banks[next], any ? b : &builtin, sizeof(banks[next])); + __atomic_store_n(&live, next, __ATOMIC_RELEASE); + /* Never back to 0, which means "nothing installed yet". */ + uint32_t g = __atomic_load_n(&gen, __ATOMIC_RELAXED) + 1u; + __atomic_store_n(&gen, g != 0u ? g : 1u, __ATOMIC_RELEASE); +} + +uint32_t sp1_scales_gen(void) +{ + return __atomic_load_n(&gen, __ATOMIC_ACQUIRE); +} + +const struct sp1_scale *sp1_scale_at(int slot) +{ + if (slot < 0 || slot >= SP1_SCALE_SLOTS) { + return NULL; + } + const struct sp1_scale *s = &bank()->s[slot]; + return s->n != 0u ? s : NULL; +} + +bool sp1_scale_filled(int slot) +{ + return sp1_scale_at(slot) != NULL; +} + +int sp1_scale_first(void) +{ + for (int i = 0; i < SP1_SCALE_SLOTS; i++) { + if (sp1_scale_filled(i)) { + return i; + } + } + return 0; /* never: install() refuses an empty bank */ +} + +const char *sp1_scale_name(int slot) +{ + const struct sp1_scale *s = sp1_scale_at(slot); + return s != NULL ? s->name : ""; +} diff --git a/firmware/src/sp1_scales.h b/firmware/src/sp1_scales.h new file mode 100644 index 0000000..27e3b01 --- /dev/null +++ b/firmware/src/sp1_scales.h @@ -0,0 +1,71 @@ +/* + * wakes-sp1 — the scale bank (#44): the seven scale slots Marbles' X quantizer and Plaits' + * FREQUENCY quantizer both choose from. + * + * Pure C, no Zephyr: the UI files, sp1_marbles.cc, the storage thread and the host suites + * all read it. + * + * ---- where the scales come from ---- + * config/scales.cnfg (Scala .scl blocks, one per slot) is the BUILT-IN bank: tools/gen_scales.py + * turns it into sp1_scales_gen.h and fails the build on a bad default. The ON job reads + * WAKES/CNFG/scales.cnfg from the drive at every ON (sp1_cnfg.h, sp1_scales_reader) and + * installs the result here BEFORE PRST reads its slots, so a preset's scale is checked + * against the scales in use. A slot the file leaves out is EMPTY: the scale steppers skip it. + * + * ---- threads ---- + * TWO copies, like the engine stack (sp1_plaits_ui.c): the storage thread writes the one not + * in use and flips `live`, once per ON job, so no reader ever sees a scale half-written. + * Every install bumps sp1_scales_gen(): the audio thread (Marbles' four quantizers) and main + * (Plaits' quantizer) compare it and reload, since slot N may now hold another scale. + */ +#ifndef SP1_SCALES_H +#define SP1_SCALES_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define SP1_SCALE_SLOTS 7 /* Adara (#44): more than 7 in the file are dropped */ +#define SP1_SCALE_DEGREES 64 /* marbles::kMaxDegrees, raised from 16 (plaits_ovr) */ +#define SP1_SCALE_NAME_MAX 24 /* the Scala description, cut to fit, for the log */ + +/* One scale, in Marbles' terms (marbles/random/quantizer.h, Scale). */ +struct sp1_scale { + float period; /* volts at 1 V/oct: 1.0 = the octave (2/1) */ + uint8_t n; /* degrees, the root included; 0 = EMPTY slot */ + uint8_t plaits; /* Plaits plays the degrees of weight >= this */ + uint8_t by_ear; /* 1: Plaits' root is Tune By Ear's (#30), 0: C */ + uint8_t weight[SP1_SCALE_DEGREES]; /* 0-255: how selective STEPS must be to drop it */ + float volts[SP1_SCALE_DEGREES]; /* rising, volts[0] = 0 (the root, weight 255) */ + char name[SP1_SCALE_NAME_MAX]; +}; + +struct sp1_scale_bank { + struct sp1_scale s[SP1_SCALE_SLOTS]; +}; + +/* The built-in bank, config/scales.cnfg at build time. */ +void sp1_scales_defaults(struct sp1_scale_bank *b); + +/* Storage thread, once per ON job: the bank in use from now on. A bank with no scale at all is + * replaced by the built-in one (Marbles' X always needs a scale to quantize to). */ +void sp1_scales_install(const struct sp1_scale_bank *b); + +/* Bumped by every install. */ +uint32_t sp1_scales_gen(void); + +/* The scale in a slot, or NULL if the slot is empty or out of range. The pointer is good + * until the next install (the next ON). */ +const struct sp1_scale *sp1_scale_at(int slot); +bool sp1_scale_filled(int slot); +int sp1_scale_first(void); /* the first filled slot */ +const char *sp1_scale_name(int slot); /* "" for an empty slot */ + +#ifdef __cplusplus +} +#endif + +#endif /* SP1_SCALES_H */ diff --git a/firmware/src/sp1_store.c b/firmware/src/sp1_store.c index e7e8dc5..83dc1ed 100644 --- a/firmware/src/sp1_store.c +++ b/firmware/src/sp1_store.c @@ -8,7 +8,7 @@ */ /* Every image writes a config file that is missing from the drive, with its built-in text * (Adara, #52): the text comes with the generated headers, and only when this is defined - * BEFORE the first include of any of them. ~33 KB of flash for the four files. */ + * BEFORE the first include of any of them. ~36 KB of flash for the five files. */ #define SP1_CNFG_TEMPLATES #include "sp1_store.h" #include "sp1_emmc.h" @@ -18,6 +18,7 @@ #include "sp1_engines_gen.h" #if defined(CONFIG_SP1_PLAITS) #include "sp1_audio_gen.h" +#include "sp1_scales_gen.h" #endif #include "sp1_logs_gen.h" #if defined(CONFIG_SP1_STORAGE_TEST) @@ -354,6 +355,7 @@ static int ensure_dir(const char *path) #define ENGINES_CNFG DIR_CNFG "/engines.cnfg" #define AUDIO_CNFG DIR_CNFG "/audio.cnfg" #define MIDI_CNFG DIR_CNFG "/midi.cnfg" +#define SCALES_CNFG DIR_CNFG "/scales.cnfg" /* A config file is a few KB (engines.cnfg ~16, midi.cnfg ~14); never read a huge one. */ #define CNFG_READ_MAX 65536u @@ -365,6 +367,7 @@ static struct sp1_logs_cfg logs_cfg; #define MISSING_ENGINES 0x2u #define MISSING_AUDIO 0x4u #define MISSING_MIDI 0x8u +#define MISSING_SCALES 0x10u static uint8_t cnfg_missing; static void cnfg_problem(void *ctx, int line, const char *what, const char *why) @@ -555,6 +558,96 @@ static void cnfg_load_midi(void) bad, bad == 1 ? "" : "s", bad ? " -- those lines keep their defaults" : "", notes, notes == 1 ? "" : "s"); } + +/* scales.cnfg (#44): ALL OR NOTHING, like engines.cnfg -- except a slot above [7], which is + * dropped with a note (Adara). Staged here; scales_commit installs it ONCE per ON job, before + * PRST checks its slots' scales. Once: sp1_scales.c keeps two copies and writes the one not + * in use, so a single install per job is what keeps a reader off the copy being written. */ +static struct sp1_scale_bank st_scales; +static bool scales_done; + +static void scales_feed(void *r, const char *t, size_t n) +{ + sp1_scales_feed(r, t, n); +} + +static void cnfg_load_scales(void) +{ + static struct sp1_scales_reader rd; /* ~1.2 KB: off the thread's stack */ + sp1_scales_begin(&rd, &st_scales, cnfg_problem, (void *)"scales.cnfg"); + size_t got; + bool rerr; + const int rc = cnfg_read(SCALES_CNFG, scales_feed, &rd, &got, &rerr); + if (rc != 0) { + sp1_scales_defaults(&st_scales); + if (rc == -ENOENT) { + cnfg_missing |= MISSING_SCALES; + } + LINE("CNFG scales.cnfg: %s -- the built-in scales\n", + rc == -ENOENT ? "not on the drive (a copy goes there)" : "cannot be opened"); + return; + } + int filled, dropped; + int bad = sp1_scales_end(&rd, &filled, &dropped); + if (bad == 0 && (rerr || got >= CNFG_READ_MAX)) { + /* Only part of the file was read: part of a bank is not the user's bank. */ + bad = 1; + sp1_scales_defaults(&st_scales); + } + LINE("CNFG scales.cnfg: %u B read%s, %d problem%s -- %s\n", (unsigned)got, + rerr ? " (then a read error)" : (got >= CNFG_READ_MAX ? " (too long)" : ""), + bad, bad == 1 ? "" : "s", + bad ? "the built-in scales instead (the whole file is set aside)" : "your scales"); + if (dropped > 0) { + LINE("CNFG scales.cnfg is OVERLOADED: %d scale%s above [7] dropped (7 slots)\n", + dropped, dropped == 1 ? "" : "s"); + } +} + +/* The bank in use from now on, and -- with logs.cnfg's `scales = on` -- what is in it. */ +static void scales_commit(void) +{ + if (scales_done) { + return; + } + scales_done = true; + sp1_scales_install(&st_scales); + int n = 0; + for (int i = 0; i < SP1_SCALE_SLOTS; i++) { + n += sp1_scale_filled(i); + } + LINE("CNFG scale bank: %d scale%s, starting at slot %d\n", n, n == 1 ? "" : "s", + sp1_scale_first() + 1); + for (int i = 0; i < SP1_SCALE_SLOTS; i++) { + const struct sp1_scale *s = sp1_scale_at(i); + if (s == NULL) { + LINE("SCALES %d: empty\n", i + 1); + continue; + } + int plaits = 0; + for (int k = 0; k < s->n; k++) { + plaits += s->weight[k] >= s->plaits; + } + const int pc = (int)(s->period * 120000.0f + 0.5f); /* cents x 100 */ + LINE("SCALES %d: %s -- %d degree%s, period %d.%02d cents, Plaits plays %d " + "(weight >= %d), tune by ear %s\n", i + 1, s->name, s->n, s->n == 1 ? "" : "s", + pc / 100, pc % 100, plaits, s->plaits, s->by_ear ? "on" : "off"); + /* Every degree as cents/weight, so a file can be checked against what Wakes read; + * 16 to a line (a scale can have 64). */ + static char b[16 * 14 + 1]; + for (int k0 = 0; k0 < s->n; k0 += 16) { + size_t m = 0u; + b[0] = '\0'; + for (int k = k0; k < s->n && k < k0 + 16 && m < sizeof(b); k++) { + const int c = (int)(s->volts[k] * 120000.0f + 0.5f); + m += (size_t)snprintk(b + m, sizeof(b) - m, " %d.%02d/%u", c / 100, + c % 100, (unsigned)s->weight[k]); + } + LINE("SCALES %d degrees %d-%d (cents/weight):%s\n", i + 1, k0 + 1, + k0 + 16 < s->n ? k0 + 16 : s->n, b); + } + } +} #endif /* No volume: the built-in everything, so nothing from an earlier ON's files lingers. */ @@ -567,6 +660,7 @@ static void cnfg_defaults(void) sp1_pui_set_stack(stack); sp1_audio_cfg_defaults(&st_audio); sp1_midi_cfg_defaults(&st_midi); + sp1_scales_defaults(&st_scales); /* staged: scales_commit installs it */ atomic_set(&cnfg_ready, 1); #endif } @@ -587,6 +681,9 @@ static void cnfg_load(void) if (!stop) { cnfg_load_midi(); } + if (!stop) { + cnfg_load_scales(); + } atomic_set(&cnfg_ready, 1); #endif } @@ -635,6 +732,10 @@ static void cnfg_create_missing(void) (void)cnfg_write_one(MIDI_CNFG, "midi.cnfg", SP1_MIDI_TEMPLATE, sizeof(SP1_MIDI_TEMPLATE) - 1u); } + if ((cnfg_missing & MISSING_SCALES) && !stop) { + (void)cnfg_write_one(SCALES_CNFG, "scales.cnfg", SP1_SCALES_TEMPLATE, + sizeof(SP1_SCALES_TEMPLATE) - 1u); + } #endif cnfg_missing = 0u; } @@ -1566,6 +1667,9 @@ static void job_on_enter(void) if (log_live) { log_teardown(); /* never expected: every way out of ON closes the log */ } +#if defined(CONFIG_SP1_PLAITS) + scales_done = false; /* one install of the scale bank per ON job (#44) */ +#endif cnfg_defaults(); /* until (unless) the drive's files say otherwise (#52) */ claim_for_wakes(); struct sp1_emmc_ident id; @@ -1589,6 +1693,7 @@ static void job_on_enter(void) } #if defined(CONFIG_SP1_PLAITS) if (!ok) { + scales_commit(); /* the built-in scales, before main may go on (#44) */ atomic_set(&prst_state, SP1_STORE_PRST_OFF); } #endif @@ -1615,6 +1720,9 @@ static void job_on_enter(void) cnfg_load(); } #if defined(CONFIG_SP1_PLAITS) + /* #44: the scales in use from now on (the file's, or the built-in ones), BEFORE + * PRST checks its slots' scales against them. */ + scales_commit(); /* PRST (#50): all four slots into RAM, before main starts audio. */ if (rc == 0 && !stop) { prst_load_all(); diff --git a/third_party/eurorack/README.md b/third_party/eurorack/README.md index f113b73..c04a4ea 100644 --- a/third_party/eurorack/README.md +++ b/third_party/eurorack/README.md @@ -36,8 +36,8 @@ our own firmware. (`utils/gate_flags.h`, `utils/ring_buffer.h`). Not vendored: `marbles.cc`, `ui.cc`, `settings.cc`, `cv_reader*`, `clock_inputs`, the self-patching detector, `scale_recorder`, `note_filter`, `io_buffer`, `drivers/`. `firmware/src/sp1_marbles.cc` does what `marbles.cc` -does for the generators; the six preset scales are copied from `settings.cc` into -`firmware/src/sp1_marbles_scales.inc`. `ramp_extractor.cc` (the external clock) is compiled +does for the generators; the six preset scales from `settings.cc` are the default bank in +`config/scales.cnfg`, written as Scala (#44). `ramp_extractor.cc` (the external clock) is compiled but never called. **MIDI (M5a):** `stmlib/algorithms/note_stack.h`, from the same stmlib commit — the note diff --git a/tools/gen_logs.py b/tools/gen_logs.py index 2b92499..37405ee 100644 --- a/tools/gen_logs.py +++ b/tools/gen_logs.py @@ -19,9 +19,10 @@ import re import sys -KEYS = ['enabled', 'performance', 'controls', 'midi', 'usb', 'storage'] +KEYS = ['enabled', 'performance', 'controls', 'midi', 'usb', 'storage', 'scales'] CATS = {'performance': 'SP1_LOG_PERFORMANCE', 'controls': 'SP1_LOG_CONTROLS', - 'midi': 'SP1_LOG_MIDI', 'usb': 'SP1_LOG_USB', 'storage': 'SP1_LOG_STORAGE'} + 'midi': 'SP1_LOG_MIDI', 'usb': 'SP1_LOG_USB', 'storage': 'SP1_LOG_STORAGE', + 'scales': 'SP1_LOG_SCALES'} ONOFF = {'on': 1, 'off': 0} LINE_MAX = 160 # SP1_CNFG_LINE_MAX: the device ignores longer lines diff --git a/tools/gen_prst.py b/tools/gen_prst.py index ccd226e..a61ae97 100644 --- a/tools/gen_prst.py +++ b/tools/gen_prst.py @@ -16,8 +16,16 @@ So the field list has a FINGERPRINT (a hash of every key, kind, check and choice token), and FORMATS below records the fingerprint of each released version. The build fails if the current list's fingerprint is not the newest entry. To change the format on purpose: add -the next version with the fingerprint the error prints -- and the release that ships it -must say so and ask users to install wakes-sp1-fresh. +the next version with the fingerprint the error prints. + +---- reading OLDER formats (Adara, #30) ---- +A field ADDED in a later format says so in SINCE. An older format stays READABLE as long as +the fields that existed then still fingerprint to exactly what that format recorded -- i.e. +the change only added fields. Such a file loads every field it has, and the newer fields +take their defaults without counting as "defaulted" (the file could not have had them). +The script works this out itself (readable_formats) and the firmware reads exactly those. +A change that alters an existing key, kind, check or token makes every older format +unreadable again: then the release must ask users to install wakes-sp1-fresh. ⚠️ Never edit an existing FORMATS entry: a version names one exact format forever. @@ -30,6 +38,12 @@ # ---- the format versions: {version: fingerprint}. Append only. ------------------------------ FORMATS = { 1: '83265ab33880809b', + 2: '43e0d960b51854c1', # #30: + plaits.quantizer_root +} + +# ---- fields added after format 1: {(section, key): the format that added it} -------------- +SINCE = { + ('plaits', 'quantizer_root'): 2, } # ---- choices: (token written in the file, C expression of the value) ---------------------- @@ -66,6 +80,7 @@ # (section, key, kind, check, path in struct sp1_prst) # kind engine = an engine NAME (config/engines.cnfg), resolved to its slot # pos = a fader value, 0..1 (pot space, before detents) +# note = a pitch in semitones, MIDI numbering, 0..127, fractions kept (#30) # = one of CHOICES[kind] # check extra validity beyond "is one of the tokens", applied by sp1_prst.c: # scale = a scale that is included (docs/MARBLES-SETTINGS.md); scale_off also -1 @@ -88,6 +103,7 @@ ('plaits', 'lpg_decay', 'pos', '', 'plaits.v[%s][2]' % ST), ('plaits', 'level', 'pos', '', 'plaits.v[%s][3]' % ST), ('plaits', 'quantizer', 'scale_off', 'scale', 'plaits.scale'), + ('plaits', 'quantizer_root', 'note', '', 'plaits.root'), ('plaits', 'output', 'output', '', 'out_mode'), ('plaits', 'burst', 'burst', '', 'burst_div'), ('plaits', 'drive', 'drive', '', 'drive'), @@ -135,7 +151,7 @@ def validate(): if (sec, key) in seen: fail('%s.%s listed twice' % (sec, key)) seen.add((sec, key)) - if kind not in ('engine', 'pos') and kind not in CHOICES: + if kind not in ('engine', 'pos', 'note') and kind not in CHOICES: fail('%s.%s: unknown kind %r' % (sec, key, kind)) if check not in CHECKS: fail('%s.%s: unknown check %r' % (sec, key, check)) @@ -150,11 +166,18 @@ def validate(): fail('choice %s: token %r must be lowercase, without spaces' % (name, a)) -def fingerprint(): +def since(sec, key): + return SINCE.get((sec, key), 1) + + +def fingerprint(version=None): # Everything that decides what a file means. NOT the struct paths: they are where a - # value lands in RAM, which can change without changing a single file. + # value lands in RAM, which can change without changing a single file. With `version`, + # the fields that existed in that format only. parts = [] for sec, key, kind, check, _ in FIELDS: + if version is not None and since(sec, key) > version: + continue parts.append('%s.%s:%s:%s' % (sec, key, kind, check)) for name in sorted(CHOICES): parts.append('%s=%s' % (name, ','.join('%s>%s' % tv for tv in CHOICES[name]))) @@ -175,12 +198,18 @@ def check_version(): return newest, fp +def readable_formats(newest): + # Older formats whose fields are still exactly as they were (see the docstring). + return [v for v in sorted(FORMATS) if v == newest or fingerprint(v) == FORMATS[v]] + + def c_str(s): return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"' def generate(out): version, fp = check_version() + readable = readable_formats(version) L = [] L.append('/* GENERATED by tools/gen_prst.py -- the PRST field table (#50).') L.append(' * Do not edit: edit FIELDS / CHOICES there. Included by sp1_prst.c only. */') @@ -190,8 +219,10 @@ def generate(out): L.append('#define SP1_PRST_FORMAT %d' % version) L.append('#define SP1_PRST_FINGERPRINT "%s"' % fp) L.append('#define SP1_PRST_NFIELDS %d' % len(FIELDS)) + L.append('/* The formats this firmware reads (older ones: only fields were added since). */') + L.append('#define SP1_PRST_READABLE(f) (%s)' % ' || '.join('(f) == %d' % v for v in readable)) L.append('') - L.append('enum { SP1_PRST_K_ENGINE = 0, SP1_PRST_K_POS, SP1_PRST_K_CHOICE };') + L.append('enum { SP1_PRST_K_ENGINE = 0, SP1_PRST_K_POS, SP1_PRST_K_CHOICE, SP1_PRST_K_NOTE };') L.append('enum { %s };' % ', '.join('SP1_PRST_C_%s = %d' % ((c or 'none').upper(), i) for i, c in enumerate(CHECKS))) L.append('') @@ -203,14 +234,15 @@ def generate(out): L.append('') L.append('static const struct sp1_prst_field SP1_PRST_FIELDS[SP1_PRST_NFIELDS] = {') for sec, key, kind, check, path in FIELDS: - if kind in ('engine', 'pos'): + if kind in ('engine', 'pos', 'note'): k, ch, n = 'SP1_PRST_K_' + kind.upper(), 'NULL', '0' else: k = 'SP1_PRST_K_CHOICE' ch = 'sp1_prst_ch_' + kind n = 'sizeof(%s) / sizeof(%s[0])' % (ch, ch) - L.append('\t{ %s, %s, %s, SP1_PRST_C_%s, %s, %s, offsetof(struct sp1_prst, %s) },' - % (c_str(sec), c_str(key), k, (check or 'none').upper(), ch, n, path)) + L.append('\t{ %s, %s, %s, SP1_PRST_C_%s, %s, %s, offsetof(struct sp1_prst, %s), %d },' + % (c_str(sec), c_str(key), k, (check or 'none').upper(), ch, n, path, + since(sec, key))) L.append('};') L.append('') L.append('#endif /* SP1_PRST_GEN_H */') @@ -223,7 +255,8 @@ def generate(out): if old != text: # leave the timestamp alone when nothing changed with open(out, 'w', encoding='utf-8', newline='\n') as f: f.write(text) - print('PRST format %d (%s), %d fields -> %s' % (version, fp, len(FIELDS), out)) + print('PRST format %d (%s), %d fields, reads %s -> %s' + % (version, fp, len(FIELDS), ', '.join(map(str, readable)), out)) def main(argv): diff --git a/tools/gen_scales.py b/tools/gen_scales.py new file mode 100644 index 0000000..ecff69e --- /dev/null +++ b/tools/gen_scales.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""wakes-sp1 -- the built-in scale bank, from config/scales.cnfg (#44). + + gen_scales.py build step (CMake runs this) + +config/scales.cnfg is the DEFAULT bank: the scales Wakes uses when the drive has no +WAKES/CNFG/scales.cnfg, or when the drive's copy has a problem (all or nothing, like +engines.cnfg). End users edit the copy on the drive, which the firmware writes from this same +file when it is missing -- so out.h carries the file's text too (SP1_SCALES_TEMPLATE). + +The format (sp1_cnfg.h has the device's reader, which reads it the same way): + + [3] a slot, 1-7 + plaits = 32 Plaits plays the degrees of weight >= 32 (default 0: all) + tune_by_ear = off Plaits' root stays C (default on: Tune By Ear, #30) + ! comment Scala's comment lines; ; and # are comments too + name the Scala description + 12 pitches that follow, the period included (1-64) + 100.0 16 cents (has a ".") or a ratio (3/2, 2), then a weight 0-255 + ... + 2/1 the last pitch is the period + +The build fails, naming the line, on anything the device would refuse -- and, unlike the +device, on a slot above [7] too: a default is never "overloaded". + +Standard library only. Read as UTF-8 (with or without a BOM). +""" +import math +import os +import re +import struct +import sys + +SLOTS = 7 # SP1_SCALE_SLOTS +DEGREES = 64 # SP1_SCALE_DEGREES = marbles::kMaxDegrees (raised from 16, #44) +NAME_MAX = 24 # SP1_SCALE_NAME_MAX, the NUL included +LINE_MAX = 160 # SP1_CNFG_LINE_MAX: the device ignores longer lines + + +def _fail(path, line, msg): + where = '%s:%d' % (path, line) if line else path + sys.stderr.write('\n%s: error: %s\n\n' + 'The built-in scales are checked at build time. See the comments\n' + 'in config/scales.cnfg.\n' % (where, msg)) + sys.exit(1) + + +fail = _fail + + +def f32(x): + """x rounded to a C float.""" + return struct.unpack(' 0x7FFFFFFF or b > 0x7FFFFFFF: + return None + return math.log2(a / b) + + +def cut_comment(s): + """; or # at the start or after whitespace (sp1_cnfg.c: cut_comment).""" + for i, c in enumerate(s): + if c in ';#' and (i == 0 or s[i - 1].isspace()): + return s[:i] + return s + + +def name_cut(text): + b = text.encode('utf-8') + if len(b) <= NAME_MAX - 1: + return b + n = NAME_MAX - 1 + while n > 0 and (b[n] & 0xC0) == 0x80: + n -= 1 + return b[:n] + + +WIKI = re.compile(r'(?i)\[\s*scales_wiki\s*\]') +COPY_FROM = re.compile(r';\s*v{4,}') # "; vvvv ... copy from the line below" +COPY_TO = re.compile(r';\s*\^{4,}') # "; ^^^^ ... copy down to the line above" + + +def parse(path): + """The bank above [scales_wiki], and a check of every example below it.""" + with open(path, encoding='utf-8-sig') as f: + text = f.read() + if not text.lstrip().startswith(';'): + fail(path, 1, 'the file must start with a comment naming its format ' + '("; Format: scl blocks ...")') + lines = list(enumerate(text.splitlines(), 1)) + wiki = next((i for i, (_, raw) in enumerate(lines) if WIKI.fullmatch(raw.strip())), None) + main = lines if wiki is None else lines[:wiki] + bank = parse_bank(main, path) + if not any(bank): + fail(path, 0, 'the default bank has no scale') + if wiki is not None: + check_examples(lines[wiki + 1:], path) + return bank, text + + +def check_examples(lines, path): + """Every block between a "; vvvv" and a "; ^^^^" line below [scales_wiki] must load as a + scale when pasted under a slot -- the file tells users to do exactly that.""" + start = None + for i, (ln, raw) in enumerate(lines): + s = raw.strip() + if COPY_FROM.match(s): + if start is not None: + fail(path, ln, 'a "copy from" marker before the previous block ended') + start = i + 1 + elif COPY_TO.match(s): + if start is None: + fail(path, ln, 'a "copy to" marker without a "copy from" above it') + block = lines[start:i] + first = block[0][0] if block else ln + bank = parse_bank([(first, '[1]')] + block, path, + 'scale library example at line %d: ' % first) + if bank[0] is None: + fail(path, first, 'the scale library example at line %d is empty' % first) + start = None + if start is not None: + fail(path, lines[start - 1][0], 'a "copy from" marker with no "copy to" below it') + + +def parse_bank(lines, path, label=''): + """(line number, text) pairs -> the seven slots. `label` prefixes every error.""" + def fail(path, line, msg): + _fail(path, line, label + msg) + bank = [None] * SLOTS + slot = None # the section's slot; None before the first + state = None # 'desc', 'count', 'pitch', 'done' + scale = None + bang = False + for ln, raw in lines: + if len(raw.encode('utf-8')) > LINE_MAX: + fail(path, ln, 'line is over %d bytes: the device would ignore it' % LINE_MAX) + s = raw.strip() + if s.startswith(';') or s.startswith('#'): + continue + if s.startswith('['): + if state in ('count', 'pitch'): + fail(path, ln, 'the scale in [%d] ends before its last pitch' % (slot + 1)) + m = re.fullmatch(r'\[\s*(\d+)\s*\]', s) + if not m or not 1 <= int(m.group(1)) <= SLOTS: + fail(path, ln, '%s is not a scale slot ([1] to [%d])' % (s, SLOTS)) + slot = int(m.group(1)) - 1 + if bank[slot] is not None: + fail(path, ln, '[%d] is there twice' % (slot + 1)) + scale = {'name': b'', 'plaits': 0, 'plaits_set': False, 'by_ear': 1, + 'by_ear_set': False, 'count': 0, 'p': [], 'head': ln, 'has': False} + bank[slot] = scale + state = 'desc' + bang = False + continue + s = cut_comment(s).strip() + if s.startswith('!'): + bang = bang or state == 'desc' + continue + if slot is None: + if s: + fail(path, ln, '"%s" is not under a scale slot ([1] to [%d])' % (s, SLOTS)) + continue + m = re.fullmatch(r'(?i)plaits\s*=\s*(.*)', s) + if m and state in ('desc', 'done'): + if scale['plaits_set']: + fail(path, ln, 'plaits is set twice for [%d]' % (slot + 1)) + v = m.group(1).strip() + if not re.fullmatch(r'\d+', v) or int(v) > 255: + fail(path, ln, 'plaits must be a weight, 0-255, not "%s"' % v) + scale['plaits'] = int(v) + scale['plaits_set'] = True + continue + m = re.fullmatch(r'(?i)tune_by_ear\s*=\s*(.*)', s) + if m and state in ('desc', 'done'): + if scale['by_ear_set']: + fail(path, ln, 'tune_by_ear is set twice for [%d]' % (slot + 1)) + v = m.group(1).strip().lower() + if v not in ('on', 'off'): + fail(path, ln, 'tune_by_ear must be on or off, not "%s"' % v) + scale['by_ear'] = 1 if v == 'on' else 0 + scale['by_ear_set'] = True + continue + if state == 'desc': + if not s and not bang: + continue + scale['name'] = name_cut(s) + scale['has'] = True + state = 'count' + elif state == 'count': + if not s: + continue + if not re.fullmatch(r'\d+', s): + fail(path, ln, '"%s" should be the number of pitches in the scale' % s) + c = int(s) + if not 1 <= c <= DEGREES: + fail(path, ln, '%d pitches: Wakes takes 1-%d, the period included' % (c, DEGREES)) + scale['count'] = c + state = 'pitch' + elif state == 'pitch': + if not s: + continue + tok, rest = re.match(r'(\S+)\s*(.*)', s).groups() + v = pitch(tok) + if v is None: + fail(path, ln, '"%s" is not a pitch: cents with a "." or a ratio' % tok) + w = 255 + if re.fullmatch(r'\d+', rest): + w = int(rest) + if w > 255: + fail(path, ln, 'weight %d is above 255' % w) + scale['p'].append((v, w, ln)) + if len(scale['p']) == scale['count']: + state = 'done' + finish(path, slot, scale, fail) + else: # done + if s: + fail(path, ln, '"%s" comes after the last pitch of [%d]' % (s, slot + 1)) + if state in ('count', 'pitch'): + fail(path, 0, 'the scale in [%d] ends before its last pitch' % (slot + 1)) + for i, sc in enumerate(bank): + if sc is not None and not sc['has']: + bank[i] = None # [n] with nothing in it: an empty slot + return bank + + +def finish(path, slot, sc, fail): + period, _, pl = sc['p'][-1] + if not period > 0: + fail(path, pl, 'the period of [%d] must be above the root' % (slot + 1)) + degs = sorted(sc['p'][:-1], key=lambda t: t[0]) + for i, (v, w, ln) in enumerate(degs): + if not v > 0: + fail(path, ln, 'a pitch of [%d] is at or below the root' % (slot + 1)) + if not v < period: + fail(path, ln, 'a pitch of [%d] is at or above the period' % (slot + 1)) + if i and v == degs[i - 1][0]: + fail(path, ln, '[%d] has the same pitch twice' % (slot + 1)) + sc['period'] = period + sc['degs'] = [(0.0, 255)] + [(v, w) for v, w, _ in degs] + + +def c_float(x): + r = '%.9g' % f32(x) + if 'e' not in r and '.' not in r: + r += '.0' + return r + 'f' + + +def c_bytes(b): + out = '' + for c in b: + ch = chr(c) + if ch in '\\"': + out += '\\' + ch + elif 0x20 <= c < 0x7f: + out += ch + else: + out += '\\%03o' % c + return '"%s"' % out + + +def c_string(text): + """The text as C string literals, one per line (gen_logs.py).""" + out = [] + for ln in text.splitlines(keepends=True): + s = '' + for b in ln.encode('utf-8'): + c = chr(b) + if c == '\\': + s += '\\\\' + elif c == '"': + s += '\\"' + elif c == '\n': + s += '\\n' + elif c == '\t': + s += '\\t' + elif 0x20 <= b < 0x7f: + s += c + else: + s += '\\%03o' % b + out.append('\t"%s"' % s) + return '\n'.join(out) if out else '\t""' + + +def header(bank, text): + L = ['/* GENERATED by tools/gen_scales.py from config/scales.cnfg -- do not edit. */', + '#pragma once', + '', + '#define SP1_SCALES_GEN_SLOTS %d' % SLOTS, + '#define SP1_SCALES_GEN_DEGREES %d' % DEGREES, + '', + '/* The built-in bank (struct sp1_scale_bank, sp1_scales.h). */', + '#define SP1_SCALES_DEFAULTS { { \\'] + for i, sc in enumerate(bank): + if sc is None: + L.append('\t{ 0.0f, 0, 0, 0, { 0 }, { 0.0f }, "" }, /* [%d] empty */ \\' % (i + 1)) + continue + ws = ', '.join(str(w) for _, w in sc['degs']) + vs = ', '.join(c_float(v) for v, _ in sc['degs']) + L.append('\t{ %s, %d, %d, %d, \\' % (c_float(sc['period']), len(sc['degs']), + sc['plaits'], sc['by_ear'])) + L.append('\t { %s }, \\' % ws) + L.append('\t { %s }, \\' % vs) + L.append('\t %s }, /* [%d] */ \\' % (c_bytes(sc['name']), i + 1)) + L += ['} }', + '', + '/* config/scales.cnfg as the firmware writes it to WAKES/CNFG/ when it is missing;', + ' * sp1_store.c defines SP1_CNFG_TEMPLATES before including this. */', + '#if defined(SP1_CNFG_TEMPLATES)', + 'static const char SP1_SCALES_TEMPLATE[] =', + c_string(text) + ';', + '#endif', + ''] + return '\n'.join(L) + + +def main(): + if len(sys.argv) != 3: + sys.stderr.write(__doc__) + sys.exit(2) + src, out = sys.argv[1], sys.argv[2] + bank, text = parse(src) + text = header(bank, text.replace('\r\n', '\n')) + try: + with open(out, encoding='utf-8') as f: + if f.read() == text: + return # unchanged: do not force a rebuild + except OSError: + pass + os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True) + with open(out, 'w', encoding='utf-8', newline='\n') as f: + f.write(text) + + +if __name__ == '__main__': + main() diff --git a/tools/host-tests/cnfgtest.c b/tools/host-tests/cnfgtest.c index 2b22452..3f4d41d 100644 --- a/tools/host-tests/cnfgtest.c +++ b/tools/host-tests/cnfgtest.c @@ -4,6 +4,7 @@ #include #include #include +#include #define SP1_CNFG_TEMPLATES #include "sp1_cnfg.h" @@ -11,6 +12,7 @@ #include "sp1_logs_gen.h" #include "sp1_engines_gen.h" #include "sp1_audio_gen.h" +#include "sp1_scales_gen.h" static int fails; #define CHECK(cond, ...) do { if (!(cond)) { printf(" FAIL: "); \ @@ -134,7 +136,7 @@ static void reader(void) char b[48]; CHECK(strcmp(sp1_logs_describe(SP1_LOG_ALL, b, sizeof(b)), - "performance controls midi usb storage") == 0, "describe all: %s", b); + "performance controls midi usb storage scales") == 0, "describe all: %s", b); CHECK(strcmp(sp1_logs_describe(0u, b, sizeof(b)), "none") == 0, "describe none: %s", b); } @@ -157,7 +159,10 @@ static void categories(void) { "[+00:01:02.345] UAC open=1\n", SP1_LOG_USB }, { "[+00:01:02.345] STORE volume ok\n", SP1_LOG_STORAGE }, { "[+00:01:02.345] LOG 60 s: 12 flushes\n", SP1_LOG_STORAGE }, + { "[+00:01:02.345] SCALES 1: major -- 12 degrees\n", SP1_LOG_SCALES }, + { "[+00:01:02.345] SCALE 2: minor\n", SP1_LOG_CONTROLS }, /* the selection */ /* Always written. */ + { "[+00:01:02.345] CNFG scales.cnfg is OVERLOADED: 1 scale\n", 0u }, { "[+00:01:02.345] PWR shutdown suppressed\n", 0u }, { "[+00:01:02.345] BOOT on battery\n", 0u }, { "[+00:01:02.345] CNFG logs.cnfg line 3: x -- y\n", 0u }, @@ -748,6 +753,350 @@ static void midi(void) } } +/* ---------------------------------------------------------------- scales.cnfg (#44) */ + +static struct sp1_scale_bank sbank; +static int s_filled, s_dropped, s_wiki; + +static int read_scales(const char *text, size_t chunk) +{ + struct sp1_scales_reader r; + problems_seen = 0; + last_line = 0; + last_what[0] = '\0'; + sp1_scales_begin(&r, &sbank, problem, NULL); + const size_t n = strlen(text); + if (chunk == 0u) { + chunk = n ? n : 1u; + } + for (size_t i = 0u; i < n; i += chunk) { + sp1_scales_feed(&r, text + i, (i + chunk <= n) ? chunk : n - i); + } + const int bad = sp1_scales_end(&r, &s_filled, &s_dropped); + s_wiki = r.wiki_notes; + /* Problems + the notes (dropped slots, slots below [scales_wiki]) are everything the + * reader reported. */ + CHECK(bad + s_dropped + s_wiki == problems_seen, "scales reader counted %d problems + " + "%d + %d notes, reported %d", bad, s_dropped, s_wiki, problems_seen); + return bad; +} + +/* What a user does with the library (#44): copy the lines between the markers under the + * block titled `title`, and paste them under a [slot] line. Appends "[slot]\n" + those lines + * to t at m; returns the new length, or -1 if the template has no such block. */ +static int copy_block(char *t, int m, size_t size, int slot, const char *title) +{ + const char *p = strstr(SP1_SCALES_TEMPLATE, title); + const char *from = p != NULL ? strstr(p, "copy from the line below") : NULL; + if (from == NULL) { + return -1; + } + from = strchr(from, '\n') + 1; + const char *to = strstr(from, "\n; ^^^^"); + if (to == NULL) { + return -1; + } + return m + snprintf(t + m, size - (size_t)m, "[%d]\n%.*s\n", slot, (int)(to - from), from); +} + +static bool same_scale(const struct sp1_scale *a, const struct sp1_scale *b) +{ + if (a->n != b->n || a->plaits != b->plaits || strcmp(a->name, b->name) != 0 || + fabsf(a->period - b->period) > 1e-6f) { + return false; + } + for (int i = 0; i < a->n; i++) { + if (a->weight[i] != b->weight[i] || fabsf(a->volts[i] - b->volts[i]) > 1e-6f) { + return false; + } + } + return true; +} + +static bool is_defaults(void) +{ + struct sp1_scale_bank d; + sp1_scales_defaults(&d); + for (int i = 0; i < SP1_SCALE_SLOTS; i++) { + if (!same_scale(&sbank.s[i], &d.s[i])) { + return false; + } + } + return true; +} + +static void scales(void) +{ + printf("[7] scales.cnfg\n"); + struct sp1_scale_bank d; + sp1_scales_defaults(&d); + + /* Scala's pitch syntax. */ + static const struct { + const char *s; + bool ok; + float cents; + } P[] = { + { "100.0", true, 100.0f }, { "100.", true, 100.0f }, { ".5", true, 0.5f }, + { "-5.0", true, -5.0f }, { "1200.000", true, 1200.0f }, { "3/2", true, 701.955f }, + { "2", true, 1200.0f }, { "2/1", true, 1200.0f }, { "81/80", true, 21.506f }, + { "0/1", false, 0 }, { "3/0", false, 0 }, { "-3/2", false, 0 }, + { "1.2.3", false, 0 }, { "abc", false, 0 }, { ".", false, 0 }, + { "3/2/1", false, 0 }, { "", false, 0 }, { "99999999999/2", false, 0 }, + }; + for (size_t i = 0u; i < sizeof(P) / sizeof(P[0]); i++) { + float v = -1.0f; + const bool ok = sp1_scl_pitch(P[i].s, strlen(P[i].s), &v); + CHECK(ok == P[i].ok && (!ok || fabsf(v * 1200.0f - P[i].cents) < 0.005f), + "pitch \"%s\": %d, %.4f cents", P[i].s, ok, (double)(v * 1200.0f)); + } + + /* The template the firmware writes when the file is missing reads back as exactly the + * built-in bank, with no problem, whatever chunk size the drive hands over. */ + const size_t chunks[] = { 0u, 1u, 7u, 128u }; + for (size_t k = 0u; k < sizeof(chunks) / sizeof(chunks[0]); k++) { + const int bad = read_scales(SP1_SCALES_TEMPLATE, chunks[k]); + CHECK(bad == 0 && s_dropped == 0, "template, chunk %u: %d problems (line %d: %s)", + (unsigned)chunks[k], bad, last_line, last_what); + CHECK(is_defaults(), "template, chunk %u: not the built-in bank", (unsigned)chunks[k]); + } + /* What the built-in bank is: Marbles' six, whole-tone in slot 7 (Adara), and their + * Plaits note sets. */ + CHECK(s_filled == 7, "built-in: %d scales", s_filled); + CHECK(d.s[6].n == 6u && d.s[6].plaits == 0u && d.s[6].by_ear == 1u && + strcmp(d.s[6].name, "whole-tone") == 0 && + fabsf(d.s[6].volts[3] - 0.5f) < 1e-6f && d.s[6].weight[5] == 255u, + "slot 7: %s, %u degrees", d.s[6].name, d.s[6].n); + static const int plaits_notes[7] = { 7, 7, 5, 7, 7, 7, 6 }; + for (int i = 0; i < 7; i++) { + int n = 0; + for (int k = 0; k < d.s[i].n; k++) { + n += d.s[i].weight[k] >= d.s[i].plaits; + } + CHECK(n == plaits_notes[i], "%s: Plaits plays %d, expected %d", d.s[i].name, n, + plaits_notes[i]); + CHECK(d.s[i].period == 1.0f && d.s[i].weight[0] == 255u && d.s[i].volts[0] == 0.0f, + "%s: root/period", d.s[i].name); + } + /* Within 0.12 cents of Marbles' own 4-decimal tables (marbles/settings.cc). */ + static const float bhairav[12] = { 0.0f, 0.0752f, 0.1699f, 0.2630f, 0.3219f, 0.4150f, + 0.4918f, 0.5850f, 0.6601f, 0.7549f, 0.8479f, 0.9069f }; + for (int k = 0; k < 12; k++) { + CHECK(fabsf(d.s[4].volts[k] - bhairav[k]) * 1200.0f < 0.12f, "bhairav %d: %.5f", k, + (double)d.s[4].volts[k]); + } + + /* A Scale Workshop export pasted as it is, CRLF and a BOM included, unsorted, a ratio + * period of 3/1, no weights. */ + CHECK(read_scales("\xEF\xBB\xBF[2]\r\n! tritave.scl\r\n!\r\nBohlen-Pierce\r\n 3\r\n!\r\n" + " 9/5\r\n 7/5\r\n 3/1\r\n", 1u) == 0 && s_filled == 1 && + sbank.s[0].n == 0u && sbank.s[1].n == 3u && + strcmp(sbank.s[1].name, "Bohlen-Pierce") == 0 && + fabsf(sbank.s[1].period - log2f(3.0f)) < 1e-6f && + fabsf(sbank.s[1].volts[1] - log2f(1.4f)) < 1e-6f && + fabsf(sbank.s[1].volts[2] - log2f(1.8f)) < 1e-6f && + sbank.s[1].weight[1] == 255u && sbank.s[1].weight[2] == 255u && + sbank.s[1].plaits == 0u, "Scale Workshop paste: %d problems (line %d: %s)", + problems_seen, last_line, last_what); + /* An empty description is a blank line once the .scl has begun with a ! line. */ + CHECK(read_scales("[1]\n!\n\n2\n150.0 16\n2/1\n", 0u) == 0 && sbank.s[0].n == 2u && + sbank.s[0].name[0] == '\0' && sbank.s[0].weight[1] == 16u, + "an empty description: %d problems (%s)", problems_seen, last_what); + /* Blank lines straight after [n] are spacing; weights and plaits; text after a pitch. */ + CHECK(read_scales("[3]\n\nplaits = 100\nmine\n3\n700.0 200 ; G\n400.0 an E\n2/1\n" + "plaits = 7\n", 0u) == 1 && is_defaults(), + "plaits twice: the whole file set aside"); + CHECK(read_scales("[3]\n\nplaits = 100\nmine\n3\n700.0 200 ; G\n400.0 an E\n2/1\n", 0u) == 0 && + sbank.s[2].plaits == 100u && sbank.s[2].n == 3u && + sbank.s[2].weight[1] == 255u && sbank.s[2].weight[2] == 200u, + "weights, plaits, comments: %d problems (%s)", problems_seen, last_what); + /* [scales_wiki] (#44): nothing below it is read -- scales, keys, garbage, broken headers + * and long lines alike -- and a slot down there is a note, not a problem. */ + { + static char t[2048]; + int m = snprintf(t, sizeof(t), "[2]\nmine\n2\n350.0\n2/1\n\n[Scales_Wiki]\n" + "plaits = 999\nnot a scale at all\n[oops\n[3]\nbad\n0\n"); + for (int i = 0; i < 200; i++) { /* a 200-byte line */ + t[m++] = 'x'; + } + snprintf(t + m, sizeof(t) - (size_t)m, "\n[1]\nmajor-ish\n1\n2/1\n"); + CHECK(read_scales(t, 5u) == 0 && s_filled == 1 && sbank.s[1].n == 2u && + sbank.s[0].n == 0u && sbank.s[2].n == 0u && s_wiki == 2, + "[scales_wiki]: %d problems, %d scales, %d notes (line %d: %s)", + problems_seen - s_wiki, s_filled, s_wiki, last_line, last_what); + } + /* Problems above [scales_wiki] still count. */ + CHECK(read_scales("[1]\na\n2\nC#\n2/1\n[scales_wiki]\n", 0u) == 1 && is_defaults(), + "a problem above [scales_wiki] was not counted"); + /* The template's library is not read: the built-in bank is exactly slots 1-7. */ + CHECK(strstr(SP1_SCALES_TEMPLATE, "\n[scales_wiki]\n") != NULL, + "the template has no [scales_wiki] line"); + + /* An empty [n] is an empty slot, not a problem. */ + CHECK(read_scales("[5]\n[6]\nx\n1\n2/1\n", 0u) == 0 && s_filled == 1 && sbank.s[5].n == 1u, + "an empty section: %d problems", problems_seen); + + /* Tune By Ear (#30): on unless the scale says off, before or after the pitches. */ + CHECK(read_scales("[1]\na\n1\n2/1\n[2]\ntune_by_ear = OFF\nb\n1\n2/1\n" + "[3]\nc\n1\n2/1\ntune_by_ear = off\n", 0u) == 0 && + sbank.s[0].by_ear == 1u && sbank.s[1].by_ear == 0u && sbank.s[2].by_ear == 0u, + "tune_by_ear: %d problems (%s)", problems_seen, last_what); + CHECK(d.s[0].by_ear == 1u && d.s[2].by_ear == 1u && d.s[3].by_ear == 0u && + d.s[5].by_ear == 0u, "built-in tune_by_ear: modes on, pelog and the raags off"); + + /* 64 pitches (#44, Adara: 31-EDO and beyond): 53-EDO fills 53 degrees; 64 is the most. */ + { + static char t[4096]; + static const int EDO[3] = { 31, 53, 64 }; + for (int e = 0; e < 3; e++) { + const int edo = EDO[e]; + int m = snprintf(t, sizeof(t), "[2]\n%d-EDO\n%d\n", edo, edo); + for (int k = 1; k < edo; k++) { + m += snprintf(t + m, sizeof(t) - (size_t)m, "%.4f\n", + 1200.0 * k / edo); + } + snprintf(t + m, sizeof(t) - (size_t)m, "2/1\n"); + CHECK(read_scales(t, 13u) == 0 && sbank.s[1].n == (uint8_t)edo && + fabsf(sbank.s[1].volts[edo - 1] - (float)(edo - 1) / (float)edo) < 1e-5f, + "%d-EDO: %d problems (%s), %u degrees", edo, problems_seen, last_what, + sbank.s[1].n); + } + } + + /* The seven modes at the end of the template, uncommented and put in a slot each, as + * the file tells users to: each loads, and plaits = 32 gives exactly its 7 notes. */ + { + static const char *const MODE[7] = { "ionian", "dorian", "phrygian", "lydian", + "mixolydian", "aeolian", "locrian" }; + static const int NOTES[7][7] = { + { 0, 2, 4, 5, 7, 9, 11 }, { 0, 2, 3, 5, 7, 9, 10 }, { 0, 1, 3, 5, 7, 8, 10 }, + { 0, 2, 4, 6, 7, 9, 11 }, { 0, 2, 4, 5, 7, 9, 10 }, { 0, 2, 3, 5, 7, 8, 10 }, + { 0, 1, 3, 5, 6, 8, 10 }, + }; + static const char *const TITLE[7] = { "; ---- Ionian", "; ---- Dorian", + "; ---- Phrygian", "; ---- Lydian", + "; ---- Mixolydian", "; ---- Aeolian", + "; ---- Locrian" }; + static char t[8192]; + int m = 0; + int found = 0; + for (int i = 0; i < 7; i++) { + const int k = copy_block(t, m, sizeof(t), i + 1, TITLE[i]); + if (k > 0) { + m = k; + found++; + } + } + CHECK(found == 7, "the template has %d mode blocks, expected 7", found); + CHECK(read_scales(t, 0u) == 0 && s_filled == 7, "the modes: %d problems (line %d: " + "%s)", problems_seen, last_line, last_what); + for (int i = 0; i < 7 && found == 7; i++) { + const struct sp1_scale *s = &sbank.s[i]; + int n = 0; + bool ok = strcmp(s->name, MODE[i]) == 0 && s->n == 12u && s->plaits == 32u && + s->by_ear == 1u; + for (int k = 0; k < s->n; k++) { + if (s->weight[k] >= s->plaits) { + ok = ok && n < 7 && + fabsf(s->volts[k] * 12.0f - (float)NOTES[i][n]) < 1e-4f; + n++; + } + } + CHECK(ok && n == 7, "mode %s: %d notes for Plaits", MODE[i], n); + } + /* Ionian is Marbles' major, weight for weight. */ + bool same_w = true; + for (int k = 0; k < 12; k++) { + same_w = same_w && sbank.s[0].weight[k] == d.s[0].weight[k]; + } + CHECK(same_w, "ionian's weights are not Marbles' major's"); + } + + /* The two 31-EDO blocks at the end of the library, uncommented the same way: the + * chromatic one gives Plaits all 31 notes (plaits = 0), Mothra[6] its six (steps 0 6 12 + * 18 24 30, plaits = 32). */ + { + static const char *const TITLE[2] = { "; ---- 31edo: Chromatic", + "; ---- 31edo: Mothra[6]" }; + static char t[8192]; + int m = 0; + for (int b = 0; b < 2; b++) { + const int k = copy_block(t, m, sizeof(t), b + 1, TITLE[b]); + CHECK(k > 0, "the template has no \"%s\" block", TITLE[b]); + m = k > 0 ? k : m; + } + CHECK(read_scales(t, 0u) == 0 && s_filled == 2, "the 31-EDO blocks: %d problems " + "(line %d: %s)", problems_seen, last_line, last_what); + const struct sp1_scale *c = &sbank.s[0], *mo = &sbank.s[1]; + CHECK(c->n == 31u && c->plaits == 0u, "31edo chromatic: %u degrees, plaits %u", c->n, + c->plaits); + int n = 0; + bool on_grid = mo->n == 31u && mo->plaits == 32u; + for (int k = 0; k < mo->n; k++) { + if (mo->weight[k] >= mo->plaits) { + on_grid = on_grid && k == 6 * n && + fabsf(mo->volts[k] * 31.0f - (float)k) < 1e-3f; + n++; + } + } + CHECK(on_grid && n == 6, "Mothra[6]: Plaits plays %d notes, not steps 0 6 12 18 24 30", + n); + } + + /* Overloaded (Adara): above [7] is dropped with a note, the rest loads. */ + CHECK(read_scales("[1]\na\n1\n2/1\n[8]\nb\n1\n2/1\n[12]\nc\n2\n100.0\n2/1\n", 0u) == 0 && + s_dropped == 2 && s_filled == 1 && sbank.s[0].n == 1u && !is_defaults(), + "overloaded: %d problems, %d dropped", problems_seen, s_dropped); + + /* Every problem sets the WHOLE file aside: the built-in bank. */ + static const char *const BAD[] = { + "[1]\na\n65\n", /* > 64 pitches */ + "[1]\ntune_by_ear = maybe\na\n1\n2/1\n", /* not on / off */ + "[1]\ntune_by_ear = on\ntune_by_ear = off\na\n1\n2/1\n", /* twice */ + "[1]\na\n0\n", /* no period */ + "[1]\na\ntwelve\n100.0\n2/1\n", /* count is not a number */ + "[1]\na\n2\n100.0\n", /* ends early */ + "[1]\na\n2\n100.0\n2/1\n300.0\n", /* after the last pitch */ + "[1]\na\n2\n1300.0\n2/1\n", /* above the period */ + "[1]\na\n2\n1200.0\n2/1\n", /* on the period */ + "[1]\na\n2\n-100.0\n2/1\n", /* below the root */ + "[1]\na\n3\n100.0\n100.0\n2/1\n", /* the same pitch twice */ + "[1]\na\n2\n100.0 256\n2/1\n", /* weight above 255 */ + "[1]\na\n2\nC#\n2/1\n", /* not a pitch */ + "[1]\na\n1\n-1200.0\n", /* period below the root */ + "[1]\nplaits = 300\na\n1\n2/1\n", /* plaits above 255 */ + "[1]\na\n1\n2/1\n[1]\nb\n1\n2/1\n", /* a slot twice */ + "[0]\na\n1\n2/1\n", /* slot 0 */ + "[major]\na\n1\n2/1\n", /* not a slot */ + "a\n1\n2/1\n[1]\nb\n1\n2/1\n", /* before any slot */ + "[1]\n[2]\n", /* no scale at all */ + "", /* nothing */ + "[1\na\n1\n2/1\n", /* a broken header */ + }; + for (size_t i = 0u; i < sizeof(BAD) / sizeof(BAD[0]); i++) { + const int bad = read_scales(BAD[i], 0u); + CHECK(bad >= 1 && is_defaults() && s_filled == 7, "bad file %u: %d problems, %d " + "scales", (unsigned)i, bad, s_filled); + } + + /* The bank itself: an empty one is refused, a slot's contents change with an install, + * and every install moves the generation on. */ + struct sp1_scale_bank b; + memset(&b, 0, sizeof(b)); + const uint32_t g0 = sp1_scales_gen(); + sp1_scales_install(&b); + CHECK(sp1_scales_gen() == g0 + 1u && sp1_scale_filled(0) && sp1_scale_first() == 0 && + strcmp(sp1_scale_name(0), "major") == 0, "an empty bank installs the built-in one"); + CHECK(read_scales("[4]\nmine\n2\n350.0\n2/1\n", 0u) == 0, "a one-scale file"); + sp1_scales_install(&sbank); + CHECK(!sp1_scale_filled(0) && sp1_scale_first() == 3 && sp1_scale_at(3)->n == 2u && + strcmp(sp1_scale_name(3), "mine") == 0 && sp1_scale_name(0)[0] == '\0' && + sp1_scale_at(7) == NULL && sp1_scale_at(-1) == NULL, "installed: slot 4 only"); + sp1_scales_defaults(&b); + sp1_scales_install(&b); + CHECK(sp1_scales_gen() == g0 + 3u && sp1_scale_first() == 0, "back to the built-in bank"); +} + int main(void) { reader(); @@ -756,6 +1105,7 @@ int main(void) engines(); audio(); midi(); + scales(); printf(fails ? "cnfgtest: %d FAILED\n" : "cnfgtest: all passed\n", fails); return fails ? 1 : 0; } diff --git a/tools/host-tests/hostbuild.sh b/tools/host-tests/hostbuild.sh index 53e413c..2b8c0f3 100644 --- a/tools/host-tests/hostbuild.sh +++ b/tools/host-tests/hostbuild.sh @@ -29,6 +29,8 @@ python3 "$ROOT/tools/gen_prst.py" "$GEN/sp1_prst_gen.h" >/dev/null # #52: the logging defaults and logs.cnfg's text, as the firmware build generates them. python3 "$ROOT/tools/gen_logs.py" "$ROOT/config/logs.cnfg" "$GEN/sp1_logs_gen.h" >/dev/null python3 "$ROOT/tools/gen_audio.py" "$ROOT/config/audio.cnfg" "$GEN/sp1_audio_gen.h" >/dev/null +# #44: the built-in scale bank (config/scales.cnfg). +python3 "$ROOT/tools/gen_scales.py" "$ROOT/config/scales.cnfg" "$GEN/sp1_scales_gen.h" >/dev/null # The MIDI script (M5a) as the firmware build generates it -- with ONE change: its `pickup` # forced to `sum`, because miditest.cc checks the offset maths and the other suites were # written against offsets. miditest_pickup.cc runs the shipped script as it is otherwise, once @@ -111,6 +113,7 @@ g++ $CXXFLAGS $INC -c $SRC/sp1_midi.cc -o $OBJ/sp1_midi.o gcc $CFLAGS $INC -c $SRC/sp1_plaits_ui.c -o $OBJ/pui.o gcc $CFLAGS $INC -c $SRC/sp1_marbles_ui.c -o $OBJ/mui.o gcc $CFLAGS $INC -c $SRC/sp1_prst.c -o $OBJ/prst.o +gcc $CFLAGS $INC -c $SRC/sp1_scales.c -o $OBJ/scales.o # Binaries land in the build dir, never in the repo. for t in "$@"; do @@ -129,7 +132,7 @@ for t in "$@"; do "$t" "$SP/uacring.c" -o "$out" ;; *cnfgtest.c) # #52: the config-file reader and the log file's cursor -- pure C, nothing else linked. - gcc $CFLAGS -Wall -Wextra $INC "$t" "$SRC/sp1_cnfg.c" "$SRC/sp1_logring.c" -o "$out" ;; + gcc $CFLAGS -Wall -Wextra $INC "$t" "$SRC/sp1_cnfg.c" "$SRC/sp1_logring.c" "$SRC/sp1_scales.c" -lm -o "$out" ;; *test_usb_rt_parse.c) # feldd's own host test of the packet validator Wakes uses (third_party/feldd). gcc -std=gnu11 -O2 "$t" "$FELDD/src/usb_rt_parse.c" -o "$out" ;; @@ -145,7 +148,7 @@ for t in "$@"; do gcc $CFLAGS $AINC -c $SRC/sp1_plaits_ui.c -o $OBJ/pui_alt.o gcc $CFLAGS $AINC -c $SRC/sp1_marbles_ui.c -o $OBJ/mui_alt.o g++ $CXXFLAGS $AINC "$t" $OBJ/sp1_synth_alt.o $OBJ/sp1_marbles.o $OBJ/sp1_midi_alt.o \ - $OBJ/pui_alt.o $OBJ/mui_alt.o "$LIB" -lm -o "$out" ;; + $OBJ/pui_alt.o $OBJ/mui_alt.o $OBJ/scales.o "$LIB" -lm -o "$out" ;; *miditest_pickup.cc) # The shipped script under pickup shared and takeover (Adara, M5a round 4): one # binary each, miditest_pickup_shared and miditest_pickup_takeover. @@ -160,13 +163,13 @@ for t in "$@"; do gcc $CFLAGS $PINC -c $SRC/sp1_plaits_ui.c -o $OBJ/pui_$m.o gcc $CFLAGS $PINC -c $SRC/sp1_marbles_ui.c -o $OBJ/mui_$m.o g++ $CXXFLAGS $PINC "$t" $OBJ/sp1_synth_$m.o $OBJ/sp1_marbles.o $OBJ/sp1_midi_$m.o \ - $OBJ/pui_$m.o $OBJ/mui_$m.o "$LIB" -lm -o "${out}_$m" + $OBJ/pui_$m.o $OBJ/mui_$m.o $OBJ/scales.o "$LIB" -lm -o "${out}_$m" [ "$m" = takeover ] || echo "${out}_$m" done out=${out}_takeover ;; *.cc) g++ $CXXFLAGS $INC "$t" $OBJ/sp1_synth.o $OBJ/sp1_marbles.o $OBJ/sp1_midi.o \ - $OBJ/pui.o $OBJ/mui.o "$LIB" -lm -o "$out" ;; - *.c) gcc $CFLAGS $INC "$t" $OBJ/pui.o $OBJ/mui.o $OBJ/prst.o $OBJ/sp1_midi.o -lm -o "$out" ;; + $OBJ/pui.o $OBJ/mui.o $OBJ/scales.o "$LIB" -lm -o "$out" ;; + *.c) gcc $CFLAGS $INC "$t" $OBJ/pui.o $OBJ/mui.o $OBJ/prst.o $OBJ/scales.o $OBJ/sp1_midi.o -lm -o "$out" ;; esac echo "$out" done diff --git a/tools/host-tests/prsttest.c b/tools/host-tests/prsttest.c index b516bd7..c8881b9 100644 --- a/tools/host-tests/prsttest.c +++ b/tools/host-tests/prsttest.c @@ -16,6 +16,7 @@ const char *sp1_marbles_model_name(int m) { (void)m; return "?"; } void sp1_marbles_plaits_scale(int s) { (void)s; } float sp1_marbles_plaits_quantize(float st) { return st; } int sp1_marbles_plaits_degrees(float *st, int max) { (void)st; (void)max; return 0; } +float sp1_marbles_plaits_period(void) { return 12.0f; } const char *sp1_marbles_scale_name(int s) { (void)s; return "?"; } static int fails; @@ -47,6 +48,8 @@ static int diff(const struct sp1_prst *a, const struct sp1_prst *b, const char * } } D(a->plaits.scale != b->plaits.scale, "quantizer %d vs %d", a->plaits.scale, b->plaits.scale); + D(fabsf(a->plaits.root - b->plaits.root) > 0.00005f, "quantizer root %.4f vs %.4f", + a->plaits.root, b->plaits.root); D(a->out_mode != b->out_mode, "output %d vs %d", a->out_mode, b->out_mode); D(a->burst_div != b->burst_div, "burst %d vs %d", a->burst_div, b->burst_div); D(a->drive != b->drive, "drive %d vs %d", a->drive, b->drive); @@ -89,6 +92,7 @@ static void unusual(struct sp1_prst *p) p->plaits.v[SP1_PUI_BASE][0] = 1.0f; /* both ends survive */ p->plaits.v[SP1_PUI_BASE][1] = 0.0f; p->plaits.scale = 3; /* pelog */ + p->plaits.root = 61.3712f; /* C#4 +37 cents (#30) */ p->out_mode = SP1_OUT_RING; p->burst_div = 7; p->drive = 4; @@ -119,6 +123,7 @@ static void unusual(struct sp1_prst *p) * its range, every choice one the firmware can hold. */ static bool safe(const struct sp1_prst *p) { + if (!(p->plaits.root >= 0.0f && p->plaits.root <= 127.0f)) { return false; } for (int l = 0; l < SP1_PUI_LAYERS; l++) { for (int i = 0; i < 4; i++) { const float v = p->plaits.v[l][i]; @@ -186,6 +191,29 @@ int main(void) struct sp1_prst a, b, d; struct sp1_prst_report rep; + /* #44: the built-in bank fills all seven scale slots (whole-tone in [7]), so a scale + * token naming an EMPTY slot can only be checked against a bank with a gap. First the + * default bank: `free` (slot 7) is a scale like any other. Then slot 7 is emptied for + * the rest of the run, which is what the "not included" checks below were written for. */ + { + static char t[SP1_PRST_TEXT_MAX]; + struct sp1_prst p; + sp1_prst_rip(&p, -1); + p.marbles.scale = 6; + p.plaits.scale = 6; + for (int k = 0; k < 4; k++) { + p.marbles.dest[k] = SP1_DEST_NONE; /* no V/Oct: the interlock (M4b) */ + } + const int n = sp1_prst_write(&p, t, sizeof(t)); + sp1_prst_parse(t, (size_t)n, &a, &rep); + CHECK(rep.format_ok && rep.bad == 0 && a.marbles.scale == 6 && a.plaits.scale == 6, + "slot 7 (whole-tone) should load from a preset: bad %d", rep.bad); + struct sp1_scale_bank bank; + sp1_scales_defaults(&bank); + memset(&bank.s[6], 0, sizeof(bank.s[6])); + sp1_scales_install(&bank); + } + /* ---------- 1. the defaults: one source, and the rip still gives them ---------- */ printf("1. ROTC defaults\n"); sp1_pui_init(); @@ -276,6 +304,10 @@ int main(void) { "x1", "trig" }, /* TRIG is not on the X ring */ { "y", "banana" }, { "t_range", "x2" }, { "range", "0-10v" }, { "deja_vu_t", "yes" }, { "t_model", "7" }, + /* #30: the Tune By Ear root, 0..127 semitones, a plain decimal */ + { "quantizer_root", "nan" }, { "quantizer_root", "-1.0000" }, + { "quantizer_root", "127.0001" }, { "quantizer_root", "C#4" }, + { "quantizer_root", "1000" }, }; char buf[SP1_PRST_TEXT_MAX + 64]; for (size_t k = 0; k < sizeof(bad) / sizeof(bad[0]); k++) { @@ -328,7 +360,7 @@ int main(void) "quantizer + V/Oct: scale %d, x2 %d, bad %d", a.plaits.scale, a.marbles.dest[1], rep.bad); /* every value missing: all defaults, nothing called bad */ - sp1_prst_parse("[wakes]\nformat = 1\n", 19, &a, &rep); + sp1_prst_parse("[wakes]\nformat = 2\n", 19, &a, &rep); CHECK(rep.format_ok && rep.defaulted == sp1_prst_fields() && rep.bad == 0, "an empty slot: defaulted %d bad %d", rep.defaulted, rep.bad); CHECK(diff(&a, &d, "empty") == 0, "an empty slot is not the ROTC default"); @@ -336,7 +368,7 @@ int main(void) /* ---------- 4. the format version ---------- */ printf("4. format version\n"); static const char *const fmts[] = { - NULL, "2", "0", "1x", "", "01x", " ", "999999999", "-1", + NULL, "3", "0", "1x", "", "01x", " ", "999999999", "-1", }; for (size_t k = 0; k < sizeof(fmts) / sizeof(fmts[0]); k++) { m = with(text, "format", fmts[k], buf, sizeof(buf)); @@ -351,10 +383,36 @@ int main(void) strcat(buf, "[plaits]\nformat = 1\n"); sp1_prst_parse(buf, strlen(buf), &a, &rep); CHECK(!rep.format_ok, "a format line outside [wakes] counted"); - /* "01" is a decimal 1: accepted */ - m = with(text, "format", "01", buf, sizeof(buf)); + /* "02" is a decimal 2: accepted */ + m = with(text, "format", "02", buf, sizeof(buf)); sp1_prst_parse(buf, (size_t)m, &a, &rep); - CHECK(rep.format_ok && rep.defaulted == 0, "format 01 rejected"); + CHECK(rep.format_ok && rep.defaulted == 0, "format 02 rejected"); + + /* ---- format 1 (v0.8.0 - v0.8.2): read, with the Tune By Ear root on C (#30) ---- + * A format-1 file is this patch without quantizer_root and with format = 1. Nothing in + * it counts as defaulted: the root did not exist in that format. */ + CHECK(sp1_prst_format() == 2, "this firmware writes format %d", sp1_prst_format()); + m = with(text, "quantizer_root", NULL, buf, sizeof(buf)); + { + static char v1[SP1_PRST_TEXT_MAX + 64]; + const int m1 = with(buf, "format", "1", v1, sizeof(v1)); + sp1_prst_parse(v1, (size_t)m1, &a, &rep); + struct sp1_prst want = b; + want.plaits.root = 0.0f; + CHECK(rep.format_ok && rep.format == 1 && rep.defaulted == 0 && rep.bad == 0, + "format 1: format_ok %d defaulted %d bad %d", rep.format_ok, rep.defaulted, + rep.bad); + CHECK(diff(&a, &want, "format 1") == 0, "format 1: not the patch with the root on C"); + /* a format-1 file that somehow has the key: it is read (only fields were added) */ + const int m2 = with(text, "format", "1", v1, sizeof(v1)); + sp1_prst_parse(v1, (size_t)m2, &a, &rep); + CHECK(rep.format_ok && a.plaits.root == b.plaits.root, "format 1 + a root: %.4f", + a.plaits.root); + /* the same file as format 2 has lost a field: that one IS defaulted */ + sp1_prst_parse(buf, (size_t)m, &a, &rep); + CHECK(rep.format_ok && rep.defaulted == 1 && a.plaits.root == 0.0f, + "format 2 without its root: defaulted %d", rep.defaulted); + } /* ---------- 5. the text as people edit it ---------- */ printf("5. hand-edited text\n"); diff --git a/tools/host-tests/routetest.cc b/tools/host-tests/routetest.cc index 1086e0c..71658d8 100644 --- a/tools/host-tests/routetest.cc +++ b/tools/host-tests/routetest.cc @@ -24,6 +24,94 @@ static int fails; static const uint32_t kFrames = 240; // one DMA block +// ---- section 13 (#44, #30): drive F1 like a hand, read the note Plaits gets ---- +static uint16_t f1_pos = 1850; + +static void move_f1(uint16_t to, int settle_ticks = 40) { + const uint16_t mid[4] = { 1850, 1850, 1850, 1850 }; + uint16_t f[4]; + memcpy(f, mid, sizeof(f)); + while (f1_pos != to) { // small steps: pickup follows MOVEMENT + const int d = static_cast(to) - static_cast(f1_pos); + f1_pos = static_cast(f1_pos + (d > 8 ? 8 : (d < -8 ? -8 : d))); + f[0] = f1_pos; + sp1_pui_tick(8u, f, true, false, false); + } + f[0] = f1_pos; + for (int t = 0; t < settle_ticks; ++t) { sp1_pui_tick(8u, f, true, false, false); } +} + +static float note_now() { + sp1_synth_params p; + sp1_pui_params(&p); + return p.note; +} + +// OCTV to `mode` through a patch (the SETTINGS fader is not under test), quantizer off. +static void put_mode(int mode) { + sp1_pui_patch p; + sp1_pui_get(&p); + p.v[SP1_PUI_SETTINGS][0] = (mode + 0.5f) / 11.0f; + p.v[SP1_PUI_BASE][0] = f1_pos / 3701.0f; + p.scale = SP1_PUI_SCALE_OFF; + sp1_pui_put(&p); + move_f1(f1_pos); +} + +// A scale on C, whatever FREQUENCY plays: the preset path (Tune By Ear only acts on a turn-on +// from the SETTINGS page, #30). For the checks written against C-rooted note sets. +static void scale_on_c(int sc) { + sp1_pui_patch p; + sp1_pui_get(&p); + p.scale = sc; + p.root = 0.0f; // a preset saved on C (PRST format 2, #30) + sp1_pui_put(&p); +} + +struct Sweep { + float lo, hi; + float cls[80]; // pitch classes above the root, within one period + int cnt; +}; + +// F1 from bottom to top: the note range, and the distinct classes relative to `root`. +static void sweep(Sweep* s, float root, float period) { + move_f1(0); + s->lo = 1e9f; + s->hi = -1e9f; + s->cnt = 0; + for (int k = 0; k <= 3701; k += 2) { + move_f1(static_cast(k), k == 3701 ? 40 : 3); + const float n = note_now(); + s->lo = n < s->lo ? n : s->lo; + s->hi = n > s->hi ? n : s->hi; + float c = fmodf(n - root, period); + if (c < 0.0f) { c += period; } + if (period - c < 0.02f) { c = 0.0f; } + bool seen = false; + for (int i = 0; i < s->cnt; ++i) { + if (fabsf(s->cls[i] - c) < 0.02f) { seen = true; break; } + } + if (!seen && s->cnt < 80) { s->cls[s->cnt++] = c; } + } + move_f1(3701); + const float n = note_now(); + s->hi = n > s->hi ? n : s->hi; +} + +// Exactly these classes (any order), to 0.02 of a semitone. +static bool same_classes(const Sweep& s, const float* want, int n) { + if (s.cnt != n) { return false; } + for (int i = 0; i < n; ++i) { + bool found = false; + for (int j = 0; j < s.cnt; ++j) { + if (fabsf(s.cls[j] - want[i]) < 0.02f) { found = true; break; } + } + if (!found) { return false; } + } + return true; +} + static void base_params(sp1_synth_params* p) { memset(p, 0, sizeof(*p)); p->note = 48.0f; @@ -232,7 +320,7 @@ int main() { // and collect the pitch classes that come out. for (int sc = -1; sc < SP1_MUI_SCALES; ++sc) { if (sc >= 0 && !sp1_mui_scale_included(sc)) { continue; } - sp1_pui_set_scale(sc); + scale_on_c(sc); // on C: these are the C-rooted note sets // Distinct pitch classes, to 0.05 of a semitone -- NOT rounded to integers: // pelog, bhairav and shri are microtonal and never land on the semitone grid. float cls[32]; @@ -293,7 +381,7 @@ int main() { } // ---- octave mode 9 + a scale = a sweep of scale DEGREES over nine octaves ---- - sp1_pui_set_scale(0); // major, 7 degrees -> 63 steps + scale_on_c(0); // major on C, 7 degrees -> 63 steps memcpy(f, mid, sizeof(f)); f[0] = 0; // SETTINGS F1 to mode 9: 9/11 of travel @@ -919,6 +1007,140 @@ int main() { sp1_marbles_run(false); } + // ---------- 13. OCTV's two octaves, Tune By Ear, big scales (#44, #30) ---------- + printf("13. OCTV two-octave lock, Tune By Ear, 64-degree scales\n"); + { + const uint16_t mid[4] = { 1850, 1850, 1850, 1850 }; + sp1_pui_init(); + sp1_pui_enter(mid); + f1_pos = 1850; + struct Sweep s; + + // Modes 1-8: one octave either side of the octave's C, no scale (Adara, #44). + put_mode(4); + CHECK(sp1_pui_octave_mode() == 4, "OCTV is mode %d, not 4", sp1_pui_octave_mode()); + sweep(&s, 0.0f, 12.0f); + printf(" mode 4, no scale: MIDI %.2f .. %.2f\n", s.lo, s.hi); + CHECK(fabsf(s.lo - 36.0f) < 0.05f && fabsf(s.hi - 60.0f) < 0.05f, + "mode 4 should run C2..C4 (36..60), got %.2f..%.2f", s.lo, s.hi); + + // Tune By Ear: park F1, turn the quantizer on -> that note is the root. + move_f1(1110); // F1 0.3 -> 48 - 0.4 * 12 = 43.2 + const float tuned = note_now(); + sp1_pui_set_scale(0); // major: tune_by_ear on + printf(" tuned by ear at %.3f, root %.3f\n", tuned, sp1_pui_scale_root()); + // (Not 43.2 exactly: FREQUENCY's 5 % centre detent stretches the rest of the travel.) + CHECK(tuned > 42.5f && tuned < 44.5f && fabsf(tuned - lrintf(tuned)) > 0.1f, + "F1 0.3 in mode 4 should be a little above G2, off the semitone grid, got %.3f", + tuned); + CHECK(sp1_pui_scale_by_ear() && fabsf(sp1_pui_scale_root() - tuned) < 1e-4f, + "the root is %.3f, not the note FREQUENCY played (%.3f)", sp1_pui_scale_root(), + tuned); + sweep(&s, tuned, 12.0f); + const float major[7] = { 0, 2, 4, 5, 7, 9, 11 }; + printf(" major on that root: %d classes, MIDI %.2f .. %.2f\n", s.cnt, s.lo, s.hi); + CHECK(fabsf(s.lo - (tuned - 12.0f)) < 0.05f && fabsf(s.hi - (tuned + 12.0f)) < 0.05f, + "the ends should be the root an octave down / up, got %.2f..%.2f", s.lo, s.hi); + CHECK(same_classes(s, major, 7), "major around the tuned root: wrong notes"); + + // A scale with tune_by_ear off (pelog) sits on C; stepping does not re-tune. + sp1_pui_set_scale(3); + CHECK(!sp1_pui_scale_by_ear() && sp1_pui_scale_root() == 0.0f, "pelog should stay on C"); + sweep(&s, 0.0f, 12.0f); + const float pelog[7] = { 0.0f, 1.53f, 3.15f, 5.52f, 7.0596f, 8.4804f, 10.5804f }; + CHECK(same_classes(s, pelog, 7) && fabsf(s.lo - 36.0f) < 0.05f && + fabsf(s.hi - 60.0f) < 0.05f, "pelog on C: %d classes, %.2f..%.2f", s.cnt, s.lo, s.hi); + sp1_pui_set_scale(0); + CHECK(fabsf(sp1_pui_scale_root() - tuned) < 1e-4f, "stepping back re-tuned the root"); + + // Off and on again takes a new root; a preset brings its own (PRST format 2). + sp1_pui_set_scale(SP1_PUI_SCALE_OFF); + move_f1(2776); // F1 0.75 -> 48 + 0.5 * 12 = 54 + const float tuned2 = note_now(); + sp1_pui_set_scale(1); + CHECK(fabsf(sp1_pui_scale_root() - tuned2) < 1e-4f && tuned2 > 53.0f && tuned2 < 55.0f, + "re-tuned root %.3f, FREQUENCY played %.3f", sp1_pui_scale_root(), tuned2); + { + sp1_pui_patch pp; + sp1_pui_get(&pp); + CHECK(pp.root == tuned2, "the patch did not take the root: %.3f", pp.root); + sp1_pui_set_scale(SP1_PUI_SCALE_OFF); // forget it, then load the preset + sp1_pui_put(&pp); + CHECK(sp1_pui_scale() == 1 && sp1_pui_scale_root() == tuned2, + "a preset should bring its root back: %.3f", sp1_pui_scale_root()); + pp.root = 0.0f; // a format-1 preset + sp1_pui_put(&pp); + CHECK(sp1_pui_scale_root() == 0.0f, "a preset saved on C should load on C"); + } + + // Big scales: 53-EDO in slot 7, a 13-step Bohlen-Pierce tritave (3/1) in slot 6. + sp1_scale_bank b; + sp1_scales_defaults(&b); + sp1_scale* e = &b.s[6]; + memset(e, 0, sizeof(*e)); + e->period = 1.0f; + e->n = 53; + for (int k = 0; k < 53; ++k) { e->volts[k] = k / 53.0f; e->weight[k] = 255; } + strcpy(e->name, "53-EDO"); + sp1_scale* bp = &b.s[5]; + memset(bp, 0, sizeof(*bp)); + bp->period = log2f(3.0f); + bp->n = 13; + for (int k = 0; k < 13; ++k) { bp->volts[k] = bp->period * k / 13.0f; bp->weight[k] = 255; } + strcpy(bp->name, "bohlen-pierce"); + sp1_scales_install(&b); + sp1_pui_scales_settle(); + + put_mode(10); + sp1_pui_set_scale(6); + sweep(&s, 0.0f, 12.0f); + float edo53[53]; + for (int k = 0; k < 53; ++k) { edo53[k] = 12.0f * k / 53.0f; } + printf(" 53-EDO, mode 10: %d classes per octave\n", s.cnt); + CHECK(s.cnt == 53 && same_classes(s, edo53, 53), "53-EDO gave %d classes", s.cnt); + + put_mode(4); + sp1_pui_set_scale(5); + sweep(&s, 0.0f, 12.0f * log2f(3.0f)); + const float tri = 12.0f * log2f(3.0f); + printf(" tritave, mode 4: MIDI %.2f .. %.2f (roots at k * %.2f)\n", s.lo, s.hi, tri); + // Centre = the root nearest C3 (48): 3 x 19.02 = 57.06; ends one tritave either side. + CHECK(fabsf(s.lo - 2.0f * tri) < 0.05f && fabsf(s.hi - 4.0f * tri) < 0.05f, + "mode 4 with a 3/1 period should run %.2f..%.2f, got %.2f..%.2f", 2.0f * tri, + 4.0f * tri, s.lo, s.hi); + + // The quantizer itself past 32 degrees: at the most selective level only the weight-255 + // degrees (every 4th of 53) remain, including those above bit 31. + { + marbles::Scale sc; + sc.base_interval = 1.0f; + sc.num_degrees = 53; + for (int k = 0; k < 53; ++k) { + sc.degree[k].voltage = k / 53.0f; + sc.degree[k].weight = (k % 4 == 0) ? 255 : 16; + } + static marbles::Quantizer q; + q.Init(sc); + bool on_grid = true, high = false; + for (int i = 0; i < 4000; ++i) { + const float v = -5.0f + 10.0f * i / 4000.0f; + for (int t = 0; t < 8; ++t) { q.Process(v, 1.0f, false); } // settle the level + const float o = q.Process(v, 1.0f, false); + const int k = static_cast(lrintf(o * 53.0f)); + const int cls = ((k % 53) + 53) % 53; + on_grid = on_grid && fabsf(o * 53.0f - k) < 1e-3f && cls % 4 == 0; + high = high || cls > 32; + } + CHECK(on_grid && high, "53-degree quantizer: on grid %d, reached past degree 32 %d", + on_grid, high); + } + + sp1_scales_defaults(&b); + sp1_scales_install(&b); + sp1_pui_scales_settle(); + sp1_pui_set_scale(SP1_PUI_SCALE_OFF); + } + printf("\n%s (%d failure%s)\n", fails ? "FAILED" : "all checks passed", fails, fails == 1 ? "" : "s"); return fails != 0; diff --git a/tools/host-tests/uitest.c b/tools/host-tests/uitest.c index ce2a179..eeb38fa 100644 --- a/tools/host-tests/uitest.c +++ b/tools/host-tests/uitest.c @@ -24,6 +24,7 @@ const char *sp1_marbles_model_name(int m) void sp1_marbles_plaits_scale(int s) { (void)s; } float sp1_marbles_plaits_quantize(float st) { return st; } int sp1_marbles_plaits_degrees(float *st, int max) { (void)st; (void)max; return 0; } +float sp1_marbles_plaits_period(void) { return 12.0f; } const char *sp1_marbles_scale_name(int s) { static const char *const n[7] = { "major", "minor", "pentatonic", "pelog", @@ -213,8 +214,21 @@ int main(void) } } printf("\n"); - CHECK(sp1_mui_scale() == 5, "the free slot is off, so shri must be the top"); + CHECK(sp1_mui_scale() == 6, "the built-in bank fills all 7 slots: whole-tone is the top"); CHECK(!sp1_mui_scale_step(1), "scale stepped past the last included one"); + { + /* An empty slot is skipped (#44): a bank without shri (slot 6). */ + struct sp1_scale_bank bank; + sp1_scales_defaults(&bank); + memset(&bank.s[5], 0, sizeof(bank.s[5])); + sp1_scales_install(&bank); + sp1_mui_scales_settle(); /* we were on slot 7: still filled */ + CHECK(sp1_mui_scale() == 6 && sp1_mui_scale_step(-1) && sp1_mui_scale() == 4, + "an empty slot was not skipped (got %d)", sp1_mui_scale()); + CHECK(sp1_mui_scale_step(1) && sp1_mui_scale() == 6, "skipping up failed"); + sp1_scales_defaults(&bank); + sp1_scales_install(&bank); + } /* ---------- 4. X SHIFT F1-F3 are unbound ---------- */ printf("4. X SHIFT reserved faders\n");