diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index bbda699..f7bdfa1 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.0 + placeholder: v0.8.2 validations: required: true diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml index 6de1b56..e66cefc 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.0 + placeholder: v0.8.2 validations: required: false diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e4d4b19..ae2cba5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -33,7 +33,7 @@ jobs: run: | sh tools/host-tests/hostbuild.sh routetest.cc uitest.c miditest.cc miditest_alt.cc \ miditest_pickup.cc miditest_clock.cc ../../third_party/feldd/test/test_usb_rt_parse.c \ - uactest.c prsttest.c + uactest.c prsttest.c cnfgtest.c "$SP1_HOST_BUILD_DIR/routetest" "$SP1_HOST_BUILD_DIR/uitest" "$SP1_HOST_BUILD_DIR/miditest" @@ -44,6 +44,7 @@ jobs: "$SP1_HOST_BUILD_DIR/test_usb_rt_parse" "$SP1_HOST_BUILD_DIR/uactest" "$SP1_HOST_BUILD_DIR/prsttest" + "$SP1_HOST_BUILD_DIR/cnfgtest" firmware: runs-on: ubuntu-latest diff --git a/README.md b/README.md index a5a10b4..e4b73d3 100644 --- a/README.md +++ b/README.md @@ -5,21 +5,23 @@ Wakes is a semimodular synthesizer, built as a custom firmware for the SP-1, an unreleased Teenage Engineering stem player that was turned into a dev board by its community. -Wakes combines two Mutable Instruments modules: +Wakes combines code from three Mutable Instruments modules: - **Plaits**: A macro-synthesizer voice, featuring multiple sound engines - **Marbles**: A playful random sequencer +- **Yarns**: A MIDI translator The development of Wakes is unaffiliated with Teenage Engineering or Mutable Instruments. -**IMPORTANT:** Flash custom firmware on the SP-1 at your own risk. SP-1s are abandonware, they do not have manufacturer support. There is no way to go back to the base firmware once you've flashed it away. + +**CRITICAL:** Flash custom firmware on the SP-1 at your own risk. SP-1s are abandonware, they do not have manufacturer support. There is no way to go back to the base firmware once you've flashed it away. ## πŸ“– Manual -**[Wakes – Manual (PDF)](docs/Wakes%20-%20Manual.pdf)**: The manual details the layout of each page, with every control and how how to use them, in an aesthetically pleasing and readable format. Once you've installed Wakes on your SP-1 using the Flashing section below, start here. +**[Wakes – Manual (PDF)](docs/Wakes%20-%20Manual.pdf)**: The manual details the layout of each page, with every control and how to use them, in an aesthetically pleasing and readable format. Once you've installed Wakes on your SP-1 using the Flashing section below, start here. ## Status -**v0.8.0, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues). +**v0.8.2, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues). ## Flashing @@ -36,6 +38,17 @@ The T1+T4 recovery trigger in step 4 lives in Teenage Engineering's bootloader, works with whatever firmware is installed. Wakes never writes below the flash memory's `0x20000` (and neither should your CFW's), because that's where the bootloader lives. +## Configuration + +Wakes keeps its settings as `.cnfg` files on its own drive, in `WAKES/CNFG/`: the engine stack +(`engines.cnfg`), MIDI (`midi.cnfg`), USB audio (`audio.cnfg`) and logging (`logs.cnfg`). Plug the +SP-1 into a computer while it's in STANDBY (OFF, with USB plugged in), edit a file in a text editor, +eject, and turn Wakes ON: it reads them at every ON. Each file explains its own settings. Delete a +file to reset it; Wakes writes a fresh copy with the defaults at the next ON. No fork or build needed. + +The files in [`config/`](config/) are the defaults built into the firmware, not your device's +settings. Edit them only to build Wakes with different defaults ([`config/README.md`](config/README.md)). + ## Building Zephyr **v4.3.1** and Zephyr SDK **0.17.4**, both pinned. The workspace path must not contain @@ -58,13 +71,14 @@ Output: `build/zephyr/wakes-sp1.bin`. The Zephyr patch is required and is lost o | | | |---|---| | [`docs/UI-PAGES.md`](docs/UI-PAGES.md) | every control on every page, in detail | -| [`config/engines.csv`](config/engines.csv) | which engine sits in each of the 24 slots (editable) | +| [`config/engines.cnfg`](config/engines.cnfg) | the default engine stack: which engine sits in each of the 24 slots, and what every engine does | | [`docs/PLAITS-ENGINES.md`](docs/PLAITS-ENGINES.md) | every engine, its faders and its CPU cost | | [`docs/MARBLES-SETTINGS.md`](docs/MARBLES-SETTINGS.md) | Marbles models, ranges and scales | | [`docs/DEFAULTS.md`](docs/DEFAULTS.md) | every default, and what a reset restores | | [`docs/MIDI.md`](docs/MIDI.md) | MIDI over USB: what it does, and how to change it | -| [`config/midi.ini`](config/midi.ini) | the MIDI script: channel, legato, CC numbers (editable) | -| [`config/audio.ini`](config/audio.ini) | USB audio out: its level (parked or on VOL) and the speaker while a host records (editable) | +| [`config/midi.cnfg`](config/midi.cnfg) | the MIDI script: channel, legato, CC numbers (the default; Wakes reads `WAKES/CNFG/midi.cnfg` on its drive at every ON) | +| [`config/audio.cnfg`](config/audio.cnfg) | USB audio out: its level (parked or on VOL) and the speaker while a host records (the default; Wakes reads `WAKES/CNFG/audio.cnfg` on its drive at every ON) | +| [`config/logs.cnfg`](config/logs.cnfg) | the log Wakes writes to its drive, `WAKES/LOGS/` (the default; Wakes reads `WAKES/CNFG/logs.cnfg` on its drive at every ON) | | [`docs/SAFETY.md`](docs/SAFETY.md) | rules for anyone changing the firmware | ## Licence diff --git a/config/README.md b/config/README.md new file mode 100644 index 0000000..efd2ada --- /dev/null +++ b/config/README.md @@ -0,0 +1,33 @@ +# config/ β€” Wakes' built-in defaults + +**These files are not the settings on your Wakes.** They are the defaults every firmware image is +built with. You do not need to edit them, fork this repository or build anything to change how +your Wakes behaves. + +## To change your Wakes' settings + +Edit the copies on Wakes' own drive: + +1. Plug Wakes into a computer while it is off (STANDBY). It shows up as a drive. +2. Open `WAKES/CNFG/` and edit the file in a text editor. +3. Eject the drive and turn Wakes ON. It reads the files at every ON. + +If a file is missing from `WAKES/CNFG/`, Wakes writes it there with these defaults at the next ON, +so deleting a file is how you reset it. Each file explains its own settings, and a line Wakes +cannot read keeps its default and is named in the log (`WAKES/LOGS/`). + +| File | What it sets | +|---|---| +| `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 | +| `logs.cnfg` | the log Wakes writes to its drive, and what goes in it | + +## When to edit these + +Only to build your own firmware with **different defaults**: the values a Wakes uses when its drive +has no file, and the text it writes there when one is missing. The build checks every file here and +stops, naming the line, if one is wrong, so a broken default can never ship. + +You can also copy a file from here to `WAKES/CNFG/` to get a clean one back, though deleting it +from the drive does the same thing. diff --git a/config/audio.cnfg b/config/audio.cnfg new file mode 100644 index 0000000..8e5ce77 --- /dev/null +++ b/config/audio.cnfg @@ -0,0 +1,38 @@ +; Format: ini +; ===================================================================================== +; Wakes β€” the audio settings +; ===================================================================================== +; +; This file configures how Wakes handles sound output. Wakes reads this file from its drive +; (WAKES/CNFG/audio.cnfg) every time it turns ON. +; +; Lines starting with ; or # are comments. They are not applied as settings. +; Every setting can be left blank to get its default. +; A line Wakes cannot read keeps its default, and the log (WAKES/LOGS/) names it. + + +[usb] +; USB AUDIO OUT. Plugged into a computer, phone or other USB host, Wakes shows up as an +; audio input ("Wakes Audio Out", or "Wakes" - the name depends on the host): 48 kHz, +; 16-bit stereo, no driver. It carries what the speaker and headphones get. + +; level - How USB audio out sets its level: +; parked (default) = +; while a host takes USB audio, VOL is set to `parked_level` (the next parameter below) +; and VOL+/VOL- are disabled. When the host stops, VOL goes back to where you left it. +; Wakes has ONE output level controlling every output, so parking it parks the +; headphones (and the speaker, if `speaker = on`) at that level too. +; vol = +; VOL+/- are unlocked, controlling USB audio gain like everything else. +level = parked + + +; parked_level - 'parked' mode gainstage, in dB. Options are: -- 0, -3, -6, -9, -12, +; -15, -18, -21, -24, -27 or -30. 0 is full scale, which Wakes' loudest patches (the +; drive's top steps) reach; -6 leaves the recording device some headroom. +parked_level = -6 + +; speaker - enable or disable the speaker while a host takes USB audio: +; off (default) = while connected, the onboard speaker is disabled. +; on = the speaker will play the same audio that goes out over USB and the headphone jack. +speaker = off \ No newline at end of file diff --git a/config/audio.ini b/config/audio.ini deleted file mode 100644 index 9e16a7d..0000000 --- a/config/audio.ini +++ /dev/null @@ -1,43 +0,0 @@ -; ===================================================================================== -; Wakes β€” the audio settings -; ===================================================================================== -; -; How Wakes' sound leaves the device. Edit it in your fork, build (or let CI build) and -; flash: the build reads this file and FAILS with the line number if something in it is -; wrong, so a typo can never become a firmware that silently ignores your setting. -; -; Lines starting with ; are comments. Every setting can be left out to get its default. - - -[usb] -; USB AUDIO OUT. Plugged into a computer, phone or other USB host, Wakes shows up as an -; audio input ("Wakes Audio Out", or "Wakes" -- the name depends on the host): 48 kHz, -; 16-bit stereo, no driver. It carries what the speaker and headphones get -- the output -; select (OUT / AUX / OUT+AUX / OUTxAUX) and the drive included. Nothing changes until a -; host actually takes the audio (records or monitors the input); these settings apply only -; while it does. Headphones always play. - -; How USB audio out sets its level: -; parked (default) = while a host takes USB audio, VOL is set to `parked_level` and its -; buttons do nothing, so a recording's level never depends on where VOL happened to -; be. When the host stops, VOL goes back to where you left it. -; Wakes has ONE output level for every output, so parking it parks the headphones -; (and the speaker, if `speaker = on`) at that level too. That is deliberate: it is -; the cheapest way to do it. A separate level for USB alone would need a second gain -; pass over every block of audio (about 0.3 % of the CPU), which Wakes keeps for its -; engines. -; vol = VOL moves USB audio out like everything else, like the volume knob of a -; hardware synth on a mixer track. -level = parked - -; The level USB audio out is parked at, in dB: one of VOL's steps -- 0, -3, -6, -9, -12, -; -15, -18, -21, -24, -27 or -30. 0 is full scale, which Wakes' loudest patches (the -; drive's top steps) reach; -6 leaves a recording some headroom. -parked_level = -6 - -; The speaker while a host takes USB audio: -; off (default) = quiet: the host is recording, so the room only gets a second copy. -; It comes back as soon as the host stops taking the audio (or goes to sleep, or the -; cable is pulled). -; on = it keeps playing. -speaker = off diff --git a/config/engines-instructions.md b/config/engines-instructions.md deleted file mode 100644 index d55b86b..0000000 --- a/config/engines-instructions.md +++ /dev/null @@ -1,18 +0,0 @@ -# Configuring `engines.csv` - -Each row is a slot, 1 to 24. T2/T3 step through the slots in row order. - -- **Edit only the Engine column.** Don't change Slot or Glyph, and don't move whole rows. -- **Add an engine:** type its name into an empty Engine cell. -- **Remove an engine:** clear its Engine cell. Empty slots are skipped. -- **Reorder:** move names between Engine cells. -- Each engine can be used once. The device starts on the first filled slot. -- Save as UTF-8. If the glyphs turn into `?`, write them as `#` (full), `+` (half), `.` (off). -- Rebuild the firmware. If the file is wrong, the build names the line. - -## Engine names - -2-op FM Β· 6-op FM A Β· 6-op FM B Β· 6-op FM C Β· additive Β· bass drum Β· chiptune Β· chords Β· -filtered noise Β· grain / formant Β· hi-hat Β· modal Β· particle Β· phase distortion Β· snare drum Β· -speech Β· string Β· string machine Β· swarm Β· VA + VCF Β· virtual analog Β· wave terrain Β· -waveshaping Β· wavetable diff --git a/config/engines.cnfg b/config/engines.cnfg new file mode 100644 index 0000000..d5355bf --- /dev/null +++ b/config/engines.cnfg @@ -0,0 +1,278 @@ +; Format: ini +; ===================================================================================== +; Wakes β€” Plaits Engine Stack Configuration +; ===================================================================================== +; +; Mutable Instruments Plaits is a Eurorack macro-oscillator module created by Γ‰milie Gillet, +; and its code comprises the audible portion of Wakes! Plaits has 24 sound engines. Its custom +; firmware community has created many more over the years. Wakes currently features the originals. +; This CNFG file determines the Plaits sound engines you want to include in your engine stack. +; T2 and T3 step through the slots in the order shown below, skipping empty slots or unused lines. +; Wakes starts on the first filled slot. You'll return to that slot when you Rip Out The Cables. +; +; - LIST FORMAT: +; N = engine-name ; +; +; - 16 default slots, with a maximum of 24. Each slot has its own glyph which flashes when selected. +; Glyphs are shown after the ; on each line. The glyph belongs to the SLOT, not to the engine +; in that slot. Moving an engine moves it to that slot's glyph. +; - To include an engine, paste its name directly from the ENGINES section below. +; Each engine can be used once. +; - Leave a slot empty (or delete its line) to skip it. +; - This file is the whole stack: a slot that is not listed here is empty. +; - Engines that are not in the stack will still be usable if a PRST uses them. +; You'll know an engine is not in your stack by a flashing glyph across all four face LEDs. +; - If Wakes can't use this file (a misspelled engine, an engine used twice, or no engines at +; all), it ignores the whole file and plays the 16 built-in engines. The log says which line. +; +; Remember: in ini files, text following a ; or a # is a comment. + +[engines] +1 = virtual-analog ; ●○○○ +2 = waveshaping ; ●●○○ +3 = 2-op-FM ; ●●●○ +4 = grain-formant ; ●●●● +5 = additive ; ○●●● +6 = wavetable ; ○○●● +7 = chords ; ○○○● +8 = speech ; ○●○○ +9 = swarm ; ○○●○ +10 = filtered-noise ; ●○○● +11 = particle ; ○●●○ +12 = string ; ●○●● +13 = modal ; ●●○● +14 = bass-drum ; ●○●○ +15 = snare-drum ; ○●○● +16 = hi-hat ; β—‹β—‹β—‹β—‹ +17 = ; ◐◐◐◐ +18 = ; ○◐◐○ +19 = ; ◐○○◐ +20 = ; ○◐○◐ +21 = ; ◐○◐○ +22 = ; ○◐◐◐ +23 = ; ○○○◐ +24 = ; ○◐○○ + + +; ===================================================================================== +; ENGINES +; ===================================================================================== +; +; This section contains a micro-manual for each Plaits engine Wakes can play, including +; engine names to copy from and paste above. +; Faders: F1 is always FREQ, but F2, F3 and F4 each have engine-unique parameters. +; The signals offered on the AUX output also differ between engines. +; Most engine parameters are unipolar. For engines where some parameters are bipolar, +; they're indicated below. + +; ------------------------------------------------------------------------------------- +; virtual-analog (default slot 1) +; ------------------------------------------------------------------------------------- +; Two analog-style oscillators mixed together: a variable square and a variable saw. +; F2 TIMB the square: narrow pulse -> full square -> hard-sync formants +; F3 MORP the saw: triangle -> saw, with a notch that widens +; F4 HARM detune between the two oscillators +; AUX two hard-synced waveforms added together, shaped by MORP +; Bipolar parameters: F2, F4. + +; ------------------------------------------------------------------------------------- +; waveshaping (default slot 2) +; ------------------------------------------------------------------------------------- +; A triangle wave through a waveshaper and a wavefolder. +; F2 TIMB how hard the wavefolder folds +; F3 MORP asymmetry of the waveform +; F4 HARM the waveshaper's curve +; AUX the same, through a different wavefolder curve +; Bipolar parameters: F4. + +; ------------------------------------------------------------------------------------- +; 2-op-FM (default slot 3) +; ------------------------------------------------------------------------------------- +; Two sine operators, one modulating the other's phase. +; F2 TIMB modulation index: how bright the tone is +; F3 MORP feedback: one operator modulating its own phase or the other's +; F4 HARM frequency ratio between the two operators +; AUX a sub-oscillator +; Bipolar parameters: F3. + +; ------------------------------------------------------------------------------------- +; grain-formant (default slot 4) +; ------------------------------------------------------------------------------------- +; Vocal-like formants made from windowed sine grains. +; F2 TIMB formant frequency +; F3 MORP formant width and shape +; F4 HARM frequency ratio between the two formants +; AUX filtered waveforms imitated with windowed sines +; Bipolar parameters: F4. + +; ------------------------------------------------------------------------------------- +; additive (default slot 5) +; ------------------------------------------------------------------------------------- +; A sum of harmonics whose levels follow one or more bumps in the spectrum. +; F2 TIMB which harmonic is loudest -- a little like a filter cutoff +; F3 MORP bump shape: flat and wide -> peaked and narrow +; F4 HARM how many bumps the spectrum has, starting from one +; AUX only the harmonics a drawbar organ has + +; ------------------------------------------------------------------------------------- +; wavetable (default slot 6) +; ------------------------------------------------------------------------------------- +; Banks of single-cycle waves laid out in a grid. +; F2 TIMB wavetable row: the waves are sorted dark to bright +; F3 MORP wavetable column: select shape families +; F4 HARM which bank (from the middle down, TIMB and MORP are interpolated) +; AUX a low-fi, 5-bit version + +; ------------------------------------------------------------------------------------- +; chords (default slot 7) +; ------------------------------------------------------------------------------------- +; Four-note chords played by a string-machine ensemble or a wavetable scan. +; F2 TIMB chord voicing - inversion and transposition +; F3 MORP waveform: string-machine sounds below the middle, wavetable above +; F4 HARM chord types: oct, 5, sus4, m, m7, m9, m11, 69, M9, M7, M +; AUX the chord's isolated root note + +; ------------------------------------------------------------------------------------- +; speech (default slot 8) +; ------------------------------------------------------------------------------------- +; A collection of speech synth algorithms: formant filters, SAM, LPC vowels and words. +; F2 TIMB size of the speaker, from Daleks to chipmunks (Γ‰milie's wording lol) +; F3 MORP which vowel, phoneme or word segment +; F4 HARM the method: formants -> SAM -> LPC vowels, then banks of LPC words +; AUX the raw voice source, pre-filtering + +; ------------------------------------------------------------------------------------- +; swarm (default slot 9) +; ------------------------------------------------------------------------------------- +; Eight saw-like grains, each slightly detuned: a cloud of voices. +; F2 TIMB how many grains per second +; F3 MORP grain length and overlap; at the top they run into each other +; F4 HARM how far each grain's pitch wanders +; AUX the same cloud made of sine waves + +; ------------------------------------------------------------------------------------- +; filtered-noise (default slot 10) +; ------------------------------------------------------------------------------------- +; Clocked noise through a resonant filter. +; F2 TIMB the noise's clock rate +; F3 MORP filter resonance +; F4 HARM filter type: low-pass -> band-pass -> high-pass +; AUX two band-pass filters, as far apart as HARM sets +; Bipolar parameters: F4. + +; ------------------------------------------------------------------------------------- +; particle (default slot 11) +; ------------------------------------------------------------------------------------- +; Random impulses ringing through filters: rain, crackle, droplets. +; F2 TIMB how dense the particles are +; F3 MORP below centre: reverberating all-pass network, above it: resonant +; band-pass filters +; F4 HARM how random each particle's pitch is +; AUX the raw impulses (dust) +; Bipolar parameters: F3. + +; ------------------------------------------------------------------------------------- +; string (default slot 12) +; ------------------------------------------------------------------------------------- +; A plucked or bowed string, modelled physically. Two strings take turns, so a new note +; can ring while the last one fades. +; F2 TIMB how bright the excitation is (and how dense, while it drones) +; F3 MORP decay time +; F4 HARM inharmonicity: dispersive at the bottom, stiff at the top, and +; harmonic in a small zone about a quarter of the way up +; AUX the raw excitation + +; ------------------------------------------------------------------------------------- +; modal (default slot 13) +; ------------------------------------------------------------------------------------- +; A struck resonator: bells, bars, plates, membranes. +; F2 TIMB how bright the excitation is (and how dense, while it drones) +; F3 MORP decay time +; F4 HARM the material: how inharmonic the resonator is +; AUX the raw excitation + +; ------------------------------------------------------------------------------------- +; bass-drum (default slot 14) +; ------------------------------------------------------------------------------------- +; An analog-style kick. +; F2 TIMB brightness +; F3 MORP decay time +; F4 HARM how sharp the attack is, and how much overdrive +; AUX a different kick: a frequency-modulated triangle shaped into a sine + +; ------------------------------------------------------------------------------------- +; snare-drum (default slot 15) +; ------------------------------------------------------------------------------------- +; An analog-style snare: tuned drum modes and noise. +; F2 TIMB balance between the drum's modes +; F3 MORP decay time +; F4 HARM balance between the drum and the noise +; AUX a different snare: two frequency-modulated sines and high-passed noise + +; ------------------------------------------------------------------------------------- +; hi-hat (default slot 16) +; ------------------------------------------------------------------------------------- +; A metallic hi-hat: square oscillators ring-modulating each other, plus noise. +; F2 TIMB high-pass filter cutoff +; F3 MORP decay time +; F4 HARM balance between the metal and the noise +; AUX a different hi-hat: three pairs of ring-modulated squares, cleaner + +; ------------------------------------------------------------------------------------- +; VA-VCF (not in the default stack) +; ------------------------------------------------------------------------------------- +; A classic subtractive voice: an analog-style oscillator into a resonant filter. +; F2 TIMB filter cutoff +; F3 MORP waveform, and how much sub-oscillator +; F4 HARM resonance and character: a gentle 24 dB/oct filter below the middle, +; a harsh 12 dB/oct one above +; AUX the high-pass output +; Bipolar parameters: F3, F4. + +; ------------------------------------------------------------------------------------- +; phase-distortion (not in the default stack) +; ------------------------------------------------------------------------------------- +; A sine whose phase is bent by a second oscillator: Casio-style tones. +; F2 TIMB how much distortion +; F3 MORP how asymmetric the distortion is +; F4 HARM the distorting oscillator's frequency +; AUX the same with the carrier running free: phase modulation + +; ------------------------------------------------------------------------------------- +; wave-terrain (not in the default stack) +; ------------------------------------------------------------------------------------- +; A point circling over a 3D surface; the height under it is the sound. +; F2 TIMB the size of the circle +; F3 MORP where the circle sits on the surface +; F4 HARM which surface +; AUX the height used to bend the phase of a sine instead +; Bipolar parameters: F3. + +; ------------------------------------------------------------------------------------- +; string-machine (not in the default stack) +; ------------------------------------------------------------------------------------- +; A vintage string ensemble playing chords, through a chorus and a filter. +; F2 TIMB chorus and filter amount +; F3 MORP waveform +; F4 HARM chord +; AUX part of the chord (mostly the 2nd and 4th voices) +; Bipolar parameters: F2. + +; ------------------------------------------------------------------------------------- +; chiptune (not in the default stack) +; ------------------------------------------------------------------------------------- +; An 8-bit game console: pulse waves playing chords and arpeggios. +; F2 TIMB arpeggio pattern, or chord inversion +; F3 MORP pulse width, and sync +; F4 HARM chord +; AUX the console's triangle voice + +; ------------------------------------------------------------------------------------- +; 6-op-FM-A 6-op-FM-B 6-op-FM-C (not in the default stack) +; ------------------------------------------------------------------------------------- +; Three banks A, B and C, each containing 32 six-operator FM patches in the style of a DX7. +; F2 TIMB modulator levels +; F3 MORP stretches the envelopes and the modulation ("time travel") +; F4 HARM Bank patch selection +; AUX the same as OUT +; Bipolar parameters: F3. diff --git a/config/engines.csv b/config/engines.csv deleted file mode 100644 index adc3338..0000000 --- a/config/engines.csv +++ /dev/null @@ -1,25 +0,0 @@ -Slot,Glyph,Engine -1,●○○○,virtual analog -2,●●○○,waveshaping -3,●●●○,2-op FM -4,●●●●,grain / formant -5,○●●●,additive -6,○○●●,wavetable -7,○○○●,chords -8,○●○○,speech -9,○○●○,swarm -10,●○○●,filtered noise -11,○●●○,particle -12,●○●●,string -13,●●○●,modal -14,●○●○,bass drum -15,○●○●,snare drum -16,β—‹β—‹β—‹β—‹,hi-hat -17,◐◐◐◐,VA + VCF -18,○◐◐○,phase distortion -19,◐○○◐,wave terrain -20,○◐○◐,string machine -21,◐○◐○,chiptune -22,○◐◐◐, -23,○○○◐, -24,○◐○○, diff --git a/config/logs.cnfg b/config/logs.cnfg new file mode 100644 index 0000000..88e02de --- /dev/null +++ b/config/logs.cnfg @@ -0,0 +1,40 @@ +; Format: ini +; ===================================================================================== +; Wakes β€” LOGS +; ===================================================================================== +; +; Wakes logs activity to its drive, in WAKES/LOGS/. One file per session (from turning Wakes +; on, until it is turned off). The last 5 sessions are kept. +; Find your log files in WAKES/LOGS/SESSION. Logs are named with the latest session's number. +; If you need support, we might ask you to send us these. Each file stops at 8 MB, about 12 +; hours of playing. +; +; Wakes reads this .cnfg file every time it turns ON and applies cnfg changes. +; Edit these settings to control log granularity. Adara might ask to edit these based on your +; circumstance. +; +; Lines starting with ; or # are comments. Every setting can be left out to get its default. +; A setting Wakes cannot read keeps its default, and the log says which line it was. +; +; Startup, power, battery, headphone and cnfg file lines are always written; +; the settings below choose what else gets logged. + +[logs] +; on = Wakes writes the log to its drive while ON (default). +; off = nothing is written to the drive. +enabled = on + +; CPU and audio load, every 5 seconds. +performance = on + +; What you do on the controls: pages, engines, routing, scales, ROTC. +controls = off + +; MIDI over USB, and the MIDI clock. +midi = off + +; USB audio out and the USB connection. +usb = off + +; Storage drive logs: loading and saving presets (PRST), .logs files. +storage = on diff --git a/config/midi.cnfg b/config/midi.cnfg new file mode 100644 index 0000000..9338b72 --- /dev/null +++ b/config/midi.cnfg @@ -0,0 +1,228 @@ +; Format: ini +; ===================================================================================== +; Wakes β€” MIDI +; ===================================================================================== +; +; This file configures Wakes' MIDI handling. Wakes reads this file from its drive +; (WAKES/CNFG/midi.cnfg) every time it turns ON, so a change takes effect at the next ON. +; +; Lines starting with ; or # are comments. Every setting can be left out to get its +; default. A line Wakes cannot read keeps its default, and the log (WAKES/LOGS/) names it. +; If two of your lines give the same CC, the first one keeps it and the later one gets +; none. A CC you give a parameter is taken from whichever parameter had it by default. +; The CC chart that comes with each Wakes release lists the default CCs. + +[midi] +; Which MIDI channel Wakes listens on: 1-16, or omni (every channel). +channel = omni + +; note_priority - Plaits is a monophonic synthesizer. When several keys are held, determines +; which one you hear: +; last = the most recently pressed key (most mono synths). +; low = the lowest key held -- a bass line that ignores notes played above it. +; high = the highest key held -- a lead that ignores notes played below it. +; Wakes remembers up to 12 held keys. Let go of the one sounding and the next by the same +; rule takes over if it is still held (with `last`: the one pressed before it). +note_priority = last + +; legato - What happens when a new note takes over while another key is still held: +; off = it strikes TRIG again, like a new note, and so does falling back to a key still +; held. Every note is articulated. Portamento (below) applies to every note. +; on = no reTRIG: the pitch moves to the new note while the sound carries on, +; as on a monosynth played legato. Only a note played after letting go of every +; key strikes. Portamento applies to every note. +; auto = as on, and portamento ONLY between overlapping notes: play legato to glide, +; detached to jump straight to the next note (with a strike) -- portamento under +; your fingers rather than always on. +; The same pitch played again before its note-off -- a sequencer's notes longer than its +; step -- strikes again in off, and is tied into one long note in on and auto. Either way it +; ends at the LAST of its note-offs, not the first. +legato = auto + +; portamento - the pitch glides from one note to the next instead of jumping. +; 0 = none. +; t1 .. t50 = constant TIME: every glide takes the same time, whatever the interval. +; The curve is exponential -- fast at first, then settling into the note, +; the way an analog glide (a capacitor charging) sounds -- and it lands +; exactly on the note at the set time. +; r0 .. r50 = constant RATE: the pitch moves in a straight line at a fixed speed, so a +; wider interval takes longer. The time below is per octave: a fifth takes +; 7/12 of it, two octaves twice it. +; The scale is steep, finest at the short end. Glide time (t), or time per octave (r): +; 1 ~ 1 ms 5 ~ 6 ms 10 ~ 22 ms 20 ~ 135 ms 30 ~ 0.47 s 40 ~ 1.2 s 50 ~ 2.6 s +; (r0 is under 1 ms per octave: practically instant.) +portamento = t9 + +; bend_range - Pitch bend range in semitones, 0-24. If the host sends its own bend range +; (RPN 0, "pitch bend sensitivity"), Wakes uses the host's until unplugged. +bend_range = 2 + +; The sustain pedal: cc N, or off. CC 64 is the standard pedal. +sustain = cc 64 + +; cc_smoothing - How long a CC takes to glide to a new value, in milliseconds (0-200). +; This is what turns a CC's steps into a smooth movement instead of zipper noise. +cc_smoothing = 10 + +; clock - controls whether Marbles receives MIDI clock and transport. +; on = Marbles' clock syncs with the host's clock when it receives a tick or start message. +; Marbles' RATE fader then picks a ratio of the host's beat instead of a tempo: +; 1/4, 1/3, 1/2, 2/3, 1, 3/2, 2, 3, 4. DIV+/- selects a subdivision of that ratio. +; off = disabled. +clock = on + +; clock_lead - Determines how far ahead of the host's clock Marbles will compensate. +; notes (default) = Marbles will intelligently switch between MIDI note-based clock +; delay compensation and its own auto-switching delay compensation (below). +; auto = Wakes' own delay (8.5 ms): Marbles' beats leave the output when the clock's do. +; While the host is recording Wakes over USB audio, that output is 1 ms later, and +; auto (and notes, until it has measured) follows it: 9.5 ms. +; 0-200 = that many ms, for a host whose clock offset you would rather set here. +; Tips: +; With the 'notes' or 'auto' options, leave the host's own clock offset / sync delay +; for Wakes at 0. +; Wakes outputs sound with a small delay after the triggers that cause it. Audio can't +; be played early, but a clock can: it is steady, so Wakes can read ahead and compensate +; to play tighter. +clock_lead = notes + +; pickup - How a CC and its fader share a parameter. A control that does not match the value +; does not jump - moving it moves the value the same way from where it is, a little faster +; or slower, until the two meet and continue together. +; +; sum = the CC is an OFFSET on top of the fader: fader + CC. A parameter whose +; middle is neutral reads its CC centred (64 = no change, 0 / 127 = half a +; travel down / up); any other reads it one-sided (0 = no change, 127 = a +; whole travel up); TIMBRE / MORPH / HARMONICS follow the engine, and when an +; engine change flips how one reads, the offset catches up instead of jumping. +; Unplug and every offset goes back to zero. +; shared = the CC and the fader are two hands on ONE value. A CC reads like the fader +; (0 = the bottom, 127 = the top). Whichever you move takes the value from +; where the other left it and catches up with your hand. +; takeover = while MIDI is plugged in, the faders that have a CC here REST, and only the +; CC moves the parameter (catching up with where the fader left it). Unplug and +; the faders work again, catching up with where the CC left it. +; +; In shared and takeover the CC moves the parameter itself: the fader LEDs show where the +; host put it, and it stays there when you unplug. A host knob's FIRST value after plugging +; in -- including the snapshot some hosts send when they connect -- only tells Wakes where +; the knob is; nothing moves until you turn it. +; MODEL has no fader, so it is an offset in every setting (see [plaits]), and so are the +; [bind] sources at the end of this file. +pickup = shared + +; ------------------------------------------------------------------------------------- +; MIDI CC Assignments +; +; Example: +; +; name = cc N (or none) +; +; CC 0-31 are 14-bit: Wakes also listens to their partner CC N+32 for the fine half of +; the value, which is how a host sends high-resolution CCs. A host that only sends the +; coarse half still works. Any other CC is 7-bit (128 steps), smoothed. +; For this reason, CCs 33-63 can't be assigned. Wakes will refuse them. +; +; The defaults below use only CC numbers that keyboards and DAWs do not send on their +; own (the undefined ones, and General Purpose 1-4 = CC 16-19), so out of the box +; nothing moves until you point something at it. The mod wheel (1), breath (2), foot +; (4), portamento time (5) and expression (11) are deliberately left free for you. +; +; The following MIDI CCs are not allowed for parameter control, +; as they are taken up by other functions: +; CC 0 and its fine-half CC 32 (bank select) +; CC 6 and its fine-half CC 38 (data entry) +; CC 96-101 (data entry and parameter numbers -- needed for the host's bend range) +; CC 120-127 (channel mode messages) +; CC 33-63 (discussed above) +; +; How a CC reads depends on `pickup` (refer to the explanation above). +; ------------------------------------------------------------------------------------- + + + + +[plaits] +; BASE page +timbre = cc 3 +morph = cc 9 +harmonics = cc 14 +frequency = cc 15 + +; SHIFT page: the four attenuverters +fm_attenuverter = cc 20 +timbre_attenuverter = cc 21 +morph_attenuverter = cc 22 +harmonics_attenuverter = cc 23 + +; SETTINGS page +lpg_colour = cc 24 +lpg_decay = cc 25 +level = cc 26 +octave_range = cc 102 +; model - Selects which engine plays, as an offset from the one T2/T3 selected, +; up through the filled slots of engines.cnfg (0 = the selected engine, 127 = the +; last slot). Changing MODEL will flash the slot glyph, as T2/T3 do. +; MIDI changes the engine at most every 50 ms -- each change costs the audio thread +; a brief CPU spike, as a T2/T3 press does. +model = cc 105 + + + + +[marbles] +; t page +rate = cc 27 +t_bias = cc 16 +jitter = cc 85 +deja_vu = cc 31 + +; t SHIFT page +gtlt = cc 89 +gate_length = cc 17 +gate_length_random = cc 86 +length = cc 103 + +; X page +spread = cc 28 +x_bias = cc 29 +steps = cc 30 + +; SETTINGS (Y) page +y_spread = cc 18 +y_bias = cc 19 +y_steps = cc 87 +y_divider = cc 104 + + + + +; ------------------------------------------------------------------------------------- +; Extra sources. +; +; velocity = [%] how hard each note was played +; aftertouch = [%] channel pressure +; +; is any parameter name pasted from the two MIDI CC parameter lists above +; (or `none`), and an optional depth setting -100% .. 100% (100% if unset). +; The source offsets that parameter by up to its full travel at 100%, regardless of the +; `pickup` setting selected above. +; +; Aimed at `level`, it sets how far each note opens LEVEL instead, which Plaits also reads +; similarly to an accent modulation: soft notes are quieter and darker. +; At 100%, the hardest note opens the LPG fully, and at 0%, velocity is functionally +; disabled. To play every note at full LEVEL, disconnect velocity by setting it to `none`. +; +; You can also do this on the host instead: most DAWs can turn velocity or pressure +; into a CC, and aim it at the CC of the parameter you want. +; +; Examples: +; +; velocity = level +; aftertouch = timbre 50% +; +; ------------------------------------------------------------------------------------- + +[bind] +velocity = none +aftertouch = none diff --git a/config/midi.ini b/config/midi.ini deleted file mode 100644 index 5998845..0000000 --- a/config/midi.ini +++ /dev/null @@ -1,243 +0,0 @@ -; ===================================================================================== -; Wakes β€” the MIDI script -; ===================================================================================== -; -; How Wakes listens to MIDI over USB. Edit it in your fork, build (or let CI build) and -; flash: the build reads this file and FAILS with the line number if something in it is -; wrong, so a typo can never become a firmware that silently ignores your setting. -; Every build also writes a CC chart from this file (Markdown, and a CSV in the -; midi.guide format) next to the firmware, so your chart always matches your script. -; -; Lines starting with ; are comments. Every setting can be left out to get its default. -; -; What MIDI does on Wakes, in short: -; NOTES play Plaits, one at a time (the newest, by default). A note-on strikes TRIG and -; opens LEVEL -- as far as the note's velocity says, by default ([bind] below) -- and a -; note-off lets it close through Plaits' own low-pass gate. Pitch is added to FREQUENCY -; like a V/Oct cable, with note 60 (C4) adding nothing: with F1 on its centre detent the -; keyboard plays at its real pitch, and F1 transposes. From the first note or CC until -; you unplug, FREQUENCY's scale quantizer stands aside and F1's centre detent widens -; to 10 %. -; CCs: each parameter below can be given a CC, which moves it like a second hand on its -; fader -- how the two hands share it is `pickup`, below. Nothing moves until you aim -; something at it. -; CLOCK: Marbles follows the host's MIDI clock and Start / Continue / Stop (`clock`). -; UNPLUG: notes are released, the bend and every offset go back to neutral, and a -; Marbles the host was clocking stops and has its own clock again. -; -; docs/MIDI.md has the whole story. -; -; Credit: the way Wakes plays notes -- which held note sounds, legato, portamento, the -; sustain pedal -- is ported from Mutable Instruments Yarns (Emilie Gillet, MIT): its -; monophonic part, with its note stack, its legato modes and its portamento curves and -; table. Everything Yarns does that matters here is explained below, so you never need -; its manual to read this file. Attribution in NOTICE. - -[midi] -; Which MIDI channel Wakes listens on: 1-16, or omni (every channel). Clock and transport -; have no channel, so Marbles follows them whatever this says. -channel = 1 - -; Plaits plays one note at a time. When several keys are held, which one you hear: -; last = the most recently pressed key (most mono synths). -; low = the lowest key held -- a bass line that ignores notes played above it. -; high = the highest key held -- a lead that ignores notes played below it. -; Wakes remembers up to 12 held keys. Let go of the one sounding and the next by the same -; rule takes over if it is still held (with `last`: the one pressed before it). -note_priority = last - -; What happens when a new note takes over while another key is still held: -; off = it strikes TRIG again, like a new note, and so does falling back to a key still -; held. Every note is articulated. Portamento (below) applies to every note. -; on = it does NOT strike: the pitch moves to the new note while the sound carries on, -; as on a monosynth played legato. Only a note played after letting go of every -; key strikes. Portamento applies to every note. -; auto = as on, and portamento ONLY between overlapping notes: play legato to glide, -; detached to jump straight to the next note (with a strike) -- portamento under -; your fingers rather than always on. -; The same pitch played again before its note-off -- a sequencer's notes longer than its -; step -- strikes again in off, and is tied into one long note in on and auto. Either way it -; ends at the LAST of its note-offs, not the first. -legato = off - -; Portamento: the pitch glides from one note to the next instead of jumping. 0 = none. -; t1 .. t50 = constant TIME: every glide takes the same time, whatever the interval. -; The curve is exponential -- fast at first, then settling into the note, -; the way an analog glide (a capacitor charging) sounds -- and it lands -; exactly on the note at the set time. -; r0 .. r50 = constant RATE: the pitch moves in a straight line at a fixed speed, so a -; wider interval takes longer. The time below is per octave: a fifth takes -; 7/12 of it, two octaves twice it. -; The scale is steep, finest at the short end. Glide time (t), or time per octave (r): -; 1 ~ 1 ms 5 ~ 6 ms 10 ~ 22 ms 20 ~ 135 ms 30 ~ 0.47 s 40 ~ 1.2 s 50 ~ 2.6 s -; (r0 is under 1 ms per octave: practically instant.) -portamento = 0 - -; Pitch bend range in semitones, 0-24. If the host sends its own bend range -; (RPN 0, "pitch bend sensitivity"), Wakes uses the host's until it is unplugged. -bend_range = 2 - -; The sustain pedal: cc N, or off. CC 64 is the standard pedal. -sustain = cc 64 - -; How long a CC takes to glide to a new value, in milliseconds (0-200). This is what -; turns a CC's steps into a smooth movement instead of zipper noise. Stepped parameters -; (OCTAVE range, MODEL, LENGTH, Y divider) do not glide: a step is the point. -cc_smoothing = 10 - -; How a CC and its fader share a parameter. All three use Plaits' own pickup ("catch-up"), -; the one its knobs use after a preset change: a control that does not match the value -; does not make it jump -- moving it moves the value the same way from where it is, a -; little faster or slower, until the two meet and it simply follows. -; -; sum = the CC is an OFFSET on top of the fader: fader + CC. A parameter whose -; middle is neutral reads its CC centred (64 = no change, 0 / 127 = half a -; travel down / up); any other reads it one-sided (0 = no change, 127 = a -; whole travel up); TIMBRE / MORPH / HARMONICS follow the engine, and when an -; engine change flips how one reads, the offset catches up instead of jumping. -; Unplug and every offset goes back to zero. -; shared = the CC and the fader are two hands on ONE value. A CC reads like the fader -; (0 = the bottom, 127 = the top). Whichever you move takes the value from -; where the other left it and catches up with your hand. -; takeover = while MIDI is plugged in, the faders that have a CC here REST, and only the -; CC moves the parameter (catching up with where the fader left it). Unplug and -; the faders work again, catching up with where the CC left it. -; -; In shared and takeover the CC moves the parameter itself: the fader LEDs show where the -; host put it, and it stays there when you unplug. A host knob's FIRST value after plugging -; in -- including the snapshot some hosts send when they connect -- only tells Wakes where -; the knob is; nothing moves until you turn it. -; MODEL has no fader, so it is an offset in every setting (see [plaits]), and so are the -; [bind] sources at the end of this file. -pickup = shared - -; MIDI clock and transport into Marbles: on, or off (ignore them). -; on = from the host's first clock tick (or Start), Marbles' clock IS the host's clock, -; like a cable in the Eurorack Marbles' CLOCK input. Marbles' RATE fader then picks a -; ratio of the host's beat instead of a tempo: 1/4, 1/3, 1/2, 2/3, 1, 3/2, 2, 3, 4 -; (Marbles' own table, centre = 1), times 4 or 1/4 with the t range. Start plays from -; beat 1, Continue carries on, Stop stops; PLAY still works too. MMC Play / Stop -; (MIDI Machine Control, what the OP-XY sends) work too: with MIDI clock arriving, -; Play waits for beat 1 like Start; without, it plays Marbles on its own RATE -; tempo. If the host stops -; sending clock, Marbles waits for it. Unplug, and Marbles stops and has its own -; clock again. Song Position Pointer is ignored. -; A DAW's clock arrives a few ms early or late on every tick: Wakes follows a -; straight line through the last two beats of ticks, not each tick, so Marbles' -; beats stay steady (under 1 ms of the +-8 ms in the ticks). -; Clock alone does not count as MIDI in use: the scale quantizer and F1's detent -; stay as they are. The FFWD burst follows the host's tempo too. -clock = on - -; How far ahead of the host's clock Marbles runs: notes, auto, or a number of ms (0-200). -; Wakes plays every sound about 8.5 ms after the MIDI that caused it (one 2 ms audio -; block to place the message on time, the audio queued ahead of the output, and Plaits' -; 0.5 ms TRIG delay). Notes cannot be played early, but a clock can: it is steady, so -; Wakes can read it ahead. -; notes (default) = Marbles' beats land with the host's NOTES. Hosts often send their -; clock later than their notes (Bitwig: ~23 ms), so following the clock alone puts -; Marbles late against the notes it modulates. Wakes measures where the host's notes -; fall on its clock -- quantised notes, every 5 s -- and leads by exactly that, so -; no clock offset is needed in the host. Until notes arrive (or with notes off the -; grid: swing, triplets, playing by hand) it uses auto. The console's "MIDI notes vs -; clock" line shows the measurement and the lead in use. -; auto = Wakes' own delay (8.5 ms): Marbles' beats leave the output when the clock's do. -; While the host is recording Wakes over USB audio, that output is 1 ms later, and -; auto (and notes, until it has measured) follows it: 9.5 ms. -; A number: that many ms, for a host whose clock offset you would rather set here. -; With notes or auto, leave the host's own clock offset / sync delay for Wakes at 0. -; Beat 1 after a Start is the exception: nothing said when it would come, so it sounds -; on arrival and Marbles is on time from beat 2. -clock_lead = notes - - -; ------------------------------------------------------------------------------------- -; The parameters, and which CC moves each one. name = cc N (or none) -; -; CC 0-31 are 14-bit: Wakes also listens to their partner CC N+32 for the fine half of -; the value, which is how a host sends high-resolution CCs. A host that only sends the -; coarse half still works. Any other CC is 7-bit (128 steps), smoothed. -; -; The defaults below use only CC numbers that keyboards and DAWs do not send on their -; own (the undefined ones, and General Purpose 1-4 = CC 16-19), so out of the box -; nothing moves until you point something at it. The mod wheel (1), breath (2), foot -; (4), portamento time (5) and expression (11) are deliberately left free for you. -; -; Not allowed, because MIDI already uses them: CC 0/32 (bank select), 6/38 and 96-101 -; (data entry and parameter numbers -- needed for the host's bend range), 120-127 -; (channel mode messages), and whatever CC the sustain pedal is on. CC 33-63 are the fine -; halves of CC 1-31: give the parameter CC N, and N+32 comes with it. A CC may move only -; one parameter. -; -; How a CC reads depends on `pickup` (above): in shared and takeover it is the fader's -; position (0 = bottom, 127 = top); in sum it is an offset, centred or one-sided. -; ------------------------------------------------------------------------------------- - -[plaits] -; BASE page -timbre = cc 3 -morph = cc 9 -harmonics = cc 14 -frequency = cc 15 -; SHIFT page: the four attenuverters -fm_attenuverter = cc 20 -timbre_attenuverter = cc 21 -morph_attenuverter = cc 22 -harmonics_attenuverter = cc 23 -; SETTINGS page -lpg_colour = cc 24 -lpg_decay = cc 25 -level = cc 26 ; can connect LEVEL, as pushing the fader up does -octave_range = cc 102 ; stepped: whole range modes -; Not on a fader at all: which engine plays, as an offset from the one T2/T3 selected, -; up through the filled slots of config/engines.csv (0 = the selected engine, 127 = the -; last slot). A change plays the engine flash, as T2/T3 do, and MIDI changes the engine at -; most every 50 ms -- each change costs the audio a moment, as a T2/T3 press does. -model = cc 105 - -[marbles] -; t page -rate = cc 27 -t_bias = cc 16 -jitter = cc 85 -deja_vu = cc 31 -; t SHIFT page -gtlt = cc 89 ; t gate tilt -gate_length = cc 17 -gate_length_random = cc 86 -length = cc 103 ; stepped -; X page -spread = cc 28 -x_bias = cc 29 -steps = cc 30 -; SETTINGS (Y) page -y_spread = cc 18 -y_bias = cc 19 -y_steps = cc 87 -y_divider = cc 104 ; stepped - - -; ------------------------------------------------------------------------------------- -; Extra sources. -; -; velocity = [depth%] how hard each note was played -; aftertouch = [depth%] channel pressure -; -; is any name from the two lists above, and the depth is -100% .. 100% -; (default 100%). The source pushes that parameter up from where it is, by up to its -; whole travel at 100% -- an offset, whatever `pickup` says. -; -; Aimed at `level`, it sets how far each note opens LEVEL instead, which Plaits also reads -; as accent: soft notes are quieter AND darker, as on the module with a velocity CV in -; LEVEL. At 100% the hardest note opens it fully and the softest barely at all; at 50% -; the softest still opens it half way. It shapes MIDI notes only: once a note's release -; has ended, LEVEL is the fader's again, as it is for RWD, FFWD and Marbles' TRIG. -; To play every note at full LEVEL, comment out the velocity line. -; -; You can also do this on the host instead: most DAWs can turn velocity or pressure -; into a CC, and aim it at the CC of the parameter you want. -; ------------------------------------------------------------------------------------- - -[bind] -velocity = level -; aftertouch = timbre 50% diff --git a/docs/DEFAULTS.md b/docs/DEFAULTS.md index 74516f8..ed6f4d2 100644 --- a/docs/DEFAULTS.md +++ b/docs/DEFAULTS.md @@ -33,11 +33,12 @@ than a description; it is now both.) | | parameter | range | boot | ROTC | notes | |---|---|---|---|---|---| | F1 | FREQUENCY | per OCTAVE range | **the fader's position** | fader set to 0.5, or C4, frequency unlocked (see SETTINGS F1 on ROTC) | Seeded from the physical fader on the first ON after boot only | -| F2 | TIMBRE | 0…1 | the fader's position | slot 1's neutral position (contextual to the engine) | meaning is per engine | -| F3 | MORPH | 0…1 | the fader's position | slot 1's neutral position (contextual to the engine) | meaning is per engine | -| F4 | HARMONICS | 0…1 | the fader's position | slot 1's neutral position (contextual to the engine) | meaning is per engine | +| F2 | TIMBRE | 0…1 | the fader's position | the neutral position of the first filled slot's engine | meaning is per engine | +| F3 | MORPH | 0…1 | the fader's position | the neutral position of the first filled slot's engine | meaning is per engine | +| F4 | HARMONICS | 0…1 | the fader's position | the neutral position of the first filled slot's engine | meaning is per engine | -**ROTC is a full patch reset, not a modulation reset.** It returns the engine to slot 1 and the +**ROTC is a full patch reset, not a modulation reset.** It returns the engine to the first +filled slot of the engine stack (#52: of your `engines.cnfg`, slot 1 by default) and the four BASE faders to that engine's neutral state: **0.5 for a bipolar parameter, 0 for a unipolar one**, and F1 to the middle of its travel with the range open and the quantizer off. @@ -48,7 +49,7 @@ detent means it is a real landing spot rather than a coincidence of fader positi **Which parameters are bipolar is already known per engine**, so nothing new has to be decided: each engine's detents (listed in `docs/PLAITS-ENGINES.md`) mark exactly the parameters whose centre is a neutral point, and they are compiled into `SP1_ENGINE_TABLE[].centre`. On virtual -analog, slot 1 by default, that gives F2 β†’ 0.5, F3 β†’ 0, F4 β†’ 0.5. +analog, the first filled slot by default, that gives F2 β†’ 0.5, F3 β†’ 0, F4 β†’ 0.5. ⚠️ **REVIEW 1 β€” the faders will not match after a ROTC, by design.** ROTC sets the stored values; the physical faders stay where your hands left them. Pickup then catches each one up on its next @@ -57,7 +58,7 @@ after a ROTC the instrument sounds neutral while the faders still look wrong. Th is the only way to do it without motorised faders. Confirmed as intended (Adara). ⚠️ **REVIEW 2 β€” neutral is per engine, and ROTC is a moment in time.** Because ROTC also returns -you to slot 1, "the engine's neutral state" is unambiguous at the moment it fires. But if you then +you to the first filled slot, "the engine's neutral state" is unambiguous at the moment it fires. But if you then step to an engine with a different bipolar set, the values stay where ROTC put them and are no longer that engine's neutral. The alternative β€” re-neutralising on every engine change β€” would mean losing your patch just by browsing engines, which is clearly worse. Leaving it as a @@ -87,7 +88,7 @@ Never seeded from the faders, at boot or ever. Gain 0 means nothing modulates un | parameter | range | boot | ON | ROTC | notes | |---|---|---|---|---|---| -| engine | 24 slots, 21 filled by default | slot 1 | β€” | slot 1 | the first filled slot of `config/engines.csv` | +| engine | 24 slots, 16 filled by default | the first filled slot | β€” | the first filled slot | of the stack in `WAKES/CNFG/engines.cnfg` on the drive, or the built-in `config/engines.cnfg` | | FREQUENCY quantization | off + 7 scales | off | β€” | off | forced off when something is routed to V/Oct | | output select | OUT / AUX / OUT+AUX / OUTΓ—AUX | OUT | OUT | OUT | RAM only | | soft-clip drive | off, +3 / +8 / +15 / +24 dB | off | off | off | forced off on every entry to ON (this will change when ON is set to reload savestates in M5). Uneven steps since M4e; `β€’β€’`+VOLβˆ’ steps DOWN rather than toggling | diff --git a/docs/MARBLES-SETTINGS.md b/docs/MARBLES-SETTINGS.md index e16129a..060e1ed 100644 --- a/docs/MARBLES-SETTINGS.md +++ b/docs/MARBLES-SETTINGS.md @@ -4,10 +4,10 @@ The Marbles-side companion to `docs/PLAITS-ENGINES.md`: everything that is a *ch than a fader, what each choice does, the LED glyph that flashes when you change it, and whether it is included in the firmware. -⚠️ **This file is NOT read by the build**, unlike `config/engines.csv` for Plaits. The tables below are the +⚠️ **This file is NOT read by the build**, unlike `config/engines.cnfg` for Plaits. The tables below are the authority for what the firmware *should* do; `firmware/src/sp1_marbles_ui.c` holds the same glyphs and inclusion flags in C. If a third consumer ever appears, generate them from here the -way `tools/gen_engines.py` generates the engine list from `config/engines.csv` β€” until then, changing a glyph or an +way `tools/gen_engines.py` generates the engine list from `config/engines.cnfg` β€” until then, changing a glyph or an inclusion flag means changing both. ## LED glyphs diff --git a/docs/MIDI.md b/docs/MIDI.md index 5ebed7e..5a73dc1 100644 --- a/docs/MIDI.md +++ b/docs/MIDI.md @@ -5,15 +5,16 @@ class-compliant **USB-MIDI** port called `Wakes` β€” no driver. It listens; it d (Through v0.6.x the port was called `wakes-sp1`: re-select it once in your DAW or host.) Nothing about it needs setting up on the device, and there are **no new pages**: notes play -Plaits straight away, and everything deeper is set in the MIDI script, -[`config/midi.ini`](../config/midi.ini), before the firmware is built. +Plaits straight away, and everything deeper is set in the MIDI script, `midi.cnfg`, on +Wakes' own drive (`WAKES/CNFG/midi.cnfg`): edit it from a computer, and Wakes reads it at the +next ON. ## What MIDI does | | | |---|---| -| **Notes** | play Plaits. A note-on strikes **TRIG** and holds **LEVEL** open β€” as far as the note's **velocity** says, out of the box, so soft notes are quieter and darker (Plaits reads LEVEL as accent too); a note-off lets LEVEL close through Plaits' own low-pass gate, so the release is the LPG's. | -| **Several keys** | Plaits is one voice: you hear the **newest** key. Let it go and you hear the previous one if it is still held. (`note_priority` in the script can make it the lowest or the highest key held instead.) The same pitch played again before its note-off -- a sequencer's notes longer than its step -- strikes again with `legato = off` and is tied into one long note with `on` / `auto`; it ends at its **last** note-off. Even a note shorter than a quarter of a millisecond opens the gate. | +| **Notes** | play Plaits, on **any channel** out of the box (`channel = omni`). A note-on strikes **TRIG** and holds **LEVEL** fully open β€” velocity changes nothing out of the box; `[bind]` can aim it at LEVEL so soft notes are quieter and darker (Plaits reads LEVEL as accent too). A note-off lets LEVEL close through Plaits' own low-pass gate, so the release is the LPG's. | +| **Several keys** | Plaits is one voice: you hear the **newest** key. Let it go and you hear the previous one if it is still held. (`note_priority` in the script can make it the lowest or the highest key held instead.) Out of the box (`legato = auto`, `portamento = t9`) a key played while another is held **glides** to its pitch in about 18 ms without a new strike, and a key played after letting go strikes and jumps straight to its note. The same pitch played again before its note-off -- a sequencer's notes longer than its step -- strikes again with `legato = off` and is tied into one long note with `on` / `auto`; it ends at its **last** note-off. Even a note shorter than a quarter of a millisecond opens the gate. | | **Pitch** | added to FREQUENCY like a V/Oct cable, with **note 60 (C4) adding nothing**. F1 on its centre detent is exactly C4, so a centred F1 plays the keyboard at its real pitch, and moving F1 transposes. While MIDI is in use the FREQUENCY detent is **10 %** of the fader's travel (5 % otherwise), so C4 is easy to land on. | | **Pitch bend** | Β±2 semitones, or whatever range the host sends (RPN 0, "pitch bend sensitivity"). | | **Sustain pedal** | CC 64 holds released notes until it lifts. | @@ -168,7 +169,7 @@ half still works. | 25 | 57 | LPG decay | | 26 | 58 | LEVEL (PLAITS SETTINGS F4 β€” can connect it, like the fader) | | 102 | | OCTAVE range | -| 105 | | MODEL: the engine, as an offset up through your filled slots in `config/engines.csv` | +| 105 | | MODEL: the engine, as an offset up through your filled slots in `config/engines.cnfg` | | 27 | 59 | RATE | | 16 | 48 | t BIAS | | 85 | | JITTER | @@ -195,21 +196,31 @@ Left free on purpose, for your own script: CC 1 (mod wheel), 2 (breath), 4 (foot ## Changing it: the MIDI script -[`config/midi.ini`](../config/midi.ini) is commented line by line. In a fork, edit it β€” GitHub's -web editor is enough β€” and the CI build of your fork produces a `.bin` with your settings. -The build **refuses** a script with a mistake in it and names the line, so a typo cannot become a -firmware that quietly ignores you. +`midi.cnfg` is commented line by line. It lives on Wakes' drive: plug Wakes into a computer +while it is off (STANDBY), open `WAKES/CNFG/midi.cnfg` in a text editor, save, and turn Wakes +ON β€” it reads the file at every ON. If the file is not there, Wakes writes it there with the +built-in settings, commented (so deleting it resets it at the next ON); the built-in default is [`config/midi.cnfg`](../config/midi.cnfg) in this repository, which is also +where to get a clean copy. + +- Every line can be left out: it keeps its default. +- A line Wakes cannot read keeps its default too, and the log (`WAKES/LOGS/`) names the line + and what is wrong with it. +- **A CC you give a parameter is taken from whichever parameter had it by default**, which then + has none (the log notes it). **Two of your own lines on the same CC: the first keeps it**, the + later one gets none (the log says so). CC 33–63 (the fine halves) and MIDI's reserved CCs + cannot be given. +- The CC chart that comes with each release lists the built-in CCs; your file may change them. What it sets: -- `channel` β€” 1–16, or `omni`. +- `channel` β€” 1–16, or `omni` (default: every channel). - `note_priority` β€” `last` (default), `low` or `high`. -- `legato` β€” `off` (every new note strikes; the default), `on` (a note played over a held one - slides without striking), `auto` (as `on`, with portamento only between overlapping notes, - so playing legato glides and playing detached jumps). +- `legato` β€” `off` (every new note strikes), `on` (a note played over a held one slides + without striking), `auto` (the default: as `on`, with portamento only between overlapping + notes, so playing legato glides and playing detached jumps). - `portamento` β€” `0`, `t1`–`t50` (constant time, an exponential glide), `r0`–`r50` (constant rate, a straight line, timed per octave). From about 1 ms up to about 2.6 s; - the script lists the steps. + the script lists the steps. The default is `t9`, about 18 ms. - `bend_range` β€” 0–24 semitones, until the host sends its own. - `sustain` β€” `cc N`, or `off`. - `cc_smoothing` β€” 0–200 ms: how long a CC glides to a new value. This is what turns a CC's @@ -223,8 +234,9 @@ What it sets: - `[bind]` β€” `velocity` and `aftertouch` (channel pressure) can push a parameter by a depth (`velocity = timbre 40%`). Aimed at `level`, they set how far each note opens LEVEL β€” which Plaits also reads as accent, so soft notes are quieter and darker. **The shipped - script has `velocity = level`** (100 %: the softest note barely opens it; at 50 % the - softest still opens it half way). Comment that line out to play every note at full LEVEL. + script has `velocity = none` and `aftertouch = none`**: every note opens LEVEL fully. Write + `velocity = level` for velocity on LEVEL (100 %: the softest note barely opens it; at 50 % + the softest still opens it half way; at 0 % velocity does nothing). You can also do this on the host instead: most DAWs can turn velocity or pressure into a CC and aim it at one of the CCs above. diff --git a/docs/PLAITS-ENGINES.md b/docs/PLAITS-ENGINES.md index eb4756f..6007bc6 100644 --- a/docs/PLAITS-ENGINES.md +++ b/docs/PLAITS-ENGINES.md @@ -1,33 +1,51 @@ # Plaits engines β€” choosing them, glyphs, detents -**Which engine sits in which slot is set in [`config/engines.csv`](../config/engines.csv)**, not in -this document. The build reads that file every time. This page is reference: what each engine is, -what it costs, and what each fader does on it. - -## Choosing engines: `config/engines.csv` - -The file has one row per slot, 24 at most, in slot order. T2/T3 step through the slots in that -order. The device starts on the first slot that has an engine, and "rip out the cables" returns -there. - -| column | what it is | can you change it? | -|---|---|---| -| **Slot** | the slot number. It's the row's position, printed so the file reads like the device. | No | -| **Glyph** | the four-LED pattern flashed when the slot is selected, T1 first. It belongs to the slot, not to the engine in it. | No | -| **Engine** | the engine in that slot, named exactly as under "Available engines" below (upper/lower case doesn't matter). **Leave it empty** for an empty slot, which T2/T3 skip. | **Yes** | - -- **To remove an engine**, clear its Engine cell. The slot stays and is skipped. -- **To add one**, type its name into an empty slot's Engine cell. -- **To reorder**, move the engine names between rows. Don't move whole rows: the Slot and Glyph - columns have to stay where they are. - -Each engine can appear once. Open the file in a spreadsheet or a text editor; GitHub shows it as -a table. If the file is wrong, for example a glyph edited or a whole row moved, the build stops -with a message naming the line and saying what's expected there. -`python tools/gen_engines.py --list` prints every engine name the file may use. +**Which engine sits in which slot is set in [`config/engines.cnfg`](../config/engines.cnfg)**, not +in this document. The build reads that file every time, and it also describes every engine and +what its faders do. This page is reference: what each engine is, what it costs, and why the +detents are where they are. + +## Choosing engines: `config/engines.cnfg` + +An ini file (#52): one line per slot under `[engines]`, `slot = engine`, slots 1–24. T2/T3 step +through the slots in order and skip empty ones. The device starts on the first filled slot, and +"rip out the cables" returns there. + +```ini +[engines] +1 = virtual-analog ; ●○○○ +2 = waveshaping ; ●●○○ +... +17 = ; ◐◐◐◐ +``` + +- **The file is the whole stack.** A slot with no name, `none`, or no line at all is empty. +- **To remove an engine**, clear its name. **To add one**, write its name after an empty slot's + `=`. **To reorder**, move names between slots β€” not whole lines: each slot keeps its glyph. +- Names are written as in the file's engine list, with hyphens instead of spaces (`virtual-analog`, + `grain-formant`, `VA-VCF`); case doesn't matter. Each engine can appear once. +- The glyph after the `;` is a comment showing the slot's glyph. The build checks it, so a line + moved together with its glyph is caught. +- Engine names match on their letters and digits, case ignored: `grain-formant`, `grain / formant` + and `Grain Formant` are one engine (so PRST files saved under an older spelling still load). + `python tools/gen_engines.py --list` prints every engine name the file may use. Leaving an engine out removes it from engine select. It does **not** make the firmware smaller: -Plaits' voice object contains every engine regardless. +Plaits' voice object contains every engine regardless, and a PRST preset that names an engine not +in the stack still plays it (its flash is all four LEDs fading down instead of a glyph). + +**Two copies, two kinds of check** (#52): + +- **On the drive, `WAKES/CNFG/engines.cnfg`** β€” the one users edit. Wakes reads it at every ON, + before the PRST slots. A stack is all or nothing: if the file is missing, unreadable, or has + any problem β€” a name that is not an engine, an engine twice, a slot outside 1–24 or set twice, + another section, no engine at all β€” Wakes plays the **built-in stack** and the log names every + problem line (`CNFG engines.cnfg line N: …`). ROTC and the start go to the first filled slot of + whichever stack is in use. If the file is not there, Wakes writes it there with the + built-in stack and the engine descriptions (so deleting it resets it at the next ON). +- **In the repository, `config/engines.cnfg`** β€” the built-in stack every image carries, and the + file fresh writes. The build checks it and stops on any problem, naming the line, so a broken + default can never ship. ### Glyphs @@ -40,50 +58,47 @@ recognisable, not counted in binary: full brightness for slots 1–16, half brig | `◐` | `+` | half brightness (`SP1_ENGINE_LED_HALF` in `firmware/src/sp1_ui_timing.h`) | | `β—‹` | `.` | off | -Save the file as UTF-8. If a spreadsheet or editor turns the circles into `?` or garbage, the -build will say so; write the glyphs in their ASCII forms instead (`#..#` is the same glyph as -`●○○●`). - Slot 16's glyph is `β—‹β—‹β—‹β—‹` (all off); its flash shows as a brief dark blink. ### What you can't change here Each slot's **glyph**, and each engine's **index inside Plaits** and **centre detents**, are fixed, -so the CSV can't change them. They live in `SLOT_GLYPHS` and `PLAITS_ENGINES` in +so the file can't change them. They live in `SLOT_GLYPHS` and `PLAITS_ENGINES` in `tools/gen_engines.py`. The reasons for each detent are under "Why these detents" below. ## Available engines -The default `config/engines.csv` has the 16 original Plaits models first, in their panel order, -then five of the 8 models added in Plaits 1.2. Slots 22–24 are empty: the three **6-op FM** banks -are left out (a community DX7 firmware covers them), but any of them can go in an empty slot. +The default stack is the 16 original Plaits models, in their panel order, in slots 1–16 (Adara, +#52). Slots 17–24, the half-lit glyphs, are empty for you to fill: the five models added in +Plaits 1.2 (VA-VCF, phase-distortion, wave-terrain, string-machine, chiptune) and the three +**6-op FM** banks (6-op-FM-A, -B, -C) are out of the default stack, but any of them can go in an empty slot. | Default slot | Engine | Plaits # | Detents | CPU (avg; M3b–M3f logs) | |---|---|---|---|---| -| 1 | virtual analog | 8 | F2 F4 | 67.8 % | +| 1 | virtual-analog | 8 | F2 F4 | 67.8 % | | 2 | waveshaping | 9 | F4 | 52.2 % (61 % peak) | -| 3 | 2-op FM | 10 | F3 | 70.5 % (76 % peak) | -| 4 | grain / formant | 11 | F4 | 75.7 % | +| 3 | 2-op-FM | 10 | F3 | 70.5 % (76 % peak) | +| 4 | grain-formant | 11 | F4 | 75.7 % | | 5 | additive | 12 | - | M3f: 54.8 % (64 % peak); M4a: est. ~61 % / ~71 % | | 6 | wavetable | 13 | - | 63.4 % | | 7 | chords | 14 | - | 76.6 % | | 8 | speech | 15 | - | 27–39 % (varies with MORPH/HARMONICS) | | 9 | swarm | 16 | - | 73.9 % | -| 10 | filtered noise | 17 | F4 | 64.7 % | +| 10 | filtered-noise | 17 | F4 | 64.7 % | | 11 | particle | 18 | F3 | 86.5 % at 6; M3f (3): 49–51 % avg, 83–100 % peaks below MORPH centre; M4: 2 particles | | 12 | string | 19 | - | 68.9 % (74 % peak) at 2 strings (M3f) | | 13 | modal | 20 | - | 49.1 % (54 % peak) at 8 modes (M3f); M3g: 12, est. ~65 % | -| 14 | bass drum | 21 | - | 67.1 % | -| 15 | snare drum | 22 | - | 68.3 % | +| 14 | bass-drum | 21 | - | 67.1 % | +| 15 | snare-drum | 22 | - | 68.3 % | | 16 | hi-hat | 23 | - | 71.4 % | -| 17 | VA + VCF | 0 | F3 F4 | 66.4 % | -| 18 | phase distortion | 1 | - | 72.1 % | -| 19 | wave terrain | 5 | F3 | 62.6 % (one window) | -| 20 | string machine | 6 | F2 | 84.4 % (~98 % peak); M3g/M4: est. ~61 % at TIMBRE centre, ~76 % with the 2-tap chorus | -| 21 | chiptune | 7 | - | 27.7 % (one window) | -| β€” | 6-op FM A | 2 | F3 | ~78 % (one window) | -| β€” | 6-op FM B | 3 | F3 | not measured | -| β€” | 6-op FM C | 4 | F3 | not measured | +| β€” | VA-VCF | 0 | F3 F4 | 66.4 % | +| β€” | phase-distortion | 1 | - | 72.1 % | +| β€” | wave-terrain | 5 | F3 | 62.6 % (one window) | +| β€” | string-machine | 6 | F2 | 84.4 % (~98 % peak); M3g/M4: est. ~61 % at TIMBRE centre, ~76 % with the 2-tap chorus | +| β€” | chiptune | 7 | - | 27.7 % (one window) | +| β€” | 6-op-FM-A | 2 | F3 | ~78 % (one window) | +| β€” | 6-op-FM-B | 3 | F3 | not measured | +| β€” | 6-op-FM-C | 4 | F3 | not measured | The Plaits # and Detents columns are copied from `tools/gen_engines.py` for reference; that file, not this table, is what the build uses. @@ -104,18 +119,18 @@ rather than with Plaits alone. | Plaits # | slot | engine | avg % (M4a–M4d hardware) | column above | |---|---|---|---|---| -| 5 | 19 | wave terrain | **82.3** | 62.6 % "one window" | -| 7 | 21 | chiptune | 73.7 | 27.7 % "one window" | -| 8 | 1 | virtual analog | 56.5 | 67.8 % | +| 5 | β€” | wave-terrain | **82.3** | 62.6 % "one window" | +| 7 | β€” | chiptune | 73.7 | 27.7 % "one window" | +| 8 | 1 | virtual-analog | 56.5 | 67.8 % | | 9 | 2 | waveshaping | 55.9 | 52.2 % | | 12 | 5 | additive | 67.4 | M4a est. ~61 % | | 13 | 6 | wavetable | 73.9 | 63.4 % | | 16 | 9 | swarm | **79.5** | 73.9 % | -| 17 | 10 | filtered noise | 66.1 | 64.7 % | +| 17 | 10 | filtered-noise | 66.1 | 64.7 % | | 18 | 11 | particle | 47.6 | M3f (3 particles) 49–51 %; this build has 2 | | 19 | 12 | string | 71.3 | 68.9 % at 2 strings | | 20 | 13 | modal | 73.0 | M3g est. ~65 % at 12 modes | -| 21 | 14 | bass drum | 75.3 | 67.1 % | +| 21 | 14 | bass-drum | 75.3 | 67.1 % | | 23 | 16 | hi-hat | 77.0 | 71.4 % | **Everything fits.** The heaviest is wave terrain at 82.3 %, and an hour of playing produced no @@ -146,28 +161,28 @@ its range set by SETTINGS F1. Only F2–F4 change meaning with the engine. | Default slot | Engine | F2 TIMBRE | F3 MORPH | F4 HARMONICS | AUX (SETTINGS T4) | |---|---|---|---|---|---| -| 1 | virtual analog | variable square, from narrow pulse to full square to hardsync formants | variable saw, from triangle to saw with an increasingly wide notch | detuning between the two waves | sum of two hardsync'ed waveforms, shaped by MORPH | +| 1 | virtual-analog | variable square, from narrow pulse to full square to hardsync formants | variable saw, from triangle to saw with an increasingly wide notch | detuning between the two waves | sum of two hardsync'ed waveforms, shaped by MORPH | | 2 | waveshaping | wavefolder amount | waveform asymmetry | waveshaper waveform | the same, with Warps' other wavefolder curve | -| 3 | 2-op FM | modulation index | feedback β€” operator 2 modulating its own phase, or operator 1's | frequency ratio | sub-oscillator | -| 4 | grain / formant | formant frequency | formant width and shape (the window's shape) | frequency ratio between formant 1 and 2 | filtered waveforms simulated by windowed sine waves | +| 3 | 2-op-FM | modulation index | feedback β€” operator 2 modulating its own phase, or operator 1's | frequency ratio | sub-oscillator | +| 4 | grain-formant | formant frequency | formant width and shape (the window's shape) | frequency ratio between formant 1 and 2 | filtered waveforms simulated by windowed sine waves | | 5 | additive | index of the most prominent harmonic β€” a bit like a cutoff frequency | bump shape, from flat and wide to peaked and narrow | number of bumps in the spectrum, starting with one big bump | only the harmonics a Hammond organ's drawbars have | | 6 | wavetable | row index β€” waves sorted by spectral brightness | column index | active bank | low-fi (5-bit) output | | 7 | chords | chord inversion and transposition | waveform: string-machine waveforms below the centre, a wavetable scan above | chord type | the chord's root note | | 8 | speech | species, from Daleks to chipmunks | phoneme or word-segment selection | crossfades formant filtering β†’ SAM β†’ LPC vowels, then banks of LPC words | the unfiltered vocal cords' signal | | 9 | swarm | grain density | grain duration and overlap; at the top the grains merge into each other | amount of pitch randomisation | the same, with sine-wave oscillators | -| 10 | filtered noise | clock frequency | filter resonance | filter response, LP β†’ BP β†’ HP | two band-pass filters, separation set by HARMONICS | +| 10 | filtered-noise | clock frequency | filter resonance | filter response, LP β†’ BP β†’ HP | two band-pass filters, separation set by HARMONICS | | 11 | particle | particle density | filter type: a reverberating all-pass network below the centre, resonant band-pass filters above | amount of frequency randomisation | raw dust noise | | 12 | string | excitation brightness, and the dust density while it drones | decay time (energy absorption) | inharmonicity: dispersive below ~25 % of travel, stiff above, harmonic in the small dead band between | the raw exciter signal | | 13 | modal | excitation brightness and dust density | decay time (energy absorption) | amount of inharmonicity, or material | the raw exciter signal | -| 14 | bass drum | brightness | decay time | attack sharpness and amount of overdrive | a frequency-modulated triangle VCO turned into a sine by diodes | -| 15 | snare drum | balance between the drum's modes | decay time | balance of the harmonic and noisy components | two frequency-modulated sine VCOs mixed with high-passed noise | +| 14 | bass-drum | brightness | decay time | attack sharpness and amount of overdrive | a frequency-modulated triangle VCO turned into a sine by diodes | +| 15 | snare-drum | balance between the drum's modes | decay time | balance of the harmonic and noisy components | two frequency-modulated sine VCOs mixed with high-passed noise | | 16 | hi-hat | high-pass filter cutoff | decay time | balance of the metallic and the filtered noise | three pairs of square oscillators ring-modulating each other, through a clean linear VCA | -| 17 | VA + VCF | filter cutoff | waveform and sub level | resonance and filter character β€” gentle 24 dB/oct below the centre, harsh 12 dB/oct above | the 12 dB/oct high-pass output | -| 18 | phase distortion | distortion amount | distortion asymmetry | distortion frequency | the carrier runs free, making it phase modulation | -| 19 | wave terrain | path radius | path offset | terrain | the terrain's height read as phase distortion, sin(y+z) | -| 20 | string machine | chorus / filter amount | waveform | chord | voices 2 and 4, mostly | -| 21 | chiptune | arpeggio type, or chord inversion | pulse width / sync | chord | the NES triangle voice | -| β€” | 6-op FM A/B/C | modulator level(s) | envelope and modulation stretching ("time travel") | preset selection, within this bank | the same signal as OUT | +| β€” | VA-VCF | filter cutoff | waveform and sub level | resonance and filter character β€” gentle 24 dB/oct below the centre, harsh 12 dB/oct above | the 12 dB/oct high-pass output | +| β€” | phase-distortion | distortion amount | distortion asymmetry | distortion frequency | the carrier runs free, making it phase modulation | +| β€” | wave-terrain | path radius | path offset | terrain | the terrain's height read as phase distortion, sin(y+z) | +| β€” | string-machine | chorus / filter amount | waveform | chord | voices 2 and 4, mostly | +| β€” | chiptune | arpeggio type, or chord inversion | pulse width / sync | chord | the NES triangle voice | +| β€” | 6-op-FM-A/B/C | modulator level(s) | envelope and modulation stretching ("time travel") | preset selection, within this bank | the same signal as OUT | Sources: the Plaits manual's model table for F2–F4 and AUX, and the firmware 1.2 release notes for the 1.2 models (VA + VCF onwards, and 6-op FM). **String is the one the manual never documented** β€” its row is read @@ -176,7 +191,7 @@ argument (non-linearity is `(sβˆ’0.24)Β·4.166` below 0.24, `(sβˆ’0.26)Β·1.35` ab between), TIMBRE is `brightness` squared, and MORPH is `damping`. The 6-op FM banks' AUX is `aux[i] = out[i]` in `six_op_engine.cc`, i.e. the two outputs carry the same thing. -The rows follow the default slot order. Your own `config/engines.csv` may order them +The rows follow the default slot order. Your own `config/engines.cnfg` may order them differently; the per-engine descriptions don't change. ## Why these detents @@ -190,15 +205,15 @@ itself changes: | engine | detent | centre means (source) | |---|---|---| -| VA + VCF | F4, F3 | F4: resonance = max(\|hβˆ’.5\|βˆ’.125, 0), so the centre is zero resonance (24 dB/oct below, 12 dB/oct above). F3: the centre is a plain square with no sub-oscillator. | +| VA-VCF | F4, F3 | F4: resonance = max(\|hβˆ’.5\|βˆ’.125, 0), so the centre is zero resonance (24 dB/oct below, 12 dB/oct above). F3: the centre is a plain square with no sub-oscillator. | | 6-op FM Γ—3 | F3 | envelope time Γ— 2^((.5βˆ’m)Β·8): the centre is the patch's own envelopes. | -| wave terrain | F3 | path offset 1.9mβˆ’1: the centre is (almost exactly) a centred path. | -| string machine | F2 | ensemble amount \|tβˆ’.5\|Β·2: the centre is dry, with filter on one side and chorus on the other. | -| virtual analog | F4, F2 | F4: detune 2.05hβˆ’1.025, so the centre is unison. F2: square wave, no sync ("narrow pulse … full square … hardsync"). | +| wave-terrain | F3 | path offset 1.9mβˆ’1: the centre is (almost exactly) a centred path. | +| string-machine | F2 | ensemble amount \|tβˆ’.5\|Β·2: the centre is dry, with filter on one side and chorus on the other. | +| virtual-analog | F4, F2 | F4: detune 2.05hβˆ’1.025, so the centre is unison. F2: square wave, no sync ("narrow pulse … full square … hardsync"). | | waveshaping | F4 | shape amount \|hβˆ’.5\|Β·2: the centre is no waveshaping. | -| 2-op FM | F3 | feedback 2mβˆ’1: the centre is no feedback ("before 12 o'clock, chaotic! past 12 o'clock, rough!"). | -| grain / formant | F4 | formant ratio βˆ’24+48h semitones: the centre is 1:1. | -| filtered noise | F4 | the 2nd filter sits at the same pitch as the 1st; response goes LP β†’ BP (centre) β†’ HP. | +| 2-op-FM | F3 | feedback 2mβˆ’1: the centre is no feedback ("before 12 o'clock, chaotic! past 12 o'clock, rough!"). | +| grain-formant | F4 | formant ratio βˆ’24+48h semitones: the centre is 1:1. | +| filtered-noise | F4 | the 2nd filter sits at the same pitch as the 1st; response goes LP β†’ BP (centre) β†’ HP. | | particle | F3 | all-pass network below the centre, resonant band-pass above; the centre is neither. | ⚠️ **The detents are also the unipolar/bipolar table.** A detent marks a parameter whose centre is diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 1cbe660..11eb25a 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -47,6 +47,13 @@ battery overnight, and a powered amp with no clock can murmur audibly. **8. Clear every LED before `SYSTEM_OFF`.** It freezes GPIO levels; anything still lit stays lit into sleep. +**9. Nothing the user can configure reaches the power path.** The config files on the +drive (`WAKES/CNFG/*.cnfg`, issue #52) are read at every ON and a user can put anything in +them. They never name power-off or its timings, the watchdog, the flash layout, or the USB +descriptors, and none of those is ever read from the drive. A bad line keeps its built-in +default; a file that crashes the device at ON can be deleted from a computer in STANDBY, +because drive mode never reads `CNFG/`. + Rules 1–5 and 7 are the "BIG FIVE" as established by the author of `chattock/sp1-tape-looper` on real hardware. We did not discover them; we are inheriting them, and they were expensive to find. diff --git a/docs/UI-PAGES.md b/docs/UI-PAGES.md index c3083a9..413ee03 100644 --- a/docs/UI-PAGES.md +++ b/docs/UI-PAGES.md @@ -126,7 +126,7 @@ So the combination space is exactly: **`β€’β€’` + one button**, on either ladder ⚠️ So FFWD now **re-triggers** the note Marbles is holding rather than making the sequence advance faster: a roll, not an arpeggio. Driving the clock at a subdivision instead is a separate option, parked for a community vote (Adara). -- **Engines off the list** (#50): every build contains all of Plaits' engines; `config/engines.csv` +- **Engines off the list** (#50): every build contains all of Plaits' engines; `config/engines.cnfg` only decides which ones T2/T3 reach. A PRST slot may name one that is not listed, and it plays. It has no glyph of its own, so its engine flash is all four face LEDs ramping 70 % β†’ 0 at 15.6 Hz for 0.7 s. From it, **T3 β†’ the first listed engine, T2 β†’ the last**; MIDI's MODEL CC counts from @@ -452,7 +452,7 @@ T2/T3 (`[F]` / `[G]`). | **Both outputs at once** | Plaits renders OUT and AUX every block and we pick one (or a mix) for a single mono speaker. SETTINGS T4's four modes are the whole of what one output can be. A second physical output is not available. | | **User data** | wavetables and DX7 patches loaded through the ear-jack. `plaits/user_data.h` is **shimmed away** because upstream's reads STM32 flash at an address that does not exist on this chip. | | **FINE TUNE** | exposed until M4a, removed: it only ever acted in octave-range mode 9, and mode 9 is the mode that quantizes F1 to whole octaves. | -| **6-op FM Γ—3** | compiled but left out of the default `config/engines.csv` (slots 22–24 are empty); a community DX7 firmware covers it. Type a name into an empty slot to get one. | +| **6-op FM Γ—3** | compiled but left out of the default `config/engines.cnfg` (slots 17–24 are empty); a community DX7 firmware covers it. Type a name into an empty slot to get one. | ### Marbles features not exposed diff --git a/docs/Wakes - Manual.pdf b/docs/Wakes - Manual.pdf index f7f2ae4..5be36a1 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 becb3c3..b0f71ae 100644 --- a/firmware/CMakeLists.txt +++ b/firmware/CMakeLists.txt @@ -16,29 +16,30 @@ project(wakes-sp1) # The USB device is ours since M5a (src/sp1_usbd.c, CONFIG_SP1_USB_* in Kconfig): Zephyr's # sample helper, included here through M4e, hard-codes Zephyr's test vendor ID. -# ---- the engine list: generated from config/engines.csv ---- -# The CSV is the USER's choice of engines, slots and glyphs; the facts about each engine -# (its index inside Plaits, its centre detents) live in tools/gen_engines.py and are not -# user-editable. The build fails with a message naming the line if the CSV is malformed. -set(SP1_ENGINES_CSV ${CMAKE_CURRENT_SOURCE_DIR}/../config/engines.csv) +# ---- the engine list: generated from config/engines.cnfg ---- +# The DEFAULT engine stack (ini, #52): which engine sits in which slot. Each slot's glyph and +# the facts about each engine (its index inside Plaits, its centre detents) live in +# tools/gen_engines.py and are not user-editable. The build fails, naming the line, if the +# file is wrong. +set(SP1_ENGINES_CNFG ${CMAKE_CURRENT_SOURCE_DIR}/../config/engines.cnfg) set(SP1_ENGINES_GEN ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_engines.py) set(SP1_ENGINES_H ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated/sp1_engines_gen.h) add_custom_command( OUTPUT ${SP1_ENGINES_H} - COMMAND ${Python3_EXECUTABLE} ${SP1_ENGINES_GEN} ${SP1_ENGINES_CSV} ${SP1_ENGINES_H} - DEPENDS ${SP1_ENGINES_CSV} ${SP1_ENGINES_GEN} - COMMENT "Generating the engine table from config/engines.csv" + COMMAND ${Python3_EXECUTABLE} ${SP1_ENGINES_GEN} ${SP1_ENGINES_CNFG} ${SP1_ENGINES_H} + DEPENDS ${SP1_ENGINES_CNFG} ${SP1_ENGINES_GEN} + COMMENT "Generating the engine table from config/engines.cnfg" ) add_custom_target(sp1_engines_gen DEPENDS ${SP1_ENGINES_H}) add_dependencies(app sp1_engines_gen) target_include_directories(app PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated) -# ---- the MIDI script (M5a): generated from config/midi.ini ---- +# ---- the MIDI script (M5a): generated from config/midi.cnfg ---- # Like the engine list: tools/gen_midi.py fails the build, naming the line, on anything # invalid. Generated in EVERY configuration, because the UI files read its enum even where # MIDI is compiled out (sp1_midi.h then stubs the calls). With MIDI in, it also writes this # build's CC chart next to the firmware: wakes-sp1-midi.md and .csv. -set(SP1_MIDI_INI ${CMAKE_CURRENT_SOURCE_DIR}/../config/midi.ini) +set(SP1_MIDI_CNFG ${CMAKE_CURRENT_SOURCE_DIR}/../config/midi.cnfg) set(SP1_MIDI_GEN ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_midi.py) set(SP1_MIDI_H ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated/sp1_midi_gen.h) set(SP1_MIDI_OUT ${SP1_MIDI_H}) @@ -50,28 +51,43 @@ if(CONFIG_SP1_MIDI) endif() add_custom_command( OUTPUT ${SP1_MIDI_OUT} - COMMAND ${Python3_EXECUTABLE} ${SP1_MIDI_GEN} ${SP1_MIDI_INI} ${SP1_MIDI_H} ${SP1_MIDI_CHART} - DEPENDS ${SP1_MIDI_INI} ${SP1_MIDI_GEN} - COMMENT "Generating the MIDI tables from config/midi.ini" + COMMAND ${Python3_EXECUTABLE} ${SP1_MIDI_GEN} ${SP1_MIDI_CNFG} ${SP1_MIDI_H} ${SP1_MIDI_CHART} + DEPENDS ${SP1_MIDI_CNFG} ${SP1_MIDI_GEN} + COMMENT "Generating the MIDI tables from config/midi.cnfg" ) add_custom_target(sp1_midi_gen DEPENDS ${SP1_MIDI_OUT}) add_dependencies(app sp1_midi_gen) -# ---- the audio settings: config/audio.ini -> sp1_audio_gen.h (M5c) ---- +# ---- the audio settings: config/audio.cnfg -> sp1_audio_gen.h (M5c) ---- # How sound leaves the device: USB audio out's level mode and the speaker while a host takes # it. Same rule as the MIDI script: a bad value fails the build, naming the line. -set(SP1_AUDIO_INI ${CMAKE_CURRENT_SOURCE_DIR}/../config/audio.ini) +set(SP1_AUDIO_CNFG ${CMAKE_CURRENT_SOURCE_DIR}/../config/audio.cnfg) set(SP1_AUDIO_GEN ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_audio.py) set(SP1_AUDIO_H ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated/sp1_audio_gen.h) add_custom_command( OUTPUT ${SP1_AUDIO_H} - COMMAND ${Python3_EXECUTABLE} ${SP1_AUDIO_GEN} ${SP1_AUDIO_INI} ${SP1_AUDIO_H} - DEPENDS ${SP1_AUDIO_INI} ${SP1_AUDIO_GEN} - COMMENT "Generating the audio settings from config/audio.ini" + COMMAND ${Python3_EXECUTABLE} ${SP1_AUDIO_GEN} ${SP1_AUDIO_CNFG} ${SP1_AUDIO_H} + DEPENDS ${SP1_AUDIO_CNFG} ${SP1_AUDIO_GEN} + COMMENT "Generating the audio settings from config/audio.cnfg" ) add_custom_target(sp1_audio_gen DEPENDS ${SP1_AUDIO_H}) add_dependencies(app sp1_audio_gen) +# ---- the logging defaults: config/logs.cnfg -> sp1_logs_gen.h (#52) ---- +# The built-in defaults the drive's WAKES/CNFG/logs.cnfg overrides, and the file's text for +# wakes-sp1-fresh to write there. A bad default fails the build, naming the line. +set(SP1_LOGS_CNFG ${CMAKE_CURRENT_SOURCE_DIR}/../config/logs.cnfg) +set(SP1_LOGS_GEN ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_logs.py) +set(SP1_LOGS_H ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated/sp1_logs_gen.h) +add_custom_command( + OUTPUT ${SP1_LOGS_H} + COMMAND ${Python3_EXECUTABLE} ${SP1_LOGS_GEN} ${SP1_LOGS_CNFG} ${SP1_LOGS_H} + DEPENDS ${SP1_LOGS_CNFG} ${SP1_LOGS_GEN} + COMMENT "Generating the logging defaults from config/logs.cnfg" +) +add_custom_target(sp1_logs_gen DEPENDS ${SP1_LOGS_H}) +add_dependencies(app sp1_logs_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). @@ -94,6 +110,7 @@ target_sources(app PRIVATE src/sp1_standby.c src/sp1_console.c src/sp1_logbuf.c + src/sp1_logring.c src/sp1_threads.c src/sp1_usbd.c src/sp1_controls.c @@ -107,7 +124,7 @@ target_sources(app PRIVATE # ---- M6 (#43): the eMMC and the FAT volume on it (src/sp1_store.h) ---- if(CONFIG_SP1_STORAGE) - target_sources(app PRIVATE src/sp1_emmc.c src/sp1_store.c) + target_sources(app PRIVATE src/sp1_emmc.c src/sp1_store.c src/sp1_cnfg.c) target_sources_ifdef(CONFIG_SP1_STORAGE_TEST app PRIVATE src/sp1_emmc_report.c) # ff.h, for FATFS and MKFS_PARM (Zephyr's fatfs module, ELMFAT interface). target_link_libraries(app PRIVATE ELMFAT) diff --git a/firmware/Kconfig b/firmware/Kconfig index 40abf54..0e2e044 100644 --- a/firmware/Kconfig +++ b/firmware/Kconfig @@ -182,12 +182,16 @@ config FS_FATFS_CUSTOM_MOUNT_POINTS config SP1_LOGBUF_KB int "Stored log, in KB of RAM" + default 16 if SP1_STORAGE default 96 range 4 160 help Everything printk writes is also kept in RAM, newest last, and played back when a terminal next opens the console -- so a session with the USB port in another host's - hands (the OP-XY) is not lost (src/sp1_logbuf.h). 96 KB is ~14 minutes of a session. + hands (the OP-XY) is not lost (src/sp1_logbuf.h). Since #52 the session also goes to + WAKES/LOGS/ on the drive every 5 s, so this only has to cover the gap between flushes + and the boot before the first ON: 16 KB, ~2 minutes of a session (96 KB before, and + still in an image without storage -- the fallback -- where RAM is all there is). config SP1_USB_THREADS_BELOW_AUDIO bool "Run Zephyr's USB threads below the audio thread (#32)" @@ -206,7 +210,8 @@ config SP1_MIDI help A USB-MIDI 1.0 port (feldd's class, third_party/feldd) next to the console. Notes play Plaits, CCs offset parameters on both modules, all configured by - config/midi.ini at build time. Costs nothing until a host sends something. + the MIDI script (config/midi.cnfg built in, WAKES/CNFG/midi.cnfg on the drive at + every ON). Costs nothing until a host sends something. n: no MIDI function on the USB device at all. config SP1_USB_AUDIO diff --git a/firmware/VERSION b/firmware/VERSION index 485e9ed..98240f4 100644 --- a/firmware/VERSION +++ b/firmware/VERSION @@ -1,5 +1,5 @@ VERSION_MAJOR = 0 VERSION_MINOR = 8 -PATCHLEVEL = 0 +PATCHLEVEL = 2 VERSION_TWEAK = 0 EXTRAVERSION = diff --git a/firmware/src/main.c b/firmware/src/main.c index cdb3ae4..bfbb85d 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -95,14 +95,15 @@ #include "sp1_prst.h" /* M6 (#50): the ROTC defaults main.c owns */ #include "sp1_release_guard.h" #include "sp1_midi.h" +#include "sp1_cnfg.h" /* the config types: midi.cnfg, audio.cnfg (#52) */ #endif #if defined(CONFIG_SP1_USB_AUDIO) #include "sp1_uac.h" -#include "sp1_audio_gen.h" /* config/audio.ini */ +#include "sp1_cnfg.h" /* struct sp1_audio_cfg: audio.cnfg, live (#52) */ #endif -/* ---- USB audio out's level (M5c; config/audio.ini [usb] level) ---- - * `parked`: while a host takes USB audio out (sp1_uac_live), VOL is set to audio.ini's +/* ---- USB audio out's level (M5c; audio.cnfg [usb] level) ---- + * `parked`: while a host takes USB audio out (sp1_uac_live), VOL is set to audio.cnfg's * parked_level and its buttons do nothing; when the host stops, VOL goes back to where the * user left it. Wakes has ONE output level for every output, so this parks the headphones * (and the speaker, if it is on) too -- deliberately: a separate USB level would be a second @@ -116,25 +117,29 @@ static int vol_saved; static int usb_parked_db(void) { - return SP1_AUDIO_USB_PARKED_DB; + return sp1_audio_config()->parked_db; } static void usb_level_park(bool usb_live) { - if (!SP1_AUDIO_USB_LEVEL_PARKED) { + const struct sp1_audio_cfg *ac = sp1_audio_config(); + /* Already parked when the settings changed (a new ON with `level = vol`): unpark. */ + if ((!ac->parked || !usb_live) && vol_parked) { + sp1_audio_level_step(vol_saved - sp1_audio_level_get()); + vol_parked = false; + printk("LEVEL back to step %d: no host takes USB audio out, VOL unlocked\n", + vol_saved); + return; + } + if (!ac->parked) { return; } if (usb_live && !vol_parked) { vol_saved = sp1_audio_level_get(); - sp1_audio_level_step(SP1_AUDIO_USB_PARKED_STEP - vol_saved); + sp1_audio_level_step((int)ac->parked_step - vol_saved); vol_parked = true; printk("LEVEL parked at %d dBFS: a host takes USB audio out, VOL locked" - " (config/audio.ini)\n", (int)SP1_AUDIO_USB_PARKED_DB); - } else if (!usb_live && vol_parked) { - sp1_audio_level_step(vol_saved - sp1_audio_level_get()); - vol_parked = false; - printk("LEVEL back to step %d: no host takes USB audio out, VOL unlocked\n", - vol_saved); + " (audio.cnfg)\n", (int)ac->parked_db); } } #else @@ -310,7 +315,7 @@ static void prst_glyph_levels(int slot, uint32_t t, uint8_t lv[4]) /* ---- the engine flash, for an engine on the list or off it (#50) ---- * On the list: its fixed glyph through sp1_display_engine(), as always. Off the list (a PRST - * slot loaded an engine engines.csv does not list): no glyph exists, so all four face LEDs + * slot loaded an engine engines.cnfg does not list): no glyph exists, so all four face LEDs * ramp 70 % -> 0 every SP1_OFFLIST_RAMP_MS for SP1_DISP_ENGINE_HOLD_MS, then the same fade * (Adara). Redrawn every tick by offlist_glyph_tick(); anything else that flashes the row * stops it (sp1_display_flash_count). Use this wherever the ENGINE glyph is shown. */ @@ -487,7 +492,7 @@ static void midi_tick(uint32_t dt, bool busy) const bool up = sp1_midi_port_up(); if (up != midi_port_was) { midi_port_was = up; - /* The script's pickup (config/midi.ini), so a log says which one was flashed. */ + /* The script's pickup (midi.cnfg, #52), so a log says which one is in use. */ static const char *const pickup[] = { [SP1_MIDI_PICKUP_SUM] = "sum: CCs offset the faders", [SP1_MIDI_PICKUP_SHARED] = "shared: CCs and faders share each value", @@ -495,7 +500,7 @@ static void midi_tick(uint32_t dt, bool busy) }; if (up) { printk("MIDI port enabled by the host (pickup %s)\n", - pickup[SP1_MIDI_PICKUP]); + pickup[sp1_midi_config()->pickup % 3u]); /* A host can start Marbles before PLAY ever has (M5b), so seed its * random stream now if PLAY has not: the moment a host enumerates * varies as much as the moment of a first PLAY. */ @@ -1178,33 +1183,50 @@ static void prst_gather(struct sp1_prst *p) * Adara: "the shutdown animation completes -> the UI freezes -> save -> OFF or STANDBY", * with the UI locked and the LEDs off, limit 4 s. The UI is frozen because main is in here; * audio stops first (sp1_quiesce_peripherals() would stop it a moment later anyway), so the - * storage thread has the CPU. Never called by the 30 s backstop (sp1_power.h). */ -static void prst_save_at_shutdown(void) + * storage thread has the CPU. Never called by the 30 s backstop (sp1_power.h). + * #52: then the log's last lines, in what is left of the same 4 s (Adara: the save first). */ +static void storage_at_shutdown(void) { - if (!g_prst_on) { + const bool log = sp1_store_log_live(); + if (!g_prst_on && !log) { return; } - g_prst_on = false; sp1_leds_all_off(); sp1_audio_stop(); - struct sp1_prst p; - prst_gather(&p); const uint32_t t0 = k_uptime_get_32(); - if (!sp1_store_prst_save(g_prst_slot, &p)) { - printk("PRST save: not possible (storage not ready) -- nothing saved\n"); - return; + if (!g_prst_on) { + sp1_store_log_end(); + } else { + g_prst_on = false; + struct sp1_prst p; + prst_gather(&p); + if (!sp1_store_prst_save(g_prst_slot, &p)) { + printk("PRST save: not possible (storage not ready) -- nothing saved\n"); + sp1_store_log_end(); + } else { + while (sp1_store_save_result() == SP1_STORE_SAVE_BUSY && + k_uptime_get_32() - t0 < SP1_PRST_SAVE_MS) { + sp1_wdt_feed(); + k_msleep(TICK_MS); + } + const enum sp1_store_save r = sp1_store_save_result(); + printk("PRST save slot %d: %s after %u ms\n", g_prst_slot + 1, + r == SP1_STORE_SAVE_OK ? "saved" : (r == SP1_STORE_SAVE_BUSY + ? "NOT finished in time -- powering off anyway" + : "FAILED"), + (unsigned)(k_uptime_get_32() - t0)); + } } - while (sp1_store_save_result() == SP1_STORE_SAVE_BUSY && - k_uptime_get_32() - t0 < SP1_PRST_SAVE_MS) { + /* The save job closes the log after the save (sp1_store.h). */ + while (sp1_store_log_live() && k_uptime_get_32() - t0 < SP1_PRST_SAVE_MS) { sp1_wdt_feed(); k_msleep(TICK_MS); } - const enum sp1_store_save r = sp1_store_save_result(); - printk("PRST save slot %d: %s after %u ms\n", g_prst_slot + 1, - r == SP1_STORE_SAVE_OK ? "saved" : (r == SP1_STORE_SAVE_BUSY - ? "NOT finished in time -- powering off anyway" - : "FAILED"), - (unsigned)(k_uptime_get_32() - t0)); + if (log) { + printk("LOG %s after %u ms\n", sp1_store_log_live() + ? "NOT closed in time -- powering off anyway" : "closed", + (unsigned)(k_uptime_get_32() - t0)); + } } #elif defined(CONFIG_SP1_PLAITS) /* Without storage there is no PRST: "β€’β€’" + PLAY is ROTC alone. */ @@ -1373,7 +1395,7 @@ int main(void) sp1_mui_init(); #endif #if defined(CONFIG_SP1_STORAGE) && defined(CONFIG_SP1_PLAITS) - sp1_power_set_save_hook(prst_save_at_shutdown); /* PRST (#50) */ + sp1_power_set_save_hook(storage_at_shutdown); /* PRST (#50), the log (#52) */ #endif /* ---- top-level state machine ---- @@ -1384,6 +1406,9 @@ int main(void) for (;;) { if (standby) { + /* #52 (Adara): STANDBY is not logged to the drive. Its lines stay in the + * RAM log for the console; the file's cursor jumps over them at ON. */ + sp1_logbuf_file_pause(); sp1_standby_run(); /* returns only when powering ON */ standby = false; } @@ -1417,6 +1442,7 @@ int main(void) #if defined(CONFIG_SP1_STORAGE) /* M6 (#43): the eMMC job runs in the storage thread, below main and audio; * this only queues it. Every way out of ON stops it (sp1_quiesce_peripherals). */ + sp1_logbuf_file_resume(); /* #52: from here the lines are for the log file */ sp1_store_on_enter(); #if defined(CONFIG_SP1_FRESH) /* The fresh image's format holds ON entry, before audio (storage_gate). */ @@ -1431,6 +1457,27 @@ int main(void) standby = true; /* the 30 s backstop, plugged in */ continue; } + /* #52: the ON job may have installed a new engine stack (engines.cnfg). */ + sp1_pui_stack_settle(); + /* ...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. */ + { + const struct sp1_audio_cfg *ac; + const struct sp1_midi_cfg *mc; + if (sp1_store_cnfg(&ac, &mc)) { +#if defined(CONFIG_SP1_USB_AUDIO) + sp1_audio_set_config(ac); +#endif +#if defined(CONFIG_SP1_MIDI) + sp1_midi_set_config(mc); +#endif + } else { + printk("CNFG not read this ON: audio and MIDI settings stay as they " + "were\n"); + } + ARG_UNUSED(ac); + ARG_UNUSED(mc); + } if (g_prst_on) { prst_apply(sp1_store_prst_slot(g_prst_slot)); } @@ -2260,10 +2307,10 @@ int main(void) * drive above instead, so this whole block stands down. */ if (!fnc && vol_parked && (sp1_button_pressed(SP1_BTN_VOL_DOWN) || sp1_button_pressed(SP1_BTN_VOL_UP))) { - /* config/audio.ini level = parked: a host is recording, so VOL stays - * where audio.ini put it until the host stops (usb_level_park). */ + /* audio.cnfg level = parked: a host is recording, so VOL stays + * where audio.cnfg put it until the host stops (usb_level_park). */ printk("LEVEL locked at %d dBFS while a host takes USB audio out" - " (config/audio.ini)\n", (int)usb_parked_db()); + " (audio.cnfg)\n", (int)usb_parked_db()); } if (!fnc && !vol_parked && sp1_button_pressed(SP1_BTN_VOL_DOWN)) { sp1_audio_level_step(+1); diff --git a/firmware/src/sp1_audio.c b/firmware/src/sp1_audio.c index 50f39ad..f5eed86 100644 --- a/firmware/src/sp1_audio.c +++ b/firmware/src/sp1_audio.c @@ -53,7 +53,29 @@ K_MEM_SLAB_DEFINE_STATIC(tx_slab, BLK_BYTES, TX_QUEUE + 4, 4); #if defined(CONFIG_SP1_USB_AUDIO) #include "sp1_uac.h" /* M5c: the same blocks, to the host */ -#include "sp1_audio_gen.h" /* config/audio.ini: the speaker while a host takes them */ +#include "sp1_audio_gen.h" /* config/audio.cnfg built in: the speaker while a host takes them */ +#include "sp1_cnfg.h" /* struct sp1_audio_cfg (#52) */ + +/* ---- the audio settings, LIVE (#52) ---- + * config/audio.cnfg's built-in values until main hands over the drive's + * WAKES/CNFG/audio.cnfg at ON entry (sp1_audio_set_config). Main writes and reads them. */ +static struct sp1_audio_cfg audio_cfg = SP1_AUDIO_CFG_DEFAULTS; + +void sp1_audio_set_config(const struct sp1_audio_cfg *c) +{ + audio_cfg = *c; + /* The reader only passes VOL's steps; a stray value parks at the default. */ + if (audio_cfg.parked_step >= SP1_LEVEL_STEPS - 1) { + const struct sp1_audio_cfg def = SP1_AUDIO_CFG_DEFAULTS; + audio_cfg.parked_step = def.parked_step; + audio_cfg.parked_db = def.parked_db; + } +} + +const struct sp1_audio_cfg *sp1_audio_config(void) +{ + return &audio_cfg; +} #endif #if defined(CONFIG_SP1_MIDI) @@ -236,12 +258,14 @@ static const int16_t TONE_AMP[SP1_LEVEL_STEPS] = { static const int16_t TONE_DB_X10[SP1_LEVEL_STEPS] = { 0, -30, -60, -90, -120, -151, -181, -211, -241, -271, -301, -9990, }; -/* config/audio.ini's parked_level is one of these steps, as tools/gen_audio.py knows them - * (0 .. -30 dB, 3 dB apart, then mute): parking USB audio out IS setting VOL (main.c). */ -BUILD_ASSERT(SP1_LEVEL_STEPS == 12, "VOL's steps changed: update VOL_STEPS in tools/gen_audio.py"); +/* audio.cnfg's parked_level is one of these steps, as tools/gen_audio.py and the drive's + * reader (sp1_cnfg.c) know them (0 .. -30 dB, 3 dB apart, then mute): parking USB audio out + * IS setting VOL (main.c). */ +BUILD_ASSERT(SP1_LEVEL_STEPS == 12, "VOL's steps changed: update VOL_STEPS in tools/gen_audio.py " + "and the parked_level check in sp1_cnfg.c"); #if defined(CONFIG_SP1_USB_AUDIO) BUILD_ASSERT(SP1_AUDIO_USB_PARKED_STEP >= 0 && SP1_AUDIO_USB_PARKED_STEP < SP1_LEVEL_STEPS - 1, - "config/audio.ini parked_level is not one of VOL's steps"); + "config/audio.cnfg parked_level is not one of VOL's steps"); #endif static volatile bool tone_on; @@ -939,7 +963,7 @@ void sp1_audio_take_sections(struct sp1_audio_sections *out) * While it is, the TAS2505's class-D driver is powered down (page 1, reg 0x2D). * * M5c (Adara, 2026-10-05): the speaker is also off while a host is TAKING USB audio out -- - * unless config/audio.ini says `speaker = on` (SP1_AUDIO_USB_SPEAKER; default off) + * unless audio.cnfg says `speaker = on` (sp1_audio_config(); default off) * (sp1_uac_live: the stream open AND packets going out since the last poll) -- recording * Wakes over USB, the speaker would only be a second, room copy. Anything short of that * defaults to the speaker (Adara): a charger, a host without USB audio or that rejects @@ -995,7 +1019,7 @@ static bool speaker_driver(bool on) static bool speaker_wanted(void) { #if defined(CONFIG_SP1_USB_AUDIO) - if (!SP1_AUDIO_USB_SPEAKER && sp1_uac_live()) { + if (!audio_cfg.speaker && sp1_uac_live()) { return false; } #endif diff --git a/firmware/src/sp1_audio.h b/firmware/src/sp1_audio.h index 3131a4d..10d763a 100644 --- a/firmware/src/sp1_audio.h +++ b/firmware/src/sp1_audio.h @@ -96,6 +96,14 @@ uint32_t sp1_audio_take_peak(void); void sp1_audio_level_step(int delta); /* +1 = quieter by 3 dB, -1 = louder */ int sp1_audio_level_get(void); + +#if defined(CONFIG_SP1_USB_AUDIO) +/* #52: the audio settings from the drive (audio.cnfg). Main, at ON entry. sp1_audio_config() + * is the live copy (the built-in one until then). */ +struct sp1_audio_cfg; +void sp1_audio_set_config(const struct sp1_audio_cfg *c); +const struct sp1_audio_cfg *sp1_audio_config(void); +#endif int sp1_audio_level_db_x10(void); /* tenths of dBFS, -9990 = mute */ /* ---- the fallback test tone (CONFIG_SP1_PLAITS=n only): 440 Hz, off at start ---- */ diff --git a/firmware/src/sp1_cnfg.c b/firmware/src/sp1_cnfg.c new file mode 100644 index 0000000..d9acc0a --- /dev/null +++ b/firmware/src/sp1_cnfg.c @@ -0,0 +1,1106 @@ +/* wakes-sp1 β€” the config files on the drive (#52). See sp1_cnfg.h. */ +/* midi.cnfg's reader needs the destinations' names (SP1_MIDI_NAME): a second, small copy of + * that table besides sp1_midi.cc's. Defined before the first include of sp1_midi_gen.h. */ +#define SP1_MIDI_GEN_TABLES +#include "sp1_cnfg.h" +#include "sp1_logs_gen.h" +#include "sp1_engines_gen.h" +#include "sp1_audio_gen.h" + +#include + +_Static_assert(SP1_ENGINE_SLOTS == SP1_CNFG_SLOTS, "engines.cnfg has 24 slots"); +_Static_assert(SP1_ENGINE_EMPTY == SP1_CNFG_EMPTY, "one value for an empty slot"); +_Static_assert(SP1_PLAITS_ENGINE_COUNT <= 32, "the used-engine set is a 32-bit mask"); + +/* ---------------------------------------------------------------- the ini reader */ + +static bool space(char c) +{ + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v'; +} + +static char lower(char c) +{ + return (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c; +} + +/* Trim s in place; returns the new start. */ +static char *trim(char *s) +{ + while (space(*s)) { + s++; + } + size_t n = strlen(s); + while (n > 0u && space(s[n - 1u])) { + s[--n] = '\0'; + } + return s; +} + +static void lower_str(char *s) +{ + for (; *s != '\0'; s++) { + *s = lower(*s); + } +} + +static bool same(const char *a, const char *b) +{ + for (; *a != '\0' && lower(*a) == lower(*b); a++, b++) { + } + return lower(*a) == lower(*b); +} + +void sp1_cnfg_begin(struct sp1_cnfg_parser *p, sp1_cnfg_entry_fn entry, + sp1_cnfg_problem_fn problem, void *ctx) +{ + memset(p, 0, sizeof(*p)); + p->entry = entry; + p->problem = problem; + p->ctx = ctx; +} + +static void line_done(struct sp1_cnfg_parser *p) +{ + p->line++; + p->buf[p->n] = '\0'; + const bool overlong = p->overlong; + p->n = 0u; + p->overlong = false; + if (overlong) { + p->problem(p->ctx, p->line, "(a long line)", + "over 160 characters: the line is ignored"); + return; + } + char *s = p->buf; + /* A UTF-8 byte order mark (Notepad and Excel write one). */ + if (p->line == 1 && (unsigned char)s[0] == 0xEFu && (unsigned char)s[1] == 0xBBu && + (unsigned char)s[2] == 0xBFu) { + s += 3; + } + s = trim(s); + if (*s == '\0' || *s == ';' || *s == '#') { + return; + } + if (*s == '[') { + char *end = strchr(s, ']'); + if (end == NULL) { + p->section[0] = '\0'; + p->problem(p->ctx, p->line, s, "a section name needs a closing ]: the " + "settings under it are ignored"); + return; + } + *end = '\0'; + char *name = trim(s + 1); + if (strlen(name) >= sizeof(p->section)) { + p->section[0] = '\0'; + p->problem(p->ctx, p->line, name, "is not a section: the settings under it " + "are ignored"); + return; + } + strcpy(p->section, name); + lower_str(p->section); + return; + } + char *eq = strchr(s, '='); + if (eq == NULL) { + p->problem(p->ctx, p->line, s, "is not a setting (key = value): ignored"); + return; + } + *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; + } + } + val = trim(val); + if (*key == '\0') { + p->problem(p->ctx, p->line, "(nothing before the =)", "a setting needs a name: " + "ignored"); + return; + } + lower_str(key); + p->entry(p->ctx, p->line, p->section, key, val); +} + +void sp1_cnfg_feed(struct sp1_cnfg_parser *p, const char *text, size_t n) +{ + for (size_t i = 0u; i < n; i++) { + const char c = text[i]; + if (c == '\n') { + line_done(p); + } else if (p->n < SP1_CNFG_LINE_MAX) { + p->buf[p->n++] = (c == '\0') ? ' ' : c; + } else { + p->overlong = true; + } + } +} + +void sp1_cnfg_end(struct sp1_cnfg_parser *p) +{ + if (p->n > 0u || p->overlong) { + line_done(p); + } +} + +/* ---------------------------------------------------------------- logs.cnfg */ + +static const struct { + const char *key; + uint8_t bit; /* SP1_LOG_*, or 0 for `enabled` */ +} LOG_KEYS[] = { + { "enabled", 0u }, + { "performance", SP1_LOG_PERFORMANCE }, + { "controls", SP1_LOG_CONTROLS }, + { "midi", SP1_LOG_MIDI }, + { "usb", SP1_LOG_USB }, + { "storage", SP1_LOG_STORAGE }, +}; +#define SEEN_ENABLED 0x80u + +void sp1_logs_defaults(struct sp1_logs_cfg *c) +{ + c->enabled = SP1_LOGS_DEF_ENABLED != 0; + c->cats = (uint8_t)SP1_LOGS_DEF_CATS; +} + +static void report(struct sp1_logs_reader *r, int line, const char *what, const char *why) +{ + r->problems++; + r->problem(r->ctx, line, what, why); +} + +static void logs_entry(void *ctx, int line, const char *section, const char *key, + const char *value) +{ + struct sp1_logs_reader *r = ctx; + if (section[0] == '\0') { + report(r, line, key, "is not under [logs]: ignored"); + return; + } + if (strcmp(section, "logs") != 0) { + if (strcmp(section, r->bad_section) != 0) { + strcpy(r->bad_section, section); /* both < SP1_CNFG_NAME_MAX */ + report(r, line, section, "is not a section of logs.cnfg (expected [logs]): " + "its settings are ignored"); + } + return; + } + for (size_t i = 0u; i < sizeof(LOG_KEYS) / sizeof(LOG_KEYS[0]); i++) { + if (strcmp(key, LOG_KEYS[i].key) != 0) { + continue; + } + const uint8_t seen = LOG_KEYS[i].bit ? LOG_KEYS[i].bit : SEEN_ENABLED; + if (r->seen & seen) { + report(r, line, key, "is set twice: the first one is used"); + return; + } + r->seen |= seen; + bool on; + if (same(value, "on")) { + on = true; + } else if (same(value, "off")) { + on = false; + } else { + size_t k = strlen(key); + memcpy(r->what, key, k); + memcpy(r->what + k, " = ", 3u); + const size_t v = strlen(value); /* key + value < SP1_CNFG_LINE_MAX */ + memcpy(r->what + k + 3u, value, v + 1u); + report(r, line, r->what, "must be on or off: the default is used"); + return; + } + if (LOG_KEYS[i].bit == 0u) { + r->cfg->enabled = on; + } else if (on) { + r->cfg->cats |= LOG_KEYS[i].bit; + } else { + r->cfg->cats &= (uint8_t)~LOG_KEYS[i].bit; + } + return; + } + report(r, line, key, "is not a logs.cnfg setting: ignored"); +} + +static void logs_problem(void *ctx, int line, const char *what, const char *why) +{ + report(ctx, line, what, why); +} + +void sp1_logs_begin(struct sp1_logs_reader *r, struct sp1_logs_cfg *c, + sp1_cnfg_problem_fn problem, void *ctx) +{ + memset(r, 0, sizeof(*r)); + r->cfg = c; + r->problem = problem; + r->ctx = ctx; + sp1_cnfg_begin(&r->p, logs_entry, logs_problem, r); +} + +void sp1_logs_feed(struct sp1_logs_reader *r, const char *text, size_t n) +{ + sp1_cnfg_feed(&r->p, text, n); +} + +int sp1_logs_end(struct sp1_logs_reader *r) +{ + sp1_cnfg_end(&r->p); + return r->problems; +} + +const char *sp1_logs_describe(uint8_t cats, char *buf, size_t size) +{ + size_t n = 0u; + buf[0] = '\0'; + for (size_t i = 1u; i < sizeof(LOG_KEYS) / sizeof(LOG_KEYS[0]); i++) { + if (!(cats & LOG_KEYS[i].bit)) { + continue; + } + const size_t k = strlen(LOG_KEYS[i].key); + if (n + k + 2u > size) { + break; + } + if (n > 0u) { + buf[n++] = ' '; + } + memcpy(buf + n, LOG_KEYS[i].key, k + 1u); + n += k; + } + if (n == 0u && size >= 5u) { + memcpy(buf, "none", 5u); + } + return buf; +} + +/* ---------------------------------------------------------------- engines.cnfg */ + +int sp1_engine_index(const char *name, size_t n) +{ + for (int i = 0; i < SP1_PLAITS_ENGINE_COUNT; i++) { + if (sp1_engine_name_eq(SP1_PLAITS_ENGINES[i].name, name, n)) { + return i; + } + } + return -1; +} + +void sp1_engines_defaults(uint8_t out[SP1_CNFG_SLOTS]) +{ + static const uint8_t def[SP1_CNFG_SLOTS] = SP1_ENGINE_DEFAULT_STACK; + memcpy(out, def, SP1_CNFG_SLOTS); +} + +static void eng_report(struct sp1_engines_reader *r, int line, const char *what, const char *why) +{ + r->problems++; + r->problem(r->ctx, line, what, why); +} + +static void eng_problem(void *ctx, int line, const char *what, const char *why) +{ + eng_report(ctx, line, what, why); +} + +/* " = " into r->what, for a problem that is about the whole line. */ +static const char *eng_line(struct sp1_engines_reader *r, const char *key, const char *value) +{ + const size_t k = strlen(key); + const size_t v = strlen(value); /* key + value < SP1_CNFG_LINE_MAX */ + memcpy(r->what, key, k); + memcpy(r->what + k, " = ", 3u); + memcpy(r->what + k + 3u, value, v + 1u); + return r->what; +} + +static void eng_entry(void *ctx, int line, const char *section, const char *key, + const char *value) +{ + struct sp1_engines_reader *r = ctx; + if (section[0] == '\0') { + eng_report(r, line, key, "is not under [engines]"); + return; + } + if (strcmp(section, "engines") != 0) { + if (strcmp(section, r->bad_section) != 0) { + strcpy(r->bad_section, section); /* both < SP1_CNFG_NAME_MAX */ + eng_report(r, line, section, "is not a section of engines.cnfg (expected " + "[engines])"); + } + return; + } + /* The slot: 1-24, digits only. */ + int slot = 0; + const char *k = key; + for (; *k >= '0' && *k <= '9' && slot <= SP1_CNFG_SLOTS; k++) { + slot = slot * 10 + (*k - '0'); + } + if (*k != '\0' || k == key || slot < 1 || slot > SP1_CNFG_SLOTS) { + eng_report(r, line, key, "is not a slot (1-24)"); + return; + } + const uint32_t bit = 1u << (slot - 1); + if (r->seen & bit) { + eng_report(r, line, key, "is set twice"); + return; + } + r->seen |= bit; + if (value[0] == '\0' || same(value, "none")) { + return; /* an empty slot */ + } + const int e = sp1_engine_index(value, strlen(value)); + if (e < 0) { + eng_report(r, line, eng_line(r, key, value), "is not an engine name (the list is at " + "the end of the file)"); + return; + } + if (r->used & (1u << e)) { + eng_report(r, line, eng_line(r, key, value), "uses an engine that is already in " + "another slot (each engine can be used once)"); + return; + } + r->used |= 1u << e; + r->stack[slot - 1] = (uint8_t)e; + r->filled++; +} + +void sp1_engines_begin(struct sp1_engines_reader *r, sp1_cnfg_problem_fn problem, void *ctx) +{ + memset(r, 0, sizeof(*r)); + memset(r->stack, SP1_CNFG_EMPTY, sizeof(r->stack)); + r->problem = problem; + r->ctx = ctx; + sp1_cnfg_begin(&r->p, eng_entry, eng_problem, r); +} + +void sp1_engines_feed(struct sp1_engines_reader *r, const char *text, size_t n) +{ + sp1_cnfg_feed(&r->p, text, n); +} + +int sp1_engines_end(struct sp1_engines_reader *r, uint8_t out[SP1_CNFG_SLOTS], int *filled) +{ + sp1_cnfg_end(&r->p); + if (r->problems == 0 && r->filled == 0) { + eng_report(r, r->p.line, "(the whole file)", "names no engine: T2/T3 would have " + "nothing to play"); + } + if (r->problems == 0) { + memcpy(out, r->stack, SP1_CNFG_SLOTS); + *filled = r->filled; + } else { + sp1_engines_defaults(out); + int n = 0; + for (int i = 0; i < SP1_CNFG_SLOTS; i++) { + n += (out[i] != SP1_CNFG_EMPTY); + } + *filled = n; + } + return r->problems; +} + +/* ---------------------------------------------------------------- the log's categories */ + +/* Every tag the firmware prints, by category (the first word of the line). A tag that is + * not here -- BOOT, PWR, CHARGE, JACK, CTRL, CALIBRATION, CNFG, the "[ON]" status line -- + * is always written. A new printk tag lands there too until it is added. */ +static const struct { + const char *tag; + uint8_t cat; +} TAGS[] = { + { "AUD", SP1_LOG_PERFORMANCE }, { "CPU", SP1_LOG_PERFORMANCE }, + { "BLK", SP1_LOG_PERFORMANCE }, { "MISS", SP1_LOG_PERFORMANCE }, + { "SYN", SP1_LOG_PERFORMANCE }, { "THREADS", SP1_LOG_PERFORMANCE }, + { "PAGE", SP1_LOG_CONTROLS }, { "SHIFT", SP1_LOG_CONTROLS }, + { "ENGINE", SP1_LOG_CONTROLS }, { "MODULE", SP1_LOG_CONTROLS }, + { "MODEL", SP1_LOG_CONTROLS }, { "ROUTE", SP1_LOG_CONTROLS }, + { "RIP", SP1_LOG_CONTROLS }, { "UNPATCH", SP1_LOG_CONTROLS }, + { "RANGE", SP1_LOG_CONTROLS }, { "LEVEL", SP1_LOG_CONTROLS }, + { "QUANTIZE", SP1_LOG_CONTROLS }, { "SCALE", SP1_LOG_CONTROLS }, + { "PICKUP", SP1_LOG_CONTROLS }, { "DRIVE", SP1_LOG_CONTROLS }, + { "BURST", SP1_LOG_CONTROLS }, { "DIVISION", SP1_LOG_CONTROLS }, + { "OUTPUT", SP1_LOG_CONTROLS }, { "TRIG", SP1_LOG_CONTROLS }, + { "FREQUENCY", SP1_LOG_CONTROLS }, { "MARBLES", SP1_LOG_CONTROLS }, + { "DEJA", SP1_LOG_CONTROLS }, { "DIVERSITY", SP1_LOG_CONTROLS }, + { "TONE", SP1_LOG_CONTROLS }, { "SAG", SP1_LOG_CONTROLS }, + { "MIDI", SP1_LOG_MIDI }, { "CLOCK", SP1_LOG_MIDI }, + { "USB", SP1_LOG_USB }, { "UAC", SP1_LOG_USB }, + { "SPEAKER", SP1_LOG_USB }, + { "STORE", SP1_LOG_STORAGE }, { "EMMC", SP1_LOG_STORAGE }, + { "PRST", SP1_LOG_STORAGE }, { "LOG", SP1_LOG_STORAGE }, +}; + +uint8_t sp1_log_category(const char *line, size_t n) +{ + size_t i = 0u; + /* "[+hh:mm:ss.mmm] " */ + if (n >= 2u && line[0] == '[' && line[1] == '+') { + while (i < n && line[i] != ']') { + i++; + } + i++; + while (i < n && line[i] == ' ') { + i++; + } + } + size_t k = 0u; + while (i + k < n && line[i + k] >= 'A' && line[i + k] <= 'Z') { + k++; + } + if (k < 2u || k > 9u) { + return 0u; + } + /* The tag is a whole word: "STORE ..." yes, "Singles" or "USBx" no. */ + if (i + k < n) { + const char c = line[i + k]; + if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_') { + return 0u; + } + } + for (size_t t = 0u; t < sizeof(TAGS) / sizeof(TAGS[0]); t++) { + if (strlen(TAGS[t].tag) == k && memcmp(TAGS[t].tag, line + i, k) == 0) { + return TAGS[t].cat; + } + } + return 0u; +} + +/* ---------------------------------------------------------------- shared helpers */ + +/* A non-negative decimal, digits only, at most `max`. */ +static bool parse_uint(const char *s, int max, int *out) +{ + int v = 0; + if (*s == '\0') { + return false; + } + for (; *s != '\0'; s++) { + if (*s < '0' || *s > '9') { + return false; + } + v = v * 10 + (*s - '0'); + if (v > max) { + return false; + } + } + *out = v; + return true; +} + +/* "cc N" (also "ccN", any case) -> N 0-127; "none" / "off" / "" -> -1 when allowed; else -2. */ +static int parse_cc(const char *s, bool allow_none) +{ + if (allow_none && (s[0] == '\0' || same(s, "none") || same(s, "off"))) { + return -1; + } + if (lower(s[0]) != 'c' || lower(s[1]) != 'c') { + return -2; + } + s += 2; + while (space(*s)) { + s++; + } + int n; + return parse_uint(s, 127, &n) ? n : -2; +} + +/* MIDI's own CCs (tools/gen_midi.py RESERVED): bank select, data entry, (N)RPN, channel mode. */ +static const char *cc_reserved(int n) +{ + if (n == 0 || n == 32) { + return "bank select"; + } + if (n == 6 || n == 38 || n == 96 || n == 97) { + return "data entry"; + } + if (n >= 98 && n <= 101) { + return "parameter numbers (RPN / NRPN)"; + } + if (n >= 120) { + return "channel mode messages"; + } + return NULL; +} + +/* A small text builder for messages: no printf in this file. */ +struct msg { + char *b; + size_t size, n; +}; + +static void msg_s(struct msg *m, const char *s) +{ + while (*s != '\0' && m->n + 1u < m->size) { + m->b[m->n++] = *s++; + } + m->b[m->n] = '\0'; +} + +static void msg_i(struct msg *m, int v) +{ + char t[12]; + int k = 0; + unsigned u = (unsigned)(v < 0 ? -v : v); + do { + t[k++] = (char)('0' + u % 10u); + u /= 10u; + } while (u != 0u && k < 11); + if (v < 0) { + t[k++] = '-'; + } + while (k > 0 && m->n + 1u < m->size) { + m->b[m->n++] = t[--k]; + } + m->b[m->n] = '\0'; +} + +static const char *key_value(char *buf, const char *key, const char *value) +{ + struct msg m = { buf, SP1_CNFG_LINE_MAX + 4u, 0u }; + msg_s(&m, key); + msg_s(&m, " = "); + msg_s(&m, value); + return buf; +} + +/* ---------------------------------------------------------------- audio.cnfg */ + +_Static_assert(sizeof(struct sp1_audio_cfg) == 4u, "SP1_AUDIO_CFG_DEFAULTS: one value a field"); + +void sp1_audio_cfg_defaults(struct sp1_audio_cfg *c) +{ + static const struct sp1_audio_cfg def = SP1_AUDIO_CFG_DEFAULTS; + *c = def; +} + +static void audio_report(struct sp1_audio_reader *r, int line, const char *what, const char *why) +{ + r->problems++; + r->problem(r->ctx, line, what, why); +} + +static void audio_problem(void *ctx, int line, const char *what, const char *why) +{ + audio_report(ctx, line, what, why); +} + +static void audio_entry(void *ctx, int line, const char *section, const char *key, + const char *value) +{ + struct sp1_audio_reader *r = ctx; + if (section[0] == '\0') { + audio_report(r, line, key, "is not under [usb]: ignored"); + return; + } + if (strcmp(section, "usb") != 0) { + if (strcmp(section, r->bad_section) != 0) { + strcpy(r->bad_section, section); + audio_report(r, line, section, "is not a section of audio.cnfg (expected [usb]): " + "its settings are ignored"); + } + return; + } + static const char *const KEYS[] = { "level", "parked_level", "speaker" }; + int k = -1; + for (int i = 0; i < 3; i++) { + if (strcmp(key, KEYS[i]) == 0) { + k = i; + } + } + if (k < 0) { + audio_report(r, line, key, "is not an audio.cnfg setting: ignored"); + return; + } + if (r->seen & (1u << k)) { + audio_report(r, line, key, "is set twice: the first one is used"); + return; + } + r->seen |= (uint8_t)(1u << k); + if (k == 0) { + if (same(value, "parked")) { + r->cfg->parked = 1u; + } else if (same(value, "vol")) { + r->cfg->parked = 0u; + } else { + audio_report(r, line, key_value(r->what, key, value), + "must be parked or vol: the default is used"); + } + } else if (k == 1) { + /* -6, -6 dB, -6db; 0. One of VOL's steps: 0 .. -30, 3 dB apart. */ + char t[16]; + size_t n = 0u; + const char *s = value; + bool neg = false; + if (*s == '-' || *s == '+') { + neg = (*s == '-'); + s++; + } + while (*s >= '0' && *s <= '9' && n < sizeof(t) - 1u) { + t[n++] = *s++; + } + t[n] = '\0'; + while (space(*s)) { + s++; + } + int db; + const bool unit_ok = (*s == '\0') || same(s, "db"); + if (n == 0u || !unit_ok || !parse_uint(t, 99, &db) || (db != 0 && !neg) || + db > 30 || db % 3 != 0) { + audio_report(r, line, key_value(r->what, key, value), + "must be one of VOL's steps (0, -3, -6 ... -30): the default is used"); + } else { + r->cfg->parked_db = (int8_t)(-db); + r->cfg->parked_step = (uint8_t)(db / 3); + } + } else { + if (same(value, "on")) { + r->cfg->speaker = 1u; + } else if (same(value, "off")) { + r->cfg->speaker = 0u; + } else { + audio_report(r, line, key_value(r->what, key, value), + "must be on or off: the default is used"); + } + } +} + +void sp1_audio_reader_begin(struct sp1_audio_reader *r, struct sp1_audio_cfg *c, + sp1_cnfg_problem_fn problem, void *ctx) +{ + memset(r, 0, sizeof(*r)); + sp1_audio_cfg_defaults(c); + r->cfg = c; + r->problem = problem; + r->ctx = ctx; + sp1_cnfg_begin(&r->p, audio_entry, audio_problem, r); +} + +void sp1_audio_reader_feed(struct sp1_audio_reader *r, const char *text, size_t n) +{ + sp1_cnfg_feed(&r->p, text, n); +} + +int sp1_audio_reader_end(struct sp1_audio_reader *r) +{ + sp1_cnfg_end(&r->p); + return r->problems; +} + +/* ---------------------------------------------------------------- midi.cnfg */ + +_Static_assert(SP1_MIDI_DESTS <= 31, "seen_dest is a 32-bit mask"); + +void sp1_midi_cfg_defaults(struct sp1_midi_cfg *c) +{ + static const struct sp1_midi_cfg def = SP1_MIDI_CFG_DEFAULTS; + *c = def; +} + +/* SP1_MIDI_NAME[d] is "
". */ +static bool dest_is(int d, const char *section, const char *key) +{ + const char *n = SP1_MIDI_NAME[d]; + const size_t s = strlen(section); + return strncmp(n, section, s) == 0 && n[s] == ' ' && strcmp(n + s + 1, key) == 0; +} + +static const char *dest_key(int d) +{ + const char *n = strchr(SP1_MIDI_NAME[d], ' '); + return n != NULL ? n + 1 : SP1_MIDI_NAME[d]; +} + +static void midi_report(struct sp1_midi_reader *r, int line, const char *what, const char *why) +{ + r->problems++; + r->problem(r->ctx, line, what, why); +} + +static void midi_problem(void *ctx, int line, const char *what, const char *why) +{ + midi_report(ctx, line, what, why); +} + +static bool once(struct sp1_midi_reader *r, int line, const char *key, uint32_t *seen, + uint32_t bit) +{ + if (*seen & bit) { + midi_report(r, line, key, "is set twice: the first one is used"); + return false; + } + *seen |= bit; + return true; +} + +/* A CC value for `who` (a destination, or the sustain pedal): checked, then queued for the + * collision pass at the end. */ +static void take_cc(struct sp1_midi_reader *r, int line, int who, const char *key, + const char *value) +{ + const int n = parse_cc(value, true); + struct msg m = { r->why, sizeof(r->why), 0u }; + if (n == -2) { + midi_report(r, line, key_value(r->what, key, value), + "is not `cc N` with N 0-127 (or none): the default is kept"); + return; + } + if (n >= 0 && cc_reserved(n) != NULL) { + msg_s(&m, "CC "); + msg_i(&m, n); + msg_s(&m, " is reserved by MIDI ("); + msg_s(&m, cc_reserved(n)); + msg_s(&m, "): the default is kept"); + midi_report(r, line, key_value(r->what, key, value), r->why); + return; + } + if (n >= 33 && n <= 63) { + msg_s(&m, "CC "); + msg_i(&m, n); + msg_s(&m, " is the fine half of 14-bit CC "); + msg_i(&m, n - 32); + msg_s(&m, "; use CC "); + msg_i(&m, n - 32); + msg_s(&m, ": the default is kept"); + midi_report(r, line, key_value(r->what, key, value), r->why); + return; + } + r->user_cc[who] = (int8_t)n; + r->user_line[who] = (int16_t)line; + r->order[r->n_order++] = (uint8_t)who; +} + +static void midi_section(struct sp1_midi_reader *r, int line, const char *key, const char *value) +{ + static const char *const KEYS[] = { + "channel", "note_priority", "legato", "portamento", "bend_range", "sustain", + "cc_smoothing", "pickup", "clock", "clock_lead", + }; + int k = -1; + for (int i = 0; i < (int)(sizeof(KEYS) / sizeof(KEYS[0])); i++) { + if (strcmp(key, KEYS[i]) == 0) { + k = i; + } + } + if (k < 0) { + midi_report(r, line, key, "is not a [midi] setting: ignored"); + return; + } + uint32_t seen = r->seen_midi; + const bool first = once(r, line, key, &seen, 1u << k); + r->seen_midi = (uint16_t)seen; + if (!first) { + return; + } + struct sp1_midi_cfg *c = r->cfg; + const char *why = NULL; + int v; + switch (k) { + case 0: /* channel: 1-16 or omni */ + if (same(value, "omni")) { + c->channel = SP1_MIDI_OMNI; + } else if (parse_uint(value, 16, &v) && v >= 1) { + c->channel = (int8_t)(v - 1); + } else { + why = "must be 1-16 or omni: the default is used"; + } + break; + case 1: /* note_priority */ + if (same(value, "last")) { + c->priority = 0u; + } else if (same(value, "low")) { + c->priority = 1u; + } else if (same(value, "high")) { + c->priority = 2u; + } else { + why = "must be last, low or high: the default is used"; + } + break; + case 2: /* legato: off 0, auto 1, on 2 (Yarns) */ + if (same(value, "off")) { + c->legato = 0u; + } else if (same(value, "auto")) { + c->legato = 1u; + } else if (same(value, "on")) { + c->legato = 2u; + } else { + why = "must be off, on or auto: the default is used"; + } + break; + case 3: /* portamento: 0, t1-t50 (time), r0-r50 (rate) */ + if (strcmp(value, "0") == 0) { + c->portamento = 0u; + } else if (lower(value[0]) == 't' && parse_uint(value + 1, 50, &v) && v >= 1) { + c->portamento = (uint8_t)v; + } else if (lower(value[0]) == 'r' && parse_uint(value + 1, 50, &v)) { + c->portamento = (uint8_t)(51 + v); + } else { + why = "must be 0, t1-t50 or r0-r50: the default is used"; + } + break; + case 4: /* bend_range: 0-24 */ + if (parse_uint(value, 24, &v)) { + c->bend_range = (uint8_t)v; + } else { + why = "must be 0-24 semitones: the default is used"; + } + break; + case 5: /* sustain: cc N, or off */ + take_cc(r, line, SP1_MIDI_WHO_SUSTAIN, key, value); + return; + case 6: /* cc_smoothing: 0-200 ms */ + if (parse_uint(value, 200, &v)) { + c->smooth_ms = (uint8_t)v; + } else { + why = "must be 0-200 (ms): the default is used"; + } + break; + case 7: /* pickup */ + if (same(value, "sum")) { + c->pickup = SP1_MIDI_PICKUP_SUM; + } else if (same(value, "shared")) { + c->pickup = SP1_MIDI_PICKUP_SHARED; + } else if (same(value, "takeover")) { + c->pickup = SP1_MIDI_PICKUP_TAKEOVER; + } else { + why = "must be sum, shared or takeover: the default is used"; + } + break; + case 8: /* clock */ + if (same(value, "on")) { + c->clock = 1u; + } else if (same(value, "off")) { + c->clock = 0u; + } else { + why = "must be on or off: the default is used"; + } + break; + default: /* clock_lead: notes, auto, or 0-200 ms */ + if (same(value, "notes")) { + c->clock_lead_ms = -2; + } else if (same(value, "auto")) { + c->clock_lead_ms = -1; + } else if (parse_uint(value, 200, &v)) { + c->clock_lead_ms = (int16_t)v; + } else { + why = "must be notes, auto or 0-200 (ms): the default is used"; + } + break; + } + if (why != NULL) { + midi_report(r, line, key_value(r->what, key, value), why); + } +} + +/* [bind]: velocity / aftertouch = [depth%], or none. */ +static void bind_section(struct sp1_midi_reader *r, int line, const char *key, const char *value) +{ + const int src = strcmp(key, "velocity") == 0 ? 0 : (strcmp(key, "aftertouch") == 0 ? 1 : -1); + if (src < 0) { + midi_report(r, line, key, "is not a [bind] source (velocity or aftertouch): ignored"); + return; + } + uint32_t seen = r->seen_bind; + const bool first = once(r, line, key, &seen, 1u << src); + r->seen_bind = (uint8_t)seen; + if (!first) { + return; + } + int dest = -1; + int depth = 0; /* none: depth 0, as gen_midi.py writes an unbound source */ + if (!same(value, "none")) { + depth = 100; + char name[SP1_CNFG_NAME_MAX]; + size_t n = 0u; + const char *s = value; + while (*s != '\0' && !space(*s) && n < sizeof(name) - 1u) { + name[n++] = lower(*s++); + } + name[n] = '\0'; + bool ok = n > 0u && (*s == '\0' || space(*s)); /* the name ends at a space */ + while (space(*s)) { + s++; + } + if (ok && *s != '\0') { + /* "[-]N%" */ + char t[8]; + size_t k = 0u; + const bool neg = (*s == '-'); + if (neg) { + s++; + } + while (*s >= '0' && *s <= '9' && k < sizeof(t) - 1u) { + t[k++] = *s++; + } + t[k] = '\0'; + while (space(*s)) { + s++; + } + int pct = 0; + ok = k > 0u && *s == '%' && s[1] == '\0' && parse_uint(t, 100, &pct); + depth = neg ? -pct : pct; + } + for (int d = 0; ok && d < SP1_MIDI_DESTS && dest < 0; d++) { + if (strcmp(dest_key(d), name) == 0) { + dest = d; + } + } + if (!ok || dest < 0) { + midi_report(r, line, key_value(r->what, key, value), + "is not ` [depth%]` with a parameter from the lists above " + "and a depth of -100% to 100% (or none): the default is used"); + return; + } + } + if (src == 0) { + r->cfg->vel_dest = (int8_t)dest; + r->cfg->vel_depth = (float)depth * 0.01f; + } else { + r->cfg->at_dest = (int8_t)dest; + r->cfg->at_depth = (float)depth * 0.01f; + } +} + +static void midi_entry(void *ctx, int line, const char *section, const char *key, + const char *value) +{ + struct sp1_midi_reader *r = ctx; + if (section[0] == '\0') { + midi_report(r, line, key, "is not under a section: ignored"); + return; + } + if (strcmp(section, "midi") == 0) { + midi_section(r, line, key, value); + return; + } + if (strcmp(section, "bind") == 0) { + bind_section(r, line, key, value); + return; + } + if (strcmp(section, "plaits") == 0 || strcmp(section, "marbles") == 0) { + for (int d = 0; d < SP1_MIDI_DESTS; d++) { + if (dest_is(d, section, key)) { + if (once(r, line, key, &r->seen_dest, 1u << d)) { + take_cc(r, line, d, key, value); + } + return; + } + } + struct msg m = { r->why, sizeof(r->why), 0u }; + msg_s(&m, "is not a parameter of ["); + msg_s(&m, section); + msg_s(&m, "]: ignored"); + midi_report(r, line, key, r->why); + return; + } + if (strcmp(section, r->bad_section) != 0) { + strcpy(r->bad_section, section); + midi_report(r, line, section, "is not a section of midi.cnfg (expected [midi], [plaits], " + "[marbles] or [bind]): its settings are ignored"); + } +} + +void sp1_midi_reader_begin(struct sp1_midi_reader *r, struct sp1_midi_cfg *c, + sp1_cnfg_problem_fn problem, void *ctx) +{ + memset(r, 0, sizeof(*r)); + sp1_midi_cfg_defaults(c); + r->cfg = c; + r->problem = problem; + r->ctx = ctx; + for (int i = 0; i <= SP1_MIDI_DESTS; i++) { + r->user_cc[i] = -2; + } + sp1_cnfg_begin(&r->p, midi_entry, midi_problem, r); +} + +void sp1_midi_reader_feed(struct sp1_midi_reader *r, const char *text, size_t n) +{ + sp1_cnfg_feed(&r->p, text, n); +} + +static const char *who_name(int who) +{ + return who == SP1_MIDI_WHO_SUSTAIN ? "the sustain pedal" : SP1_MIDI_NAME[who]; +} + +int sp1_midi_reader_end(struct sp1_midi_reader *r, int *notes) +{ + sp1_cnfg_end(&r->p); + struct sp1_midi_cfg def; + sp1_midi_cfg_defaults(&def); + int8_t owner[128]; + int16_t owner_line[128]; + memset(owner, -1, sizeof(owner)); + memset(owner_line, 0, sizeof(owner_line)); + + /* 1. Your lines, in file order: the first to name a CC keeps it. */ + for (int k = 0; k < r->n_order; k++) { + const int who = r->order[k]; + const int cc = r->user_cc[who]; + if (cc < 0) { + continue; + } + if (owner[cc] >= 0) { + struct msg m = { r->why, sizeof(r->why), 0u }; + msg_s(&m, "CC "); + msg_i(&m, cc); + msg_s(&m, " is already given to "); + msg_s(&m, who_name(owner[cc])); + msg_s(&m, " on line "); + msg_i(&m, owner_line[cc]); + msg_s(&m, ": this one gets none"); + midi_report(r, r->user_line[who], who == SP1_MIDI_WHO_SUSTAIN ? "sustain" + : dest_key(who), r->why); + r->user_cc[who] = -1; + continue; + } + owner[cc] = (int8_t)who; + owner_line[cc] = r->user_line[who]; + } + + /* 2. The defaults of everything you did not set: a CC one of your lines took is gone. */ + for (int who = 0; who <= SP1_MIDI_DESTS; who++) { + if (r->user_cc[who] != -2) { + continue; + } + const int cc = (who == SP1_MIDI_WHO_SUSTAIN) ? def.sustain_cc : def.dest_cc[who]; + if (cc < 0) { + r->user_cc[who] = -1; + continue; + } + if (owner[cc] >= 0) { + struct msg m = { r->why, sizeof(r->why), 0u }; + msg_s(&m, "note: takes CC "); + msg_i(&m, cc); + msg_s(&m, " from "); + msg_s(&m, who_name(who)); + msg_s(&m, ", which has no CC now"); + r->notes++; + r->problem(r->ctx, owner_line[cc], who_name(owner[cc]), r->why); + r->user_cc[who] = -1; + continue; + } + owner[cc] = (int8_t)who; + r->user_cc[who] = (int8_t)cc; + } + + /* 3. The tables. */ + memset(r->cfg->cc_dest, -1, sizeof(r->cfg->cc_dest)); + for (int d = 0; d < SP1_MIDI_DESTS; d++) { + r->cfg->dest_cc[d] = r->user_cc[d]; + if (r->user_cc[d] >= 0) { + r->cfg->cc_dest[r->user_cc[d]] = (int8_t)d; + } + } + r->cfg->sustain_cc = r->user_cc[SP1_MIDI_WHO_SUSTAIN]; + if (notes != NULL) { + *notes = r->notes; + } + return r->problems; +} diff --git a/firmware/src/sp1_cnfg.h b/firmware/src/sp1_cnfg.h new file mode 100644 index 0000000..124f793 --- /dev/null +++ b/firmware/src/sp1_cnfg.h @@ -0,0 +1,255 @@ +/* + * wakes-sp1 β€” the config files on the drive (#52): WAKES/CNFG/.cnfg. + * + * Pure C, no Zephyr, no storage: the storage thread reads a file a chunk at a time and feeds + * it here; the host suite (tools/host-tests/cnfgtest.c) feeds it broken files. + * + * ---- the rules (Adara, #52) ---- + * - config/.cnfg in the repository is the built-in DEFAULT, compiled into every + * image (tools/gen_.py, which fails the build on a bad default). End users never + * touch it: they edit the copy on the drive, which every image writes there when it is + * missing (Adara: no trip to the repo, no fresh flash, to get a file back). + * - Read at EVERY ON, before PRST and before audio. A line overrides its default; a line + * left out keeps it; a line that cannot be read keeps it too, and the log names it. + * - The same key twice: the FIRST is used, the later one is reported. + * - Nothing in a config file touches the power path, the watchdog, the flash layout or + * the USB descriptors (docs/SAFETY.md). + * + * ---- the format: ini ---- + * [section] names ignore case + * key = value keys ignore case; ; or # after whitespace starts a comment + * ; comment / # comment + * A UTF-8 byte order mark is skipped. Lines are at most SP1_CNFG_LINE_MAX bytes. + */ +#ifndef SP1_CNFG_H +#define SP1_CNFG_H + +#include +#include +#include + +#define SP1_CNFG_LINE_MAX 160 +#define SP1_CNFG_NAME_MAX 24 + +/* A problem with one line: `what` is the line (or its key), `why` the reason and what Wakes + * does instead. The firmware prints "CNFG line N: -- ". */ +typedef void (*sp1_cnfg_problem_fn)(void *ctx, int line, const char *what, const char *why); + +/* One `key = value` (section, key lowercased; value trimmed, comment removed). */ +typedef void (*sp1_cnfg_entry_fn)(void *ctx, int line, const char *section, const char *key, + const char *value); + +struct sp1_cnfg_parser { + sp1_cnfg_entry_fn entry; + sp1_cnfg_problem_fn problem; + void *ctx; + char section[SP1_CNFG_NAME_MAX]; + char buf[SP1_CNFG_LINE_MAX + 1]; + size_t n; + int line; + bool overlong; +}; + +void sp1_cnfg_begin(struct sp1_cnfg_parser *p, sp1_cnfg_entry_fn entry, + 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); + +/* ---------------------------------------------------------------- logs.cnfg */ + +/* What goes into the log file besides the lines that always do. */ +#define SP1_LOG_PERFORMANCE 0x01u +#define SP1_LOG_CONTROLS 0x02u +#define SP1_LOG_MIDI 0x04u +#define SP1_LOG_USB 0x08u +#define SP1_LOG_STORAGE 0x10u +#define SP1_LOG_ALL 0x1Fu + +struct sp1_logs_cfg { + bool enabled; + uint8_t cats; /* SP1_LOG_* bits */ +}; + +/* The built-in defaults, from config/logs.cnfg (sp1_logs_gen.h). */ +void sp1_logs_defaults(struct sp1_logs_cfg *c); + +/* Read logs.cnfg's text over the defaults already in *c. Returns the number of problems. */ +struct sp1_logs_reader { + struct sp1_cnfg_parser p; + struct sp1_logs_cfg *cfg; + sp1_cnfg_problem_fn problem; + void *ctx; + uint8_t seen; /* keys already set (the first wins) */ + char bad_section[SP1_CNFG_NAME_MAX]; + char what[SP1_CNFG_LINE_MAX + 4]; + int problems; +}; +void sp1_logs_begin(struct sp1_logs_reader *r, struct sp1_logs_cfg *c, + sp1_cnfg_problem_fn problem, void *ctx); +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. */ +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 + * "[+hh:mm:ss.mmm] " stamp (CPU, MIDI, STORE, ...). 0 = always written: startup, power, + * battery, warnings, and any line without a known tag. */ +uint8_t sp1_log_category(const char *line, size_t n); + +/* ---------------------------------------------------------------- engines.cnfg */ + +/* Two engine names are the same engine when their letters and digits match, case ignored + * (tools/gen_engines.py, name_key): "grain / formant", "grain-formant" and "Grain Formant" + * are one engine -- so a PRST file saved under an older spelling still loads. `canon` is + * NUL-terminated; `s` is `n` bytes. */ +static inline bool sp1_engine_name_eq(const char *canon, const char *s, size_t n) +{ + size_t i = 0u; + for (;;) { + while (*canon != '\0' && !((*canon >= 'a' && *canon <= 'z') || + (*canon >= 'A' && *canon <= 'Z') || + (*canon >= '0' && *canon <= '9'))) { + canon++; + } + while (i < n && !((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z') || + (s[i] >= '0' && s[i] <= '9'))) { + i++; + } + if (*canon == '\0' || i == n) { + return *canon == '\0' && i == n; + } + const char a = (*canon >= 'A' && *canon <= 'Z') ? (char)(*canon - 'A' + 'a') : *canon; + const char b = (s[i] >= 'A' && s[i] <= 'Z') ? (char)(s[i] - 'A' + 'a') : s[i]; + if (a != b) { + return false; + } + canon++; + i++; + } +} + +/* The stack: SP1_CNFG_SLOTS Plaits engine indices, SP1_CNFG_EMPTY for an empty slot (the + * same values as sp1_engines_gen.h's SP1_ENGINE_DEFAULT_STACK; sp1_cnfg.c checks). */ +#define SP1_CNFG_SLOTS 24 +#define SP1_CNFG_EMPTY 255u + +/* An engine of this build by name (sp1_engine_name_eq): its Plaits index, or -1. */ +int sp1_engine_index(const char *name, size_t n); + +/* The built-in stack (config/engines.cnfg at build time). */ +void sp1_engines_defaults(uint8_t out[SP1_CNFG_SLOTS]); + +/* Read engines.cnfg. The file is the WHOLE stack (Adara, #52): a slot it does not name is + * empty. Unlike logs.cnfg, a stack is all or nothing -- half of one would play engines in + * slots nobody chose -- so ANY problem (a name that is not an engine, an engine twice, a + * slot outside 1-24, a slot twice, another section, no engine at all) makes the whole file + * unusable and Wakes uses the built-in stack, every problem named in the log. */ +struct sp1_engines_reader { + struct sp1_cnfg_parser p; + sp1_cnfg_problem_fn problem; + void *ctx; + uint8_t stack[SP1_CNFG_SLOTS]; + uint32_t seen; /* slots set, bit per slot */ + uint32_t used; /* engines used, bit per Plaits index */ + char bad_section[SP1_CNFG_NAME_MAX]; + char what[SP1_CNFG_LINE_MAX + 4]; + int problems; + int filled; +}; +void sp1_engines_begin(struct sp1_engines_reader *r, sp1_cnfg_problem_fn problem, void *ctx); +void sp1_engines_feed(struct sp1_engines_reader *r, const char *text, size_t n); +/* The number of problems. `out` is the file's stack when there were none, otherwise the + * built-in stack. `*filled` = engines in `out`. */ +int sp1_engines_end(struct sp1_engines_reader *r, uint8_t out[SP1_CNFG_SLOTS], int *filled); + +/* ---------------------------------------------------------------- audio.cnfg */ + +/* How sound leaves the device: USB audio out's level and the speaker while a host takes it. + * The built-in values are config/audio.cnfg's (SP1_AUDIO_CFG_DEFAULTS, sp1_audio_gen.h, in + * this field order); sp1_audio.c holds the live copy (sp1_audio_set_config). */ +struct sp1_audio_cfg { + uint8_t parked; /* [usb] level: 1 parked, 0 vol */ + int8_t parked_db; /* [usb] parked_level, 0 .. -30 in 3 dB steps */ + uint8_t parked_step; /* ...as VOL's step, -parked_db / 3 */ + uint8_t speaker; /* [usb] speaker: 1 on while a host takes USB audio out */ +}; +void sp1_audio_cfg_defaults(struct sp1_audio_cfg *c); + +/* Line by line over the built-in values, like logs.cnfg. */ +struct sp1_audio_reader { + struct sp1_cnfg_parser p; + struct sp1_audio_cfg *cfg; + sp1_cnfg_problem_fn problem; + void *ctx; + uint8_t seen; + char bad_section[SP1_CNFG_NAME_MAX]; + char what[SP1_CNFG_LINE_MAX + 4]; + int problems; +}; +void sp1_audio_reader_begin(struct sp1_audio_reader *r, struct sp1_audio_cfg *c, + sp1_cnfg_problem_fn problem, void *ctx); +void sp1_audio_reader_feed(struct sp1_audio_reader *r, const char *text, size_t n); +int sp1_audio_reader_end(struct sp1_audio_reader *r); + +/* ---------------------------------------------------------------- midi.cnfg */ + +#include "sp1_midi_gen.h" /* SP1_MIDI_DESTS and the destination enum */ + +/* The MIDI script. The built-in values are config/midi.cnfg's (SP1_MIDI_CFG_DEFAULTS, + * sp1_midi_gen.h, in this field order); sp1_midi.cc holds the live copy + * (sp1_midi_set_config), which every thread reads and only main writes, at ON entry with the + * audio thread stopped. */ +struct sp1_midi_cfg { + int8_t channel; /* 0-15, or SP1_MIDI_OMNI */ + uint8_t priority; /* stmlib NoteStackFlags: 0 last, 1 low, 2 high */ + uint8_t legato; /* Yarns legato_mode: 0 off, 1 auto, 2 on */ + uint8_t portamento; /* Yarns: 0 none, 1-50 time, 51-101 rate */ + uint8_t bend_range; /* semitones, until RPN 0 says otherwise */ + int8_t sustain_cc; /* -1 = no sustain pedal */ + uint8_t smooth_ms; /* 0-200 */ + uint8_t pickup; /* SP1_MIDI_PICKUP_SUM / _SHARED / _TAKEOVER */ + uint8_t clock; /* 1 = Marbles follows MIDI clock + transport */ + int16_t clock_lead_ms; /* 0-200; -1 auto, -2 notes */ + int8_t vel_dest; /* [bind] velocity: a destination, or -1 */ + int8_t at_dest; /* [bind] aftertouch */ + float vel_depth; /* -1 .. 1 */ + float at_depth; + int8_t dest_cc[SP1_MIDI_DESTS]; /* destination -> its CC (coarse half), or -1 */ + int8_t cc_dest[128]; /* CC -> destination, or -1 */ +}; +void sp1_midi_cfg_defaults(struct sp1_midi_cfg *c); + +/* Line by line over the built-in values, like logs.cnfg -- plus the CC rule (Adara, #52): + * - a CC you give a parameter (or the sustain pedal) is TAKEN from whichever parameter had + * it by default, which gets none (a note in the log, not a problem); + * - two of your lines on the same CC: the FIRST keeps it, the later gets none (a problem); + * - CC 33-63 are the fine halves of 1-31 and cannot be given; reserved CCs neither. + * `velocity = none` / `aftertouch = none` remove a binding. */ +#define SP1_MIDI_WHO_SUSTAIN SP1_MIDI_DESTS +struct sp1_midi_reader { + struct sp1_cnfg_parser p; + struct sp1_midi_cfg *cfg; + sp1_cnfg_problem_fn problem; + void *ctx; + uint16_t seen_midi; /* [midi] keys set (the first wins) */ + uint32_t seen_dest; /* destinations set */ + uint8_t seen_bind; + int8_t user_cc[SP1_MIDI_DESTS + 1]; /* -2 not given, -1 none, else the CC; */ + int16_t user_line[SP1_MIDI_DESTS + 1]; /* index SP1_MIDI_WHO_SUSTAIN = sustain */ + uint8_t order[SP1_MIDI_DESTS + 1]; /* the CC lines in file order */ + uint8_t n_order; + char bad_section[SP1_CNFG_NAME_MAX]; + char what[SP1_CNFG_LINE_MAX + 4]; + char why[160]; + int problems; + int notes; /* defaults that gave up their CC */ +}; +void sp1_midi_reader_begin(struct sp1_midi_reader *r, struct sp1_midi_cfg *c, + sp1_cnfg_problem_fn problem, void *ctx); +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); + +#endif /* SP1_CNFG_H */ diff --git a/firmware/src/sp1_controls.c b/firmware/src/sp1_controls.c index 8554626..3dd1e68 100644 --- a/firmware/src/sp1_controls.c +++ b/firmware/src/sp1_controls.c @@ -30,6 +30,7 @@ static bool ok; static uint16_t lad_raw[2]; static uint16_t fad_raw[SP1_NUM_FADERS]; /* last VALID fader sample */ +static void track_touch(void); /* shutdown suppression: below the scan */ static uint16_t fad_scratch[SP1_NUM_FADERS]; /* this scan, maybe sagged */ static bool fad_valid; static enum sp1_rail rail; @@ -474,6 +475,9 @@ void sp1_controls_scan(void) last_idle[i] = fad_raw[i]; } } + if (fad_valid) { + track_touch(); /* a rejected scan is no evidence either way */ + } decode_buttons(); } @@ -700,11 +704,34 @@ static uint16_t why_from, why_to; * exact 0 when parked, and 2x oversampling keeps mid-travel quiet), and far below * any deliberate move -- a real shift gesture sweeps hundreds of counts. */ #define SP1_TOUCH_COUNTS 80u +/* ...and it must be away from the mark on this many VALID scans in a row (2 = 16 ms), the + * buttons' own debounce. One reading 82 counts off on a fader parked at 0 suppressed a + * shutdown on 2026-10-15 (0006.LOGS) with nobody touching it; the logged positions show no + * sign of a worn fader (F4 is the quietest at the bottom), so a lone spike is the likely + * cause. A real move lasts far longer than 16 ms, so shifting is unchanged. This only + * decides whether the 3 s animation starts; the 30 s backstop never looks (rule 5a). */ +#define SP1_TOUCH_SCANS 2u +static uint8_t touch_run[SP1_NUM_FADERS]; /* valid scans in a row past the threshold */ + +static void track_touch(void) +{ + for (int i = 0; i < SP1_NUM_FADERS; i++) { + const uint16_t v = fad_raw[i]; + const uint16_t d = (v > mark_fad[i]) ? (uint16_t)(v - mark_fad[i]) + : (uint16_t)(mark_fad[i] - v); + if (!marked || d < SP1_TOUCH_COUNTS) { + touch_run[i] = 0u; + } else if (touch_run[i] < 255u) { + touch_run[i]++; + } + } +} void sp1_controls_activity_mark(void) { for (int i = 0; i < SP1_NUM_FADERS; i++) { mark_fad[i] = fad_raw[i]; + touch_run[i] = 0u; } marked = true; } @@ -712,6 +739,9 @@ void sp1_controls_activity_mark(void) void sp1_controls_activity_clear(void) { marked = false; + for (int i = 0; i < SP1_NUM_FADERS; i++) { + touch_run[i] = 0u; + } } bool sp1_controls_activity(void) @@ -748,9 +778,7 @@ bool sp1_controls_activity(void) * move through sag -- the sagged samples were never stored. */ for (int i = 0; i < SP1_NUM_FADERS; i++) { const uint16_t v = fad_raw[i]; - const uint16_t d = (v > mark_fad[i]) ? (uint16_t)(v - mark_fad[i]) - : (uint16_t)(mark_fad[i] - v); - if (d >= SP1_TOUCH_COUNTS) { + if (touch_run[i] >= SP1_TOUCH_SCANS) { /* past the threshold, and stayed */ why_kind = WHY_FADER; why_index = i; why_from = mark_fad[i]; diff --git a/firmware/src/sp1_logbuf.c b/firmware/src/sp1_logbuf.c index 4ee7e97..06bf2b9 100644 --- a/firmware/src/sp1_logbuf.c +++ b/firmware/src/sp1_logbuf.c @@ -1,5 +1,6 @@ /* wakes-sp1 β€” the stored log. See sp1_logbuf.h. */ #include "sp1_logbuf.h" +#include "sp1_logring.h" #include #include @@ -7,7 +8,7 @@ #include #define LB_SIZE ((uint32_t)CONFIG_SP1_LOGBUF_KB * 1024u) -#define LB_MAGIC 0x574B4C47u /* "WKLG" */ +#define LB_MAGIC 0x324B4C47u /* "GLK2": the ring + file cursor (#52) */ #define STEP_MAX 512u /* bytes played back per control tick, then * on to the end of that line */ #define PACE 48u /* bytes per 1 ms: under CDC ACM's 64 B / frame */ @@ -15,14 +16,16 @@ BUILD_ASSERT(CONFIG_SP1_LOGBUF_KB >= 4, "the stored log needs at least 4 KB"); /* ---- the buffer: survives a soft reset if RAM does (sp1_logbuf.h) ---- */ +/* The file's cursor lives in the ring too, so lines a reset cut off before they reached the + * drive are still written at the next ON (#52). */ static __noinit struct { uint32_t magic; - uint32_t size; - uint32_t head; /* next byte written */ - uint32_t len; /* bytes held, <= size */ + struct sp1_logring ring; uint32_t boots; /* boots this log has run across */ } hdr; static __noinit char data[LB_SIZE]; +static bool continued; /* this boot carries on a kept log */ +static uint32_t boot_resetreas; static printk_hook_fn_t next; /* the console's own printk output */ static struct k_spinlock lock; @@ -35,11 +38,7 @@ static uint32_t rp_pos, rp_left; static void put(char c) { - data[hdr.head] = c; - hdr.head = (hdr.head + 1u == LB_SIZE) ? 0u : hdr.head + 1u; - if (hdr.len < LB_SIZE) { - hdr.len++; - } + sp1_logring_put(&hdr.ring, data, c); } static void put_str(const char *s) @@ -95,17 +94,16 @@ static int hook(int c) void sp1_logbuf_init(uint32_t resetreas) { - const bool kept = hdr.magic == LB_MAGIC && hdr.size == LB_SIZE && - hdr.head < LB_SIZE && hdr.len <= LB_SIZE; + const bool kept = hdr.magic == LB_MAGIC && sp1_logring_valid(&hdr.ring, LB_SIZE); if (!kept) { hdr.magic = LB_MAGIC; - hdr.size = LB_SIZE; - hdr.head = 0u; - hdr.len = 0u; + sp1_logring_init(&hdr.ring, LB_SIZE); hdr.boots = 0u; } hdr.boots++; - if (kept && hdr.len > 0u) { + boot_resetreas = resetreas; + continued = kept && hdr.ring.len > 0u; + if (continued) { char m[96]; snprintk(m, sizeof(m), "\n=== RESET (resetreas 0x%08x): the log above is the boot before; " @@ -133,8 +131,8 @@ static void out_str(const char *s) void sp1_logbuf_replay_start(void) { k_spinlock_key_t key = k_spin_lock(&lock); - rp_left = hdr.len; - rp_pos = (hdr.head + LB_SIZE - hdr.len) % LB_SIZE; + rp_left = hdr.ring.len; + rp_pos = sp1_logring_oldest(&hdr.ring); k_spin_unlock(&lock, key); char m[112]; snprintk(m, sizeof(m), "\n=== STORED LOG: %u bytes, oldest first, [+uptime] per line; " @@ -184,3 +182,66 @@ void sp1_logbuf_replay_step(void) out_str("=== STORED LOG: end ===\n"); } } + +/* ---- the log file (#52) ---- */ + +bool sp1_logbuf_continued(void) +{ + return continued; +} + +uint32_t sp1_logbuf_resetreas(void) +{ + return boot_resetreas; +} + +size_t sp1_logbuf_file_take(char *out, size_t max, uint32_t *lost) +{ + /* One line per lock: at most SP1_LOGBUF_TAKE_MAX bytes copied with interrupts held off. */ + if (max > SP1_LOGBUF_TAKE_MAX) { + max = SP1_LOGBUF_TAKE_MAX; + } + k_spinlock_key_t key = k_spin_lock(&lock); + const size_t n = sp1_logring_take(&hdr.ring, data, out, max, lost); + k_spin_unlock(&lock, key); + return n; +} + +size_t sp1_logbuf_file_take_before_standby(char *out, size_t max, uint32_t *lost) +{ + if (max > SP1_LOGBUF_TAKE_MAX) { + max = SP1_LOGBUF_TAKE_MAX; + } + k_spinlock_key_t key = k_spin_lock(&lock); + const size_t n = sp1_logring_take_before_standby(&hdr.ring, data, out, max, lost); + k_spin_unlock(&lock, key); + return n; +} + +void sp1_logbuf_file_pause(void) +{ + k_spinlock_key_t key = k_spin_lock(&lock); + sp1_logring_pause(&hdr.ring); + k_spin_unlock(&lock, key); +} + +void sp1_logbuf_file_resume(void) +{ + k_spinlock_key_t key = k_spin_lock(&lock); + sp1_logring_resume(&hdr.ring); + k_spin_unlock(&lock, key); +} + +void sp1_logbuf_file_skip(void) +{ + k_spinlock_key_t key = k_spin_lock(&lock); + sp1_logring_skip(&hdr.ring); + k_spin_unlock(&lock, key); +} + +void sp1_logbuf_file_keep(void) +{ + k_spinlock_key_t key = k_spin_lock(&lock); + sp1_logring_keep(&hdr.ring); + k_spin_unlock(&lock, key); +} diff --git a/firmware/src/sp1_logbuf.h b/firmware/src/sp1_logbuf.h index 7231a34..972c4b5 100644 --- a/firmware/src/sp1_logbuf.h +++ b/firmware/src/sp1_logbuf.h @@ -8,8 +8,9 @@ * after the banner, then carries on live. Keep Wakes ON after the session, plug it into the PC, * start the logger: the session is in the file. * - * - CONFIG_SP1_LOGBUF_KB of RAM (96 KB: ~14 minutes at a session's ~120 bytes/s). When it is - * full the OLDEST lines go; the newest are always there. + * - CONFIG_SP1_LOGBUF_KB of RAM (16 KB: ~2 minutes at a session's ~120 bytes/s; 96 KB until + * the log went to the drive, #52). When it is full the OLDEST lines go; the newest are + * always there. * - Every stored line starts with the device's uptime, "[+hh:mm:ss.mmm]", because the * logger's own timestamps on a played-back line are the time of the dump, not of the event. * - It sits in .noinit, so a soft reset -- the watchdog, a fault, sp1_power_off with USB -- @@ -22,12 +23,18 @@ * keep feeding the watchdog. A full buffer takes a few seconds; the controls answer a little * slowly meanwhile. * + * - THE LOG FILE (#52): the storage thread takes whole lines from here every 5 s and writes + * them to WAKES/LOGS/ on the drive (sp1_store.h). Its cursor lives in the ring + * (sp1_logring.h), in .noinit with the rest, so lines a reset cut off before they reached + * the drive are written at the next ON. STANDBY's lines are not for the file (Adara). + * * Nothing here is on the power path, and the audio thread never prints (rule since M2). */ #ifndef SP1_LOGBUF_H #define SP1_LOGBUF_H #include +#include #include /* Once, in main(), after the console is up and before anything else prints. Wraps printk's @@ -44,4 +51,25 @@ void sp1_logbuf_replay_stop(void); bool sp1_logbuf_replaying(void); void sp1_logbuf_replay_step(void); +/* ---- the log file (#52) ---- + * This boot carries on a log kept across a soft reset (the "=== RESET" marker): the crash and + * this boot's first lines go to the interrupted session's file, the next ON starts a new one. */ +bool sp1_logbuf_continued(void); +uint32_t sp1_logbuf_resetreas(void); + +/* Storage thread: the next line for the file (sp1_logring_take), at most SP1_LOGBUF_TAKE_MAX + * bytes, taken under the lock -- one line's copy with interrupts held off, a few us. */ +#define SP1_LOGBUF_TAKE_MAX 256u +size_t sp1_logbuf_file_take(char *out, size_t max, uint32_t *lost); +/* The same, only for lines from before the last STANDBY (sp1_logring_take_before_standby). */ +size_t sp1_logbuf_file_take_before_standby(char *out, size_t max, uint32_t *lost); + +/* Main thread: STANDBY entry / ON entry (STANDBY is not logged to the drive), and "logging + * is off this ON" (nothing written so far is owed to the file). */ +void sp1_logbuf_file_pause(void); +void sp1_logbuf_file_resume(void); +void sp1_logbuf_file_skip(void); +/* Storage thread: logging is on this ON (undoes _skip's "not owed until the ON ends"). */ +void sp1_logbuf_file_keep(void); + #endif /* SP1_LOGBUF_H */ diff --git a/firmware/src/sp1_logring.c b/firmware/src/sp1_logring.c new file mode 100644 index 0000000..c4862cd --- /dev/null +++ b/firmware/src/sp1_logring.c @@ -0,0 +1,218 @@ +/* wakes-sp1 β€” the stored log's ring and the file's cursor. See sp1_logring.h. */ +#include "sp1_logring.h" + +#include + +/* a < b, positions compared by difference (sp1_logring.h). */ +static bool before(uint32_t a, uint32_t b) +{ + return (int32_t)(a - b) < 0; +} + +/* The index in data[] of absolute position p, which must be held. */ +static uint32_t at(const struct sp1_logring *r, uint32_t p) +{ + return (r->head + r->size - (r->total - p)) % r->size; +} + +void sp1_logring_init(struct sp1_logring *r, uint32_t size) +{ + memset(r, 0, sizeof(*r)); + r->size = size; +} + +bool sp1_logring_valid(struct sp1_logring *r, uint32_t size) +{ + if (r->size != size || size == 0u || r->head >= size || r->len > size || + r->paused > 1u || r->gap > 1u || r->discard > 1u) { + return false; + } + /* A cursor ahead of the writer is nonsense: start the file at the oldest line held. */ + if (before(r->total, r->frd)) { + r->frd = r->total - r->len; + } + if (r->gap && (before(r->gap_to, r->gap_from) || before(r->total, r->gap_to))) { + r->gap = 0u; + } + if (r->paused && before(r->total, r->gap_from)) { + r->paused = 0u; + } + return true; +} + +void sp1_logring_put(struct sp1_logring *r, char *data, char c) +{ + data[r->head] = c; + r->head = (r->head + 1u == r->size) ? 0u : r->head + 1u; + if (r->len < r->size) { + r->len++; + } + r->total++; +} + +uint32_t sp1_logring_oldest(const struct sp1_logring *r) +{ + return (r->head + r->size - r->len) % r->size; +} + +void sp1_logring_pause(struct sp1_logring *r) +{ + if (r->paused) { + return; + } + /* An ON with logging off: none of its lines are owed, the ones since the skip included. */ + if (r->discard) { + r->frd = r->total; + r->gap = 0u; + } + /* A closed gap the cursor has not reached yet stretches to cover this one too: the + * lines between them (an ON whose log never reached the drive) go with it. */ + if (!r->gap) { + r->gap_from = r->total; + } + r->gap = 0u; + r->paused = 1u; +} + +void sp1_logring_resume(struct sp1_logring *r) +{ + if (!r->paused) { + return; + } + r->paused = 0u; + r->gap_to = r->total; + r->gap = (r->gap_to != r->gap_from) ? 1u : 0u; +} + +void sp1_logring_skip(struct sp1_logring *r) +{ + r->frd = r->total; + r->gap = 0u; + r->discard = 1u; + if (r->paused) { + r->gap_from = r->total; + } +} + +void sp1_logring_keep(struct sp1_logring *r) +{ + r->discard = 0u; +} + +static size_t take_lines(struct sp1_logring *r, const char *data, char *out, size_t max, + uint32_t *lost, bool before_standby); + +size_t sp1_logring_take(struct sp1_logring *r, const char *data, char *out, size_t max, + uint32_t *lost) +{ + return take_lines(r, data, out, max, lost, false); +} + +size_t sp1_logring_take_before_standby(struct sp1_logring *r, const char *data, char *out, + size_t max, uint32_t *lost) +{ + return take_lines(r, data, out, max, lost, true); +} + +static size_t take_lines(struct sp1_logring *r, const char *data, char *out, size_t max, + uint32_t *lost, bool before_standby) +{ + bool resync = false; + + /* 1. Overwritten before the file took it. The gap's own bytes are not a loss. */ + const uint32_t oldest = r->total - r->len; + if (before(r->frd, oldest)) { + uint32_t gone = oldest - r->frd; + if (r->gap || r->paused) { + const uint32_t gend = r->paused ? r->total : r->gap_to; + const uint32_t lo = before(r->frd, r->gap_from) ? r->gap_from : r->frd; + const uint32_t hi = before(oldest, gend) ? oldest : gend; + if (before(lo, hi)) { + gone -= hi - lo; + } + } + *lost += gone; + r->frd = oldest; + resync = true; /* mid-line, most likely */ + } + + uint32_t limit = r->total; + bool cut = false; + if (before_standby) { + /* Only what the last ON still owes ITS file: up to where STANDBY began, never + * across. gap_from marks that whether or not STANDBY printed anything (an empty + * STANDBY leaves gap_from == gap_to, and no gap to jump), and while it lasts. */ + if (!before(r->frd, r->gap_from)) { + return 0u; + } + limit = r->gap_from; + cut = true; + } else { + /* 2. Over a closed gap. Resume lands between lines, so no resync after it. */ + if (r->gap && !before(r->frd, r->gap_from)) { + if (before(r->frd, r->gap_to)) { + r->frd = r->gap_to; + resync = false; + } + r->gap = 0u; + } + + /* 3. How far the file may read: to the gap, if there is one ahead. While paused, + * everything from gap_from on is STANDBY's (the cursor waits there for the + * resume); after step 2 a closed gap is always ahead of the cursor. */ + if (r->paused) { + if (!before(r->frd, r->gap_from)) { + return 0u; + } + limit = r->gap_from; + cut = true; + } else if (r->gap) { + limit = r->gap_from; + cut = true; + } + } + + if (resync) { + while (before(r->frd, limit) && data[at(r, r->frd)] != '\n') { + r->frd++; + (*lost)++; + } + if (!before(r->frd, limit)) { + return 0u; + } + r->frd++; /* past the '\n' */ + (*lost)++; + } + if (!before(r->frd, limit)) { + return 0u; + } + + /* 4. One line, or a max-byte piece of a long one. */ + const uint32_t avail = limit - r->frd; + const uint32_t scan = avail < max ? avail : (uint32_t)max; + uint32_t i = at(r, r->frd); + size_t n = 0u; + for (uint32_t k = 0u; k < scan; k++) { + if (data[i] == '\n') { + n = (size_t)k + 1u; + break; + } + i = (i + 1u == r->size) ? 0u : i + 1u; + } + if (n == 0u) { + if (avail >= max) { + n = max; + } else if (cut) { + n = avail; /* the gap cuts this line */ + } else { + return 0u; /* still being written */ + } + } + i = at(r, r->frd); + for (size_t k = 0u; k < n; k++) { + out[k] = data[i]; + i = (i + 1u == r->size) ? 0u : i + 1u; + } + r->frd += (uint32_t)n; + return n; +} diff --git a/firmware/src/sp1_logring.h b/firmware/src/sp1_logring.h new file mode 100644 index 0000000..cb3972a --- /dev/null +++ b/firmware/src/sp1_logring.h @@ -0,0 +1,74 @@ +/* + * wakes-sp1 β€” the stored log's ring and the log file's cursor into it (#52). + * + * Pure C, no Zephyr: sp1_logbuf.c owns the memory and the lock and calls these under it; + * the host suite (tools/host-tests/cnfgtest.c) drives them through overruns and gaps that + * would take hours to make on the device. + * + * Positions are ABSOLUTE: `total` counts every byte ever written (mod 2^32), and the file's + * cursor and the STANDBY gap are values of it. Compared by difference, so the wrap at 4 GB + * (about a year at a session's ~120 B/s) is harmless. + * + * ---- what the file gets ---- + * Whole lines, oldest first, from `frd` on. Not: + * - STANDBY (Adara, #52): sp1_logring_pause() at STANDBY entry and _resume() at ON entry + * mark a gap the cursor jumps over. Boot lines before the first STANDBY are kept. + * - Lines the ring overwrote before the file took them: counted in `lost` (bytes; the + * gap's own bytes are not counted), and the cursor moves to the next whole line. + */ +#ifndef SP1_LOGRING_H +#define SP1_LOGRING_H + +#include +#include +#include + +struct sp1_logring { + uint32_t size; /* bytes of data[] */ + uint32_t head; /* next byte written */ + uint32_t len; /* bytes held, <= size */ + uint32_t total; /* bytes ever written */ + uint32_t frd; /* the file's cursor: the next byte it takes */ + uint32_t gap_from; /* STANDBY's lines are [gap_from, gap_to) */ + uint32_t gap_to; + uint8_t paused; /* in STANDBY: nothing from gap_from on, yet */ + uint8_t gap; /* a closed gap waits for the cursor */ + uint8_t discard; /* logging is off this ON: its lines are not owed */ + uint8_t pad; +}; + +/* An empty ring over `size` bytes; the cursor at the start. */ +void sp1_logring_init(struct sp1_logring *r, uint32_t size); + +/* A ring found in .noinit after a reset: true if every field is consistent (then the file's + * cursor is clamped into what the ring still holds), false if it must be re-initialised. */ +bool sp1_logring_valid(struct sp1_logring *r, uint32_t size); + +void sp1_logring_put(struct sp1_logring *r, char *data, char c); + +/* The oldest byte still held, as an index into data[]. */ +uint32_t sp1_logring_oldest(const struct sp1_logring *r); + +/* STANDBY entry / ON entry. A second pause before a resume keeps the first. */ +void sp1_logring_pause(struct sp1_logring *r); +void sp1_logring_resume(struct sp1_logring *r); + +/* Logging is off this ON: the file is not owed anything written so far, NOR anything written + * until the ON ends -- the pause at STANDBY entry drops this ON's lines too, so they cannot + * reach the next ON's file (found in Adara's test, 0007.LOGS, 2026-10-15). Until _keep(). */ +void sp1_logring_skip(struct sp1_logring *r); +/* Logging is on this ON: from here the lines are owed to the file again. */ +void sp1_logring_keep(struct sp1_logring *r); + +/* The next line for the file into out[0..max), max >= 2: its length (with its '\n'), or 0 + * if no whole line is waiting. A line longer than max comes in max-byte pieces. A partial + * line is taken only where a gap cuts it. `*lost` += bytes the ring overwrote first. */ +size_t sp1_logring_take(struct sp1_logring *r, const char *data, char *out, size_t max, + uint32_t *lost); +/* As _take, but only lines from before the last STANDBY began: what the previous ON still owes + * its own file (its closing lines, or a 30 s backstop's tail) when this ON starts a new one. + * 0 once the cursor reaches STANDBY; never crosses it. */ +size_t sp1_logring_take_before_standby(struct sp1_logring *r, const char *data, char *out, + size_t max, uint32_t *lost); + +#endif /* SP1_LOGRING_H */ diff --git a/firmware/src/sp1_midi.cc b/firmware/src/sp1_midi.cc index bd139bd..ebb4a52 100644 --- a/firmware/src/sp1_midi.cc +++ b/firmware/src/sp1_midi.cc @@ -19,6 +19,7 @@ #define SP1_MIDI_GEN_TABLES #include "sp1_midi.h" #include "sp1_synth.h" // SP1_SYNTH_BLOCK: MIDI runs once per Plaits block (#32) +#include "sp1_cnfg.h" // struct sp1_midi_cfg: the script, live (#52) #include #include @@ -87,6 +88,12 @@ bool trig_pending; uint8_t velocity; // latest note's, Yarns' mod_velocity_ uint8_t aftertouch; +// ---- the MIDI script, LIVE (#52) ---- +// config/midi.cnfg's built-in values until main hands over the drive's WAKES/CNFG/midi.cnfg +// at ON entry (sp1_midi_set_config), with the audio thread stopped. The audio thread, the USB +// interrupt and main all read it; only that call writes it. +sp1_midi_cfg g_cfg = SP1_MIDI_CFG_DEFAULTS; + // Yarns Voice: the glide, in semitones. float note_source = 60.0f, note_target = 60.0f, note_now = 60.0f; float porta_phase = 1.0f, porta_inc = 0.0f; @@ -203,10 +210,10 @@ volatile bool out_usb; // main: a host is taking USB audio // they have said, auto (lead_learned < 0). A fixed number of ms otherwise. float lead_learned = -1.0f; float Lead() { - if (SP1_MIDI_CLOCK_LEAD_MS >= 0) { - return static_cast(SP1_MIDI_CLOCK_LEAD_MS) * static_cast(kBlocksPerMs); + if (g_cfg.clock_lead_ms >= 0) { + return static_cast(g_cfg.clock_lead_ms) * static_cast(kBlocksPerMs); } - if (SP1_MIDI_CLOCK_LEAD_MS == -2 && lead_learned >= 0.0f) { + if (g_cfg.clock_lead_ms == -2 && lead_learned >= 0.0f) { return lead_learned; } return out_usb ? kLeadAutoUsbBlocks : kLeadAutoBlocks; @@ -289,12 +296,12 @@ bool prev_begin_valid; inline float Clamp(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); } -// ---- the pickup setting (config/midi.ini `pickup`, Adara, M5a round 4) ---- +// ---- the pickup setting (midi.cnfg `pickup`, Adara, M5a round 4) ---- // sum: a CC is an OFFSET on its fader. shared / takeover: a CC is a POSITION on the fader's // own value, which the UI moves through sp1_midi_drive() -- so there it is no offset at all. // MODEL has no fader and is an offset in every setting. -constexpr bool CcIsOffset(int d) { - return SP1_MIDI_PICKUP == SP1_MIDI_PICKUP_SUM || d == SP1_MIDI_D_MODEL; +inline bool CcIsOffset(int d) { + return g_cfg.pickup == SP1_MIDI_PICKUP_SUM || d == SP1_MIDI_D_MODEL; } // ---- Plaits' catch-up: plaits/pot_controller.h, POT_STATE_CATCHING_UP (Emilie Gillet, MIT) ---- @@ -390,11 +397,12 @@ void Refresh() { note_now = note_source + (note_target - note_source) * k; } -const stmlib::NoteStackFlags kPriority = - static_cast(SP1_MIDI_PRIORITY); +stmlib::NoteStackFlags Priority() { + return static_cast(g_cfg.priority); +} uint8_t Top() { - return stack.note_by_priority(kPriority).note; + return stack.note_by_priority(Priority()).note; } // ---- Yarns part.cc, the 1M (mono) branches ------------------------------------------------ @@ -412,19 +420,19 @@ void NoteOn(uint8_t note, uint8_t vel) { // the same pitch is one long note. Either way the note-off of the first one will not end // it (on_count). stack.NoteOn(note, vel); - if (SP1_MIDI_LEGATO == 0) { - Glide(note, vel, SP1_MIDI_PORTAMENTO, true); + if (g_cfg.legato == 0) { + Glide(note, vel, g_cfg.portamento, true); } return; } const uint8_t before = Top(); stack.NoteOn(note, vel); - const stmlib::NoteEntry& after = stack.note_by_priority(kPriority); + const stmlib::NoteEntry& after = stack.note_by_priority(Priority()); if (before != after.note) { const bool legato = stack.size() > 1; Glide(after.note, after.velocity, - (SP1_MIDI_LEGATO == 1) && !legato ? 0 : SP1_MIDI_PORTAMENTO, - (SP1_MIDI_LEGATO == 0) || !legato); + (g_cfg.legato == 1) && !legato ? 0 : g_cfg.portamento, + (g_cfg.legato == 0) || !legato); } } @@ -438,10 +446,10 @@ void InternalNoteOff(uint8_t note) { tail = true; } } else { - const stmlib::NoteEntry& after = stack.note_by_priority(kPriority); + const stmlib::NoteEntry& after = stack.note_by_priority(Priority()); if (before != after.note) { // Back to a key that is still held: slide there, and in legato off strike again. - Glide(after.note, after.velocity, SP1_MIDI_PORTAMENTO, SP1_MIDI_LEGATO == 0); + Glide(after.note, after.velocity, g_cfg.portamento, g_cfg.legato == 0); } } } @@ -534,11 +542,11 @@ void Publish(int d) { // their depth, whichever way the CC reads. Aimed at LEVEL they shape the gate height // instead (GateHeight()). float bound = 0.0f; - if (SP1_MIDI_VELOCITY_DEST == d && d != SP1_MIDI_D_LEVEL) { - bound += SP1_MIDI_VELOCITY_DEPTH * static_cast(velocity) / 127.0f; + if (g_cfg.vel_dest == d && d != SP1_MIDI_D_LEVEL) { + bound += g_cfg.vel_depth * static_cast(velocity) / 127.0f; } - if (SP1_MIDI_AFTERTOUCH_DEST == d && d != SP1_MIDI_D_LEVEL) { - bound += SP1_MIDI_AFTERTOUCH_DEPTH * static_cast(aftertouch) / 127.0f; + if (g_cfg.at_dest == d && d != SP1_MIDI_D_LEVEL) { + bound += g_cfg.at_depth * static_cast(aftertouch) / 127.0f; } const bool offset = CcIsOffset(d); target_bi[d] = Clamp((offset ? CcOffset(d, true) : 0.0f) + bound, -1.0f, 1.0f); @@ -647,11 +655,11 @@ void ResetControllers() { // The gate's height. 1 unless velocity or aftertouch is bound to LEVEL. float GateHeight() { float h = 1.0f; - if (SP1_MIDI_VELOCITY_DEST == SP1_MIDI_D_LEVEL) { - h *= 1.0f + SP1_MIDI_VELOCITY_DEPTH * (static_cast(velocity) / 127.0f - 1.0f); + if (g_cfg.vel_dest == SP1_MIDI_D_LEVEL) { + h *= 1.0f + g_cfg.vel_depth * (static_cast(velocity) / 127.0f - 1.0f); } - if (SP1_MIDI_AFTERTOUCH_DEST == SP1_MIDI_D_LEVEL) { - h *= 1.0f + SP1_MIDI_AFTERTOUCH_DEPTH * (static_cast(aftertouch) / 127.0f - 1.0f); + if (g_cfg.at_dest == SP1_MIDI_D_LEVEL) { + h *= 1.0f + g_cfg.at_depth * (static_cast(aftertouch) / 127.0f - 1.0f); } return Clamp(h, 0.0f, 1.0f); } @@ -668,7 +676,7 @@ bool RpnBendSelected() { } void ControlChange(uint8_t cc, uint8_t v) { - if (SP1_MIDI_SUSTAIN_CC >= 0 && cc == SP1_MIDI_SUSTAIN_CC) { + if (g_cfg.sustain_cc >= 0 && cc == static_cast(g_cfg.sustain_cc)) { Sustain(v >= 64); return; } @@ -713,7 +721,7 @@ void ControlChange(uint8_t cc, uint8_t v) { } int d; if (cc >= 32 && cc < 64) { - d = SP1_MIDI_CC_DEST[cc - 32]; // the fine half of a 14-bit pair + d = g_cfg.cc_dest[cc - 32]; // the fine half of a 14-bit pair if (d < 0) { ++st_ignored; return; @@ -722,7 +730,7 @@ void ControlChange(uint8_t cc, uint8_t v) { cc_has_lsb[d] = true; cc_present[d] = true; } else { - d = SP1_MIDI_CC_DEST[cc]; + d = g_cfg.cc_dest[cc]; if (d < 0) { ++st_ignored; return; @@ -743,7 +751,7 @@ void ControlChange(uint8_t cc, uint8_t v) { __attribute__((noinline)) void Process(const Event& e) { const uint8_t status = e.msg[0]; const uint8_t type = status & 0xF0u; - if (SP1_MIDI_CHANNEL != SP1_MIDI_OMNI && (status & 0x0Fu) != SP1_MIDI_CHANNEL) { + if (g_cfg.channel != SP1_MIDI_OMNI && (status & 0x0Fu) != static_cast(g_cfg.channel)) { st_ignored = st_ignored + 1u; return; } @@ -755,8 +763,8 @@ __attribute__((noinline)) void Process(const Event& e) { session = true; st_notes = st_notes + 1u; NoteOn(d1, d2); - if (SP1_MIDI_VELOCITY_DEST >= 0) { - Publish(SP1_MIDI_VELOCITY_DEST); + if (g_cfg.vel_dest >= 0) { + Publish(g_cfg.vel_dest); } break; } @@ -776,8 +784,8 @@ __attribute__((noinline)) void Process(const Event& e) { case 0xD0: session = true; aftertouch = d1; - if (SP1_MIDI_AFTERTOUCH_DEST >= 0) { - Publish(SP1_MIDI_AFTERTOUCH_DEST); + if (g_cfg.at_dest >= 0) { + Publish(g_cfg.at_dest); } break; default: @@ -918,7 +926,7 @@ void NoteSkew(uint32_t cycles) { } void ClockRealTime(uint8_t b, uint32_t cycles) { - if (!SP1_MIDI_CLOCK) { + if (!g_cfg.clock) { return; } switch (b) { @@ -1051,7 +1059,7 @@ void ClockBlock(uint32_t blocks) { // they ARRIVE, so a note that arrives `mean` before its tick lines up with Marbles when // Marbles leads the tick by -mean. Only from quantised notes (a tight window); a lead // never goes below 0 (a clock sent EARLY would need Marbles to lag) or past 200 ms. - if (SP1_MIDI_CLOCK_LEAD_MS == -2 && sk_n >= 8u && sd < 1000.0f) { + if (g_cfg.clock_lead_ms == -2 && sk_n >= 8u && sd < 1000.0f) { float lead_ms = -mean * 1e-3f; lead_ms = lead_ms < 0.0f ? 0.0f : (lead_ms > 200.0f ? 200.0f : lead_ms); lead_learned = lead_ms * static_cast(kBlocksPerMs); @@ -1080,16 +1088,16 @@ void Neutral() { clk_b = 0.0f; ClockForgetTempo(); pub_bpm10 = 0; - if (SP1_MIDI_CLOCK_LEAD_MS == -2) { + if (g_cfg.clock_lead_ms == -2) { lead_learned = -1.0f; // notes: a new host has said nothing yet - lead_blocks = Lead(); } + lead_blocks = Lead(); // the script's lead may have changed (#52) session = false; AllNotesOff(); ResetControllers(); velocity = 0; PublishAll(); - bend_semis = SP1_MIDI_BEND_RANGE; + bend_semis = g_cfg.bend_range; bend_cents = 0; UpdateBendScale(); trig_pending = false; @@ -1186,6 +1194,18 @@ extern "C" void sp1_midi_on_enter(void) { reset_req = reset_req + 1u; } +// ---- the script from the drive (#52) ---- +// Main, at ON entry, BEFORE sp1_midi_on_enter() and audio start: nothing reads a half-copied +// script then except, possibly, the USB interrupt's `clock` byte. The reset that on_enter +// requests then puts the bend range, the clock lead and every offset back to neutral under +// the new script; the smoothing coefficient is recomputed at its next step. +extern "C" void sp1_midi_set_config(const struct sp1_midi_cfg* c) { + g_cfg = *c; + smooth_coef_blocks = 0; +} + +extern "C" const struct sp1_midi_cfg* sp1_midi_config(void) { return &g_cfg; } + extern "C" void sp1_midi_main_tick(uint32_t elapsed_ms) { if (model_since_ms < kModelStepMs) { model_since_ms += elapsed_ms; @@ -1195,7 +1215,7 @@ extern "C" void sp1_midi_main_tick(uint32_t elapsed_ms) { model_held = mt; model_since_ms = 0; } - const float tau = static_cast(SP1_MIDI_SMOOTH_MS); + const float tau = static_cast(g_cfg.smooth_ms); const float k = tau <= 0.0f ? 1.0f : 1.0f - expf(-static_cast(elapsed_ms) / tau); for (int d = 0; d < SP1_MIDI_DESTS; ++d) { if (SP1_MIDI_KIND[d] == SP1_MIDI_K_MAIN) { @@ -1206,7 +1226,7 @@ extern "C" void sp1_midi_main_tick(uint32_t elapsed_ms) { } } } - if (SP1_MIDI_PICKUP != SP1_MIDI_PICKUP_SUM) { + if (g_cfg.pickup != SP1_MIDI_PICKUP_SUM) { // The positions sp1_midi_drive() reads. A CC that has just arrived starts AT its // position: smoothing it up from 0 would be a movement the hand never made. for (int d = 0; d < SP1_MIDI_DESTS; ++d) { @@ -1239,7 +1259,7 @@ extern "C" void sp1_midi_main_tick(uint32_t elapsed_ms) { // longer matches it and catches up again, Plaits' way (CatchUp). // The UI tells its fader the value moved; the fader then catches up with it the same way. extern "C" bool sp1_midi_drive(int d, float* s) { - if (SP1_MIDI_PICKUP == SP1_MIDI_PICKUP_SUM || d < 0 || d >= SP1_MIDI_DESTS || CcIsOffset(d)) { + if (g_cfg.pickup == SP1_MIDI_PICKUP_SUM || d < 0 || d >= SP1_MIDI_DESTS || CcIsOffset(d)) { return false; } Drive& k = drive[d]; @@ -1278,8 +1298,8 @@ extern "C" bool sp1_midi_drive(int d, float* s) { // pickup takeover: while the port is up, a fader whose parameter has a CC rests. extern "C" bool sp1_midi_fader_held(int d) { - return SP1_MIDI_PICKUP == SP1_MIDI_PICKUP_TAKEOVER && d >= 0 && d < SP1_MIDI_DESTS && - !CcIsOffset(d) && SP1_MIDI_DEST_CC[d] >= 0 && port_up != 0u; + return g_cfg.pickup == SP1_MIDI_PICKUP_TAKEOVER && d >= 0 && d < SP1_MIDI_DESTS && + !CcIsOffset(d) && g_cfg.dest_cc[d] >= 0 && port_up != 0u; } extern "C" float sp1_midi_offset(int d) { @@ -1421,7 +1441,7 @@ extern "C" bool sp1_midi_audio_begin(uint32_t cycles, uint32_t blocks, uint8_t e if (smooth_due >= kSmoothBlocks) { if (smooth_due != smooth_coef_blocks) { smooth_coef_blocks = smooth_due; - const float tau = static_cast(SP1_MIDI_SMOOTH_MS) * 1e-3f; + const float tau = static_cast(g_cfg.smooth_ms) * 1e-3f; smooth_coef = tau <= 0.0f ? 1.0f : 1.0f - expf(-static_cast(smooth_due) / (tau * kRefreshHz)); diff --git a/firmware/src/sp1_midi.h b/firmware/src/sp1_midi.h index d01ce96..882a609 100644 --- a/firmware/src/sp1_midi.h +++ b/firmware/src/sp1_midi.h @@ -2,8 +2,9 @@ * wakes-sp1 β€” MIDI in (M5a): notes into Plaits, CCs onto both modules. * * The plan, and every decision behind it, is private/docs/M5-PLAN.md. The user-facing side is - * config/midi.ini (the MIDI script, read at build time by tools/gen_midi.py into - * sp1_midi_gen.h) and docs/MIDI.md. + * the MIDI script -- config/midi.cnfg built in (tools/gen_midi.py -> sp1_midi_gen.h), and + * WAKES/CNFG/midi.cnfg on the drive at every ON (#52, sp1_midi_set_config) -- and + * docs/MIDI.md. * * Framework-agnostic, like sp1_synth.cc: no Zephyr header, so the host suite runs it as is. * The USB side (feldd's class, our sp1_usbd.c) only ever calls the two producer functions. @@ -35,7 +36,7 @@ * of a Plaits block. * * ---- pickup: how a CC and its fader share a parameter (Adara, M5a round 4) ---- - * The MIDI script's `pickup` setting, fixed at build time (SP1_MIDI_PICKUP). All three use + * The MIDI script's `pickup` setting (struct sp1_midi_cfg, sp1_cnfg.h). All three use * Plaits' catch-up (plaits/pot_controller.h), as the faders do: * sum the CC is an OFFSET on top of the fader, read by polarity (below). The UIs and * the synth add sp1_midi_offset() / the audio block's offsets. @@ -169,6 +170,12 @@ void sp1_midi_set_output_usb(bool usb); /* ---- main thread ---- */ /* On every entry to ON: forget anything that queued while OFF and start from neutral. */ void sp1_midi_on_enter(void); + +/* #52: the MIDI script from the drive. Main, at ON entry, BEFORE sp1_midi_on_enter() and + * audio start. sp1_midi_config() is the live script (the built-in one until then). */ +struct sp1_midi_cfg; +void sp1_midi_set_config(const struct sp1_midi_cfg *c); +const struct sp1_midi_cfg *sp1_midi_config(void); /* Once per control tick, before the UI computes its parameters: advances the control-loop * smoothing of the Marbles offsets. */ void sp1_midi_main_tick(uint32_t elapsed_ms); diff --git a/firmware/src/sp1_plaits_ui.c b/firmware/src/sp1_plaits_ui.c index 8685e38..82ca5b6 100644 --- a/firmware/src/sp1_plaits_ui.c +++ b/firmware/src/sp1_plaits_ui.c @@ -8,6 +8,7 @@ #include "sp1_marbles.h" /* the scale quantizer FREQUENCY borrows (M4b) */ #include "sp1_midi.h" /* MIDI's offsets and the quantizer bypass (M5a) */ #include "sp1_ui_timing.h" +#include "sp1_cnfg.h" /* engine names compare by letters and digits (#52) */ #include #include @@ -52,11 +53,11 @@ #define DOUBLE_TAP_MS 400u /* second tap must START within this of the 1st */ #define BREATH_MS 1200u /* SETTINGS page breathing period */ -/* ---- the engine list: GENERATED from config/engines.csv ---- - * Which engine is in which slot comes from the user's CSV; each slot's glyph, and each +/* ---- the engine list: GENERATED from config/engines.cnfg ---- + * Which engine is in which slot comes from config/engines.cnfg; each slot's glyph, and each * engine's Plaits index and centre detents, from the fixed tables in tools/gen_engines.py * (run by the build). The reasons for each detent are in docs/PLAITS-ENGINES.md. Edit - * the CSV, not this file. */ + * config/engines.cnfg, not this file. */ #include "sp1_engines_gen.h" #define C_H 0x1u /* HARMONICS (F4) */ @@ -76,12 +77,40 @@ static enum sp1_pui_layer page = SP1_PUI_BASE; static enum sp1_pui_layer active = SP1_PUI_BASE; static bool base_seeded; /* The SELECTED engine: a position in the generated table -- or, past the table, an engine - * that is NOT in config/engines.csv, loaded from a PRST slot (#50): SP1_PUI_OFFLIST + its - * Plaits index. Every build contains all of Plaits' engines; the CSV only decides which + * that is NOT in config/engines.cnfg, loaded from a PRST slot (#50): SP1_PUI_OFFLIST + its + * Plaits index. Every build contains all of Plaits' engines; the stack only decides which * ones T2/T3 reach. Read the engine's facts through engine_of() / centre_of() / name_of(), * never SP1_ENGINE_TABLE[slot] directly. */ static int slot = SP1_ENGINE_DEFAULT_SLOT; +/* ---- the STACK: which engine is in each slot (#52) ---- + * The built-in stack until the ON job reads WAKES/CNFG/engines.cnfg from the drive, which + * replaces it at every ON (sp1_pui_set_stack). Plaits indices, SP1_ENGINE_EMPTY = an empty + * slot. SP1_ENGINE_TABLE keeps only what never changes: each slot's glyph. + * TWO copies: the storage thread writes the one not in use and then flips `live`, so main + * never reads a stack half-written -- even if it stopped waiting for the ON job (PRST's + * 10 s limit) while the job was still running. Main reads whichever is live at the start of + * each call (stk()). */ +static uint8_t stacks[2][SP1_ENGINE_SLOTS] = { SP1_ENGINE_DEFAULT_STACK, + SP1_ENGINE_DEFAULT_STACK }; +static int live; + +static const uint8_t *stk(void) +{ + return stacks[__atomic_load_n(&live, __ATOMIC_ACQUIRE) & 1]; +} + +/* The first filled slot: where the device starts and where ROTC returns (Adara, #52). */ +static int first_slot(const uint8_t *t) +{ + for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { + if (t[i] != SP1_ENGINE_EMPTY) { + return i; + } + } + return 0; /* never: the readers guarantee one engine (sp1_cnfg.h) */ +} + static bool fnc_was; static bool press_dirty; /* activity seen during this press */ static uint32_t press_ms; @@ -118,12 +147,17 @@ static bool offlist(int s) /* A selection the UI can hold: a FILLED list position, or an engine off the list. */ static bool slot_ok(int s) { - return (s >= 0 && s < SP1_ENGINE_SLOTS && SP1_ENGINE_TABLE[s].on) || offlist(s); + return (s >= 0 && s < SP1_ENGINE_SLOTS && stk()[s] != SP1_ENGINE_EMPTY) || offlist(s); } static int engine_of(int s) { - return offlist(s) ? s - SP1_PUI_OFFLIST : SP1_ENGINE_TABLE[s].plaits; + if (offlist(s)) { + return s - SP1_PUI_OFFLIST; + } + const uint8_t e = (s >= 0 && s < SP1_ENGINE_SLOTS) ? stk()[s] : SP1_ENGINE_EMPTY; + /* An empty slot has no engine: callers check slot_ok() first; this is a backstop. */ + return e < SP1_PLAITS_ENGINE_COUNT ? e : stk()[first_slot(stk())]; } static uint8_t centre_of(int s) @@ -138,7 +172,7 @@ static const char *name_of(int s) /* ---- the engine that PLAYS (M5a) ---- * `slot` is what T2/T3 selected; MIDI's MODEL CC offsets it, through the filled slots of - * config/engines.csv in order, clamped at both ends (Plaits' own MODEL CV input is an offset + * config/engines.cnfg in order, clamped at both ends (Plaits' own MODEL CV input is an offset * from the button-selected model too). A CC at either end reaches every filled slot from * any selection. Everything that depends on the engine actually sounding -- its detents, * Plaits' engine index, INTELLIGENT's polarity, the log -- uses this; the engine flash and @@ -149,10 +183,11 @@ static int eslot(void) if (off == 0.0f) { return slot; } + const uint8_t *t = stk(); int filled[SP1_ENGINE_SLOTS]; int n = 0, here = 0; /* off the list: MODEL counts from position 1 (#50) */ for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { - if (SP1_ENGINE_TABLE[i].on) { + if (t[i] != SP1_ENGINE_EMPTY) { if (i == slot) { here = n; } @@ -612,7 +647,8 @@ void sp1_pui_rip(void) /* ---- "rip out the cables" on PLAITS: a FULL PATCH WIPE (Adara, M4d) ---- * ⚠️ Through M4b this was a modulation reset that deliberately kept BASE and the * engine. docs/DEFAULTS.md changed that: it now wipes the patch. Engine back to - * slot 1, the four BASE faders to THAT engine's neutral state, everything on the + * the FIRST FILLED SLOT of the stack (#52, Adara: of the user's engines.cnfg, not slot 1 + * of the built-in one), the four BASE faders to THAT engine's neutral state, everything on the * SHIFT and SETTINGS layers to its default, and the FREQUENCY quantizer off. * * Neutral means: 0.5 for a BIPOLAR parameter -- its centre is the point where the @@ -631,14 +667,14 @@ void sp1_pui_rip(void) * set afterwards and the values stay where the rip put them. Re-neutralising on * every engine change would mean losing a patch just by browsing engines. */ struct sp1_pui_patch p; - sp1_pui_rip_patch(SP1_ENGINE_DEFAULT_SLOT, &p); + sp1_pui_rip_patch(-1, &p); /* the first filled slot of the stack (#52) */ sp1_pui_put(&p); } void sp1_pui_rip_patch(int s, struct sp1_pui_patch *p) { if (!slot_ok(s)) { - s = SP1_ENGINE_DEFAULT_SLOT; + s = first_slot(stk()); } const uint8_t c = centre_of(s); p->slot = s; @@ -666,7 +702,7 @@ void sp1_pui_get(struct sp1_pui_patch *p) void sp1_pui_put(const struct sp1_pui_patch *p) { - slot = slot_ok(p->slot) ? p->slot : SP1_ENGINE_DEFAULT_SLOT; + slot = slot_ok(p->slot) ? p->slot : first_slot(stk()); for (int l = 0; l < SP1_PUI_LAYERS; l++) { for (int i = 0; i < 4; i++) { const float x = p->v[l][i]; @@ -678,26 +714,13 @@ void sp1_pui_put(const struct sp1_pui_patch *p) pickup_all(); } -static int lower(int ch) -{ - return (ch >= 'A' && ch <= 'Z') ? ch - 'A' + 'a' : ch; -} - -static bool same_name(const char *n, const char *name, int len) -{ - int k = 0; - while (k < len && n[k] != '\0' && lower((unsigned char)n[k]) == - lower((unsigned char)name[k])) { - k++; - } - return k == len && n[k] == '\0'; -} - int sp1_pui_slot_of(const char *name, int len) { int e = -1; for (int i = 0; i < SP1_PLAITS_ENGINE_COUNT; i++) { - if (same_name(SP1_PLAITS_ENGINES[i].name, name, len)) { + /* Letters and digits, case ignored (sp1_cnfg.h, #52): an older spelling of a + * name in a PRST file still finds its engine. */ + if (sp1_engine_name_eq(SP1_PLAITS_ENGINES[i].name, name, len < 0 ? 0u : (size_t)len)) { e = i; break; } @@ -705,14 +728,41 @@ int sp1_pui_slot_of(const char *name, int len) if (e < 0) { return -1; /* not an engine of this build */ } + const uint8_t *t = stk(); for (int s = 0; s < SP1_ENGINE_SLOTS; s++) { - if (SP1_ENGINE_TABLE[s].on && SP1_ENGINE_TABLE[s].plaits == e) { - return s; /* on the list: its position */ + if (t[s] == e) { + return s; /* in the stack: its position */ } } return SP1_PUI_OFFLIST + e; /* in the build, off the list (#50) */ } +void sp1_pui_set_stack(const uint8_t stack[SP1_ENGINE_SLOTS]) +{ + const int next = (__atomic_load_n(&live, __ATOMIC_ACQUIRE) & 1) ^ 1; + for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { + stacks[next][i] = stack[i] < SP1_PLAITS_ENGINE_COUNT ? stack[i] : SP1_ENGINE_EMPTY; + } + bool any = false; + for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { + any = any || stacks[next][i] != SP1_ENGINE_EMPTY; + } + if (!any) { + const uint8_t def[SP1_ENGINE_SLOTS] = SP1_ENGINE_DEFAULT_STACK; + for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { + stacks[next][i] = def[i]; + } + } + __atomic_store_n(&live, next, __ATOMIC_RELEASE); +} + +void sp1_pui_stack_settle(void) +{ + if (!slot_ok(slot)) { + slot = first_slot(stk()); + } +} + const char *sp1_pui_slot_name(int s) { return slot_ok(s) ? name_of(s) : ""; @@ -753,27 +803,29 @@ void sp1_pui_slot_leds(int s, uint8_t out[4]) } } -/* ---- engine select (T2 / T3), in SLOT order from config/engines.csv ---- - * A slot with no engine in the CSV is empty: it keeps its place and glyph, and is +/* ---- engine select (T2 / T3), in SLOT order from config/engines.cnfg ---- + * A slot with no engine in engines.cnfg is empty: it keeps its place and glyph, and is * skipped. The build guarantees at least one slot is filled. Wraps at both ends. */ int sp1_pui_engine_step(int dir) { if (offlist(slot)) { /* From an engine off the list (#50, Adara): T3 -> the first listed engine, * T2 -> the last. */ + const uint8_t *t = stk(); int s2 = -1; for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { - if (SP1_ENGINE_TABLE[i].on && (s2 < 0 || dir < 0)) { + if (t[i] != SP1_ENGINE_EMPTY && (s2 < 0 || dir < 0)) { s2 = i; } } slot = s2; return slot; } + const uint8_t *t = stk(); int s2 = slot; for (int n = 0; n < SP1_ENGINE_SLOTS; n++) { s2 = (s2 + (dir < 0 ? SP1_ENGINE_SLOTS - 1 : 1)) % SP1_ENGINE_SLOTS; - if (SP1_ENGINE_TABLE[s2].on) { + if (t[s2] != SP1_ENGINE_EMPTY) { break; } } diff --git a/firmware/src/sp1_plaits_ui.h b/firmware/src/sp1_plaits_ui.h index 08688c7..42261ef 100644 --- a/firmware/src/sp1_plaits_ui.h +++ b/firmware/src/sp1_plaits_ui.h @@ -154,7 +154,7 @@ int sp1_pui_scale(void); void sp1_pui_set_octave_max(void); bool sp1_pui_catching(int fader); /* in the active layer */ bool sp1_pui_level_connected(void); /* SETTINGS F4 >= 5 % (M4a) */ -/* ---- engines: slots from config/engines.csv; glyphs and detents fixed in gen_engines.py ---- */ +/* ---- engines: slots from config/engines.cnfg; glyphs and detents fixed in gen_engines.py ---- */ int sp1_pui_engine(void); /* Plaits engine index (voice.cc) */ /* Which of the CURRENT engine's parameters are bipolar, as SP1_ENGINE_TABLE[].centre: * 0x1 = HARMONICS (F4), 0x2 = TIMBRE (F2), 0x4 = MORPH (F3). A detent is placed exactly @@ -190,7 +190,7 @@ void sp1_pui_rip(void); * quantizer. (The output mode, burst division and drive are main.c's; src/sp1_prst.h.) * Pickup state is NOT part of it -- sp1_pui_put() re-evaluates it, as a rip does. */ struct sp1_pui_patch { - int slot; /* engine: position in config/engines.csv */ + 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 */ }; @@ -205,9 +205,9 @@ void sp1_pui_put(const struct sp1_pui_patch *p); * source of PLAITS' ROTC defaults: PRST's field check takes its defaults from here too. */ void sp1_pui_rip_patch(int slot, struct sp1_pui_patch *p); /* The slot whose engine is called `name` (case-insensitive), among the FILLED slots of - * config/engines.csv; -1 if there is none. */ + * config/engines.cnfg; -1 if there is none. */ /* ---- engines OFF the list (#50) ---- - * Every build contains all of Plaits' engines; config/engines.csv only decides which ones + * Every build contains all of Plaits' engines; config/engines.cnfg only decides which ones * T2/T3 reach. A PRST slot may name one that is not listed, and it plays. Such a selection * is SP1_PUI_OFFLIST + its Plaits index, wherever a "slot" appears in this API. It has no * glyph (sp1_pui_slot_leds() gives dark; main.c draws the off-list animation), T3 from it @@ -215,9 +215,21 @@ void sp1_pui_rip_patch(int slot, struct sp1_pui_patch *p); * position 1. */ #define SP1_PUI_OFFLIST 100 bool sp1_pui_offlist(int slot); -/* The selection for engine `name` (case ignored): its list position if it is listed, else - * SP1_PUI_OFFLIST + its Plaits index; -1 if this build has no such engine. */ +/* The selection for engine `name` (letters and digits, case ignored -- sp1_cnfg.h): its + * position if it is in the stack, else SP1_PUI_OFFLIST + its Plaits index; -1 if this build + * has no such engine. */ int sp1_pui_slot_of(const char *name, int len); + +/* ---- the stack (#52) ---- + * Which engine is in each slot: the built-in stack (config/engines.cnfg at build time) until + * the ON job reads WAKES/CNFG/engines.cnfg from the drive and calls this -- every ON, before + * the PRST slots are read, so their engine names resolve against the new stack. Plaits + * indices, SP1_ENGINE_EMPTY for an empty slot; a stack with no engine is replaced by the + * built-in one. Safe from the storage thread while main runs (two copies, one flip). */ +void sp1_pui_set_stack(const uint8_t stack[24]); +/* Main, after the ON job: a selection left on a slot the new stack emptied moves to the + * first filled slot. (With PRST on, the loaded slot replaces the selection anyway.) */ +void sp1_pui_stack_settle(void); const char *sp1_pui_slot_name(int slot); /* "" for no engine */ const char *sp1_pui_engine_name(void); diff --git a/firmware/src/sp1_prst.h b/firmware/src/sp1_prst.h index e5d3e88..5176bfc 100644 --- a/firmware/src/sp1_prst.h +++ b/firmware/src/sp1_prst.h @@ -24,7 +24,7 @@ * ... * * Fader values are positions 0..1 with four decimals; choices are lowercase tokens; the - * engine is its NAME from config/engines.csv (Adara: by name, so a slot survives an edited + * engine is its NAME from config/engines.cnfg (Adara: by name, so a slot survives an edited * engine list). Reading ignores case, blank lines and lines starting ';' or '#'. A key the * table does not know is ignored, so is a section. If a key appears twice, the last wins. * @@ -36,7 +36,7 @@ * exponent, nothing after it); * - a choice must be one of its tokens, and pass its check (an included scale; a * destination on that output's ring); - * - the engine must name a filled slot of config/engines.csv; otherwise slot 1; + * - the engine must name a filled slot of config/engines.cnfg; otherwise slot 1; * - a missing key takes its default too. * The ROTC default comes from the rip code itself (sp1_pui_rip_patch, sp1_mui_rip_patch), * never from a second table -- and for a BASE fader it is the neutral value of the engine diff --git a/firmware/src/sp1_store.c b/firmware/src/sp1_store.c index 414be14..e7e8dc5 100644 --- a/firmware/src/sp1_store.c +++ b/firmware/src/sp1_store.c @@ -3,11 +3,23 @@ * * FatFs (ChaN, R0.16, through Zephyr's fs layer) sits on a disk driver here that reads * and writes single blocks through sp1_emmc.c. Every console line starts "STORE" (this - * file) or "EMMC" (sp1_emmc_report.c). + * file), "CNFG" (the config files), "LOG" (the log on the drive) or "EMMC" + * (sp1_emmc_report.c). */ +/* 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. */ +#define SP1_CNFG_TEMPLATES #include "sp1_store.h" #include "sp1_emmc.h" #include "sp1_console.h" +#include "sp1_cnfg.h" +#include "sp1_logbuf.h" +#include "sp1_engines_gen.h" +#if defined(CONFIG_SP1_PLAITS) +#include "sp1_audio_gen.h" +#endif +#include "sp1_logs_gen.h" #if defined(CONFIG_SP1_STORAGE_TEST) #include "sp1_emmc_report.h" #endif @@ -24,6 +36,8 @@ #define DISK_NAME "EMMC" /* = CONFIG_FS_FATFS_CUSTOM_MOUNT_POINTS */ #define MNT "/EMMC:" #define DIR_WAKES MNT "/WAKES" +#define DIR_CNFG DIR_WAKES "/CNFG" +#define DIR_LOGS DIR_WAKES "/LOGS" /* The partition starts one erase group in: 8192 blocks = 4 MB (EXT_CSD * HC_ERASE_GRP_SIZE 8 x 512 KB on this card, logs/sp1-20261007-152119.log). */ @@ -32,6 +46,9 @@ #define LINE(...) do { printk(__VA_ARGS__); sp1_console_pace(); } while (0) static volatile bool stop; +/* Set by sp1_store_abort and cleared only by the thread, once it has let go of the log file + * and the volume (log_teardown): sp1_store_on_enter() clears `stop`, so it cannot say this. */ +static volatile bool torn; /* ---- who owns the card (drive mode, M6) ---- * Two disks over one card: "EMMC" is Wakes' (FatFs, this thread) and "DRIVE" the host's @@ -55,6 +72,7 @@ static uint32_t r_data; #define JOB_ON BIT(0) #define JOB_HOST BIT(1) #define JOB_SAVE BIT(2) +#define JOB_LOGEND BIT(3) static atomic_t pending; /* What main's storage_gate() reads (sp1_store.h). */ @@ -306,6 +324,661 @@ __maybe_unused static int read_file(const char *path, void *d, size_t max, size_ return rc; } +/* Verify `path` is a FOLDER; create it if nothing is there (Adara, #50; the log's and the + * config files' folders too since #52). 0 when there is a folder to write into. Something + * else with that name -- a computer can leave a FILE called "3" where slot 3's folder + * should be -- is -ENOTDIR and is left alone: the write fails with that in the log rather + * than touching a file it did not write. */ +static int ensure_dir(const char *path) +{ + static struct fs_dirent st; + int rc = fs_stat(path, &st); + if (rc == 0) { + if (st.type == FS_DIR_ENTRY_DIR) { + return 0; + } + LINE("STORE %s is a file, not a folder -- not writing there\n", path); + return -ENOTDIR; + } + if (rc != -ENOENT) { + return rc; + } + rc = fs_mkdir(path); + LINE("STORE no folder %s -- %s (%d)\n", path, rc == 0 ? "created" : "create FAILED", rc); + return rc; +} + +/* ---------------------------------------------------------------- CNFG (#52) */ + +#define LOGS_CNFG DIR_CNFG "/logs.cnfg" +#define ENGINES_CNFG DIR_CNFG "/engines.cnfg" +#define AUDIO_CNFG DIR_CNFG "/audio.cnfg" +#define MIDI_CNFG DIR_CNFG "/midi.cnfg" +/* A config file is a few KB (engines.cnfg ~16, midi.cnfg ~14); never read a huge one. */ +#define CNFG_READ_MAX 65536u + +static struct sp1_logs_cfg logs_cfg; + +/* The files this ON's job found missing: written with their built-in text once PRST has + * loaded (cnfg_create_missing), so the user always has every file to edit. */ +#define MISSING_LOGS 0x1u +#define MISSING_ENGINES 0x2u +#define MISSING_AUDIO 0x4u +#define MISSING_MIDI 0x8u +static uint8_t cnfg_missing; + +static void cnfg_problem(void *ctx, int line, const char *what, const char *why) +{ + LINE("CNFG %s line %d: %s -- %s\n", (const char *)ctx, line, what, why); +} + +/* A file through a reader, CNFG_READ_MAX at most. 0 = read (*got bytes, *rerr if a read + * failed part-way); -ENOENT = not on the drive; anything else = could not be opened. */ +static int cnfg_read(const char *path, void (*feed)(void *r, const char *t, size_t n), void *r, + size_t *got, bool *rerr) +{ + static char chunk[128]; + *got = 0u; + *rerr = false; + struct fs_file_t f; + fs_file_t_init(&f); + const int rc = fs_open(&f, path, FS_O_READ); + if (rc != 0) { + return rc; + } + while (!stop && *got < CNFG_READ_MAX) { + const ssize_t n = fs_read(&f, chunk, sizeof(chunk)); + if (n <= 0) { + *rerr = n < 0; + break; + } + feed(r, chunk, (size_t)n); + *got += (size_t)n; + } + (void)fs_close(&f); + return 0; +} + +static void logs_feed(void *r, const char *t, size_t n) +{ + sp1_logs_feed(r, t, n); +} + +/* logs.cnfg: line by line over the built-in defaults -- a bad line keeps its default. */ +static void cnfg_load_logs(void) +{ + static struct sp1_logs_reader rd; /* ~0.4 KB: off the thread's stack */ + sp1_logs_defaults(&logs_cfg); + sp1_logs_begin(&rd, &logs_cfg, cnfg_problem, (void *)"logs.cnfg"); + size_t got; + bool rerr; + const int rc = cnfg_read(LOGS_CNFG, logs_feed, &rd, &got, &rerr); + if (rc == -ENOENT) { + cnfg_missing |= MISSING_LOGS; + LINE("CNFG logs.cnfg: not on the drive -- the built-in defaults (a copy goes there)\n"); + } else if (rc != 0) { + LINE("CNFG logs.cnfg: cannot be opened (%d) -- the built-in defaults\n", rc); + } else { + const int bad = sp1_logs_end(&rd); + LINE("CNFG logs.cnfg: %u B read%s, %d problem%s%s\n", (unsigned)got, + rerr ? " (then a read error)" : (got >= CNFG_READ_MAX ? " (the rest ignored)" : ""), + bad, bad == 1 ? "" : "s", bad ? " -- those lines keep their defaults" : ""); + } + char d[48]; + LINE("CNFG logging to the drive %s: %s\n", logs_cfg.enabled ? "on" : "off", + sp1_logs_describe(logs_cfg.cats, d, sizeof(d))); +} + +#if defined(CONFIG_SP1_PLAITS) +static void engines_feed(void *r, const char *t, size_t n) +{ + sp1_engines_feed(r, t, n); +} + +static int stack_count(const uint8_t s[SP1_CNFG_SLOTS]) +{ + int n = 0; + for (int i = 0; i < SP1_CNFG_SLOTS; i++) { + n += (s[i] != SP1_CNFG_EMPTY); + } + return n; +} + +/* engines.cnfg: ALL OR NOTHING (sp1_cnfg.h). Missing, unreadable, or any problem in it -> + * the built-in stack, every problem named. Installed before PRST reads its slots, so their + * engine names resolve against it; ROTC and the start go to its first filled slot. */ +static void cnfg_load_engines(void) +{ + static struct sp1_engines_reader rd; /* ~0.4 KB: off the thread's stack */ + uint8_t stack[SP1_CNFG_SLOTS]; + int filled = 0; + sp1_engines_begin(&rd, cnfg_problem, (void *)"engines.cnfg"); + size_t got; + bool rerr; + const int rc = cnfg_read(ENGINES_CNFG, engines_feed, &rd, &got, &rerr); + if (rc != 0) { + sp1_engines_defaults(stack); + filled = stack_count(stack); + if (rc == -ENOENT) { + cnfg_missing |= MISSING_ENGINES; + LINE("CNFG engines.cnfg: not on the drive -- the built-in stack (a copy goes " + "there)\n"); + } else { + LINE("CNFG engines.cnfg: cannot be opened (%d) -- the built-in stack\n", rc); + } + } else { + int bad = sp1_engines_end(&rd, stack, &filled); + if (bad == 0 && (rerr || got >= CNFG_READ_MAX)) { + /* Only part of the file was read: part of a stack is not the user's stack. */ + bad = 1; + sp1_engines_defaults(stack); + filled = stack_count(stack); + } + LINE("CNFG engines.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 stack instead (the whole file is set aside)" + : "your stack"); + } + sp1_pui_set_stack(stack); + int first = 0; + while (first < SP1_CNFG_SLOTS - 1 && stack[first] == SP1_CNFG_EMPTY) { + first++; + } + LINE("CNFG engine stack: %d engine%s, starting at slot %d\n", filled, + filled == 1 ? "" : "s", first + 1); +} +#endif + +#if defined(CONFIG_SP1_PLAITS) +/* audio.cnfg and midi.cnfg land here; main takes them at ON entry, before audio starts + * (sp1_store_cnfg). `cnfg_ready` says the ON job has finished writing them this ON. */ +static struct sp1_audio_cfg st_audio; +static struct sp1_midi_cfg st_midi; +static atomic_t cnfg_ready; + +static void audio_feed(void *r, const char *t, size_t n) +{ + sp1_audio_reader_feed(r, t, n); +} + +static void midi_feed(void *r, const char *t, size_t n) +{ + sp1_midi_reader_feed(r, t, n); +} + +/* audio.cnfg: line by line over the built-in values. */ +static void cnfg_load_audio(void) +{ + static struct sp1_audio_reader rd; + sp1_audio_reader_begin(&rd, &st_audio, cnfg_problem, (void *)"audio.cnfg"); + size_t got; + bool rerr; + const int rc = cnfg_read(AUDIO_CNFG, audio_feed, &rd, &got, &rerr); + if (rc != 0) { + sp1_audio_cfg_defaults(&st_audio); + if (rc == -ENOENT) { + cnfg_missing |= MISSING_AUDIO; + } + LINE("CNFG audio.cnfg: %s -- the built-in settings\n", + rc == -ENOENT ? "not on the drive (a copy goes there)" : "cannot be opened"); + return; + } + const int bad = sp1_audio_reader_end(&rd); + LINE("CNFG audio.cnfg: %u B read%s, %d problem%s%s\n", (unsigned)got, + rerr ? " (then a read error)" : (got >= CNFG_READ_MAX ? " (the rest ignored)" : ""), + bad, bad == 1 ? "" : "s", bad ? " -- those lines keep their defaults" : ""); +} + +/* midi.cnfg: line by line over the built-in script, then the CC rule (sp1_cnfg.h). */ +static void cnfg_load_midi(void) +{ + static struct sp1_midi_reader rd; /* ~0.6 KB: off the thread's stack */ + sp1_midi_reader_begin(&rd, &st_midi, cnfg_problem, (void *)"midi.cnfg"); + size_t got; + bool rerr; + const int rc = cnfg_read(MIDI_CNFG, midi_feed, &rd, &got, &rerr); + if (rc != 0) { + sp1_midi_cfg_defaults(&st_midi); + if (rc == -ENOENT) { + cnfg_missing |= MISSING_MIDI; + } + LINE("CNFG midi.cnfg: %s -- the built-in script\n", + rc == -ENOENT ? "not on the drive (a copy goes there)" : "cannot be opened"); + return; + } + int notes = 0; + const int bad = sp1_midi_reader_end(&rd, ¬es); + LINE("CNFG midi.cnfg: %u B read%s, %d problem%s%s, %d CC%s taken from a default\n", + (unsigned)got, + rerr ? " (then a read error)" : (got >= CNFG_READ_MAX ? " (the rest ignored)" : ""), + bad, bad == 1 ? "" : "s", bad ? " -- those lines keep their defaults" : "", + notes, notes == 1 ? "" : "s"); +} +#endif + +/* No volume: the built-in everything, so nothing from an earlier ON's files lingers. */ +static void cnfg_defaults(void) +{ + sp1_logs_defaults(&logs_cfg); +#if defined(CONFIG_SP1_PLAITS) + uint8_t stack[SP1_CNFG_SLOTS]; + sp1_engines_defaults(stack); + sp1_pui_set_stack(stack); + sp1_audio_cfg_defaults(&st_audio); + sp1_midi_cfg_defaults(&st_midi); + atomic_set(&cnfg_ready, 1); +#endif +} + +/* Inside the ON job, the volume mounted: every config file, over the built-in defaults. + * Never fails: a missing or unreadable file keeps the defaults. */ +static void cnfg_load(void) +{ + cnfg_missing = 0u; + cnfg_load_logs(); +#if defined(CONFIG_SP1_PLAITS) + if (!stop) { + cnfg_load_engines(); + } + if (!stop) { + cnfg_load_audio(); + } + if (!stop) { + cnfg_load_midi(); + } + atomic_set(&cnfg_ready, 1); +#endif +} + +/* A config file that was missing, written with its built-in text (Adara, #52): "this'll + * prevent people from having to refer to the repo to copy in missing cnfg files, or resorting + * to flashing a fresh bin". Only a file that is NOT THERE -- one that exists is the user's and + * is never touched, even when it cannot be read. After PRST has loaded, so ON is not held up. + * This is also how wakes-sp1-fresh fills its new WAKES/CNFG/, and how "delete a file" resets + * it to the defaults at the next ON. */ +static int cnfg_write_one(const char *path, const char *name, const char *text, size_t n) +{ + const int rc = write_file(path, text, n); + LINE("CNFG %s: written to the drive with the built-in text (%u B): %s (%d)\n", name, + (unsigned)n, rc == 0 ? "done" : "FAILED", rc); + return rc; +} + +static void cnfg_create_missing(void) +{ + if (cnfg_missing == 0u || stop) { + return; + } + int rc = ensure_dir(DIR_WAKES); + if (rc == 0) { + rc = ensure_dir(DIR_CNFG); + } + if (rc != 0) { + LINE("CNFG the missing files cannot be written: no WAKES/CNFG folder (%d)\n", rc); + return; + } + if ((cnfg_missing & MISSING_LOGS) && !stop) { + (void)cnfg_write_one(LOGS_CNFG, "logs.cnfg", SP1_LOGS_TEMPLATE, + sizeof(SP1_LOGS_TEMPLATE) - 1u); + } +#if defined(CONFIG_SP1_PLAITS) + if ((cnfg_missing & MISSING_ENGINES) && !stop) { + (void)cnfg_write_one(ENGINES_CNFG, "engines.cnfg", SP1_ENGINES_TEMPLATE, + sizeof(SP1_ENGINES_TEMPLATE) - 1u); + } + if ((cnfg_missing & MISSING_AUDIO) && !stop) { + (void)cnfg_write_one(AUDIO_CNFG, "audio.cnfg", SP1_AUDIO_TEMPLATE, + sizeof(SP1_AUDIO_TEMPLATE) - 1u); + } + if ((cnfg_missing & MISSING_MIDI) && !stop) { + (void)cnfg_write_one(MIDI_CNFG, "midi.cnfg", SP1_MIDI_TEMPLATE, + sizeof(SP1_MIDI_TEMPLATE) - 1u); + } +#endif + cnfg_missing = 0u; +} + +/* ---------------------------------------------------------------- the log (#52) */ + +/* One file per session, NNNN.logs (Adara): the session number mod 10000, so 9999.logs is + * followed by 0000.logs. The number itself keeps counting, in WAKES/LOGS/SESSION and in each + * file's first line. The last SP1_STORE_LOG_KEEP sessions are kept: a new one deletes the + * file of the session SP1_STORE_LOG_KEEP before it. */ +#define LOG_SESSION DIR_LOGS "/SESSION" +#define LOG_NAMES 10000u +#define LOG_SUMMARY_MS 60000u + +static atomic_t log_live_a; /* main reads it: sp1_store_log_live() */ +static bool log_live; /* the file is open, the card on and mounted */ +static bool session_open; /* this boot has opened a session's file */ +static uint32_t session_n; /* ...and its session number */ +static char log_path[sizeof(DIR_LOGS) + 16]; +static struct fs_file_t log_f; +static uint32_t log_size; +static bool log_full; +static uint32_t log_next; /* uptime of the next flush */ +static bool piece_cont; /* the last piece taken ended mid-line... */ +static bool piece_keep; /* ...and was (not) for the file */ +static char piece[SP1_LOGBUF_TAKE_MAX]; +/* What goes to the card: the ring is never handed to the disk directly, both because + * printk keeps writing it and because of nRF52840 anomaly 198 (SPIM3's DMA source). */ +static char stage[1024]; +static uint32_t sum_t0, sum_flushes, sum_bytes, sum_max_ms, sum_lost; + +static void log_name(uint32_t n, char *buf, size_t size) +{ + snprintk(buf, size, DIR_LOGS "/%04u.logs", (unsigned)(n % LOG_NAMES)); +} + +/* WAKES/LOGS/SESSION: the last session's number. false if it is missing or not a number. */ +static bool log_read_session(uint32_t *n) +{ + char t[16]; + size_t got = 0u; + if (read_file(LOG_SESSION, t, sizeof(t) - 1u, &got) != 0) { + return false; + } + uint32_t v = 0u; + size_t i = 0u; + while (i < got && (t[i] == ' ' || t[i] == '\t')) { + i++; + } + const size_t start = i; + for (; i < got && t[i] >= '0' && t[i] <= '9' && v < 429496729u; i++) { + v = v * 10u + (uint32_t)(t[i] - '0'); + } + if (i == start) { + return false; + } + *n = v; + return true; +} + +static int log_put(const char *d, size_t n) +{ + const ssize_t w = fs_write(&log_f, d, n); + if (w != (ssize_t)n) { + return w < 0 ? (int)w : -EIO; + } + log_size += (uint32_t)n; + return 0; +} + +/* Into the file through the size cap: past it, one last line and nothing more this session. */ +static int log_write(const char *d, size_t n) +{ + if (log_full || n == 0u) { + return 0; + } + static const char full[] = "=== LOG FULL at 8 MB: the rest of this session is not on the " + "drive (the console still has it) ===\n"; + if (log_size + n + sizeof(full) > SP1_STORE_LOG_MAX) { + log_full = true; + return log_put(full, sizeof(full) - 1u); + } + return log_put(d, n); +} + +static int log_flush(bool before_standby); + +/* Before a new session: the lines the previous one still owes its own file -- what it printed + * after its last flush (its closing lines), or a 30 s backstop's tail, or, after a soft reset + * that kept the RAM log, the crash and the boot that followed it. They are in the RAM log + * before the last STANDBY; without this they would open the NEW file. Its own errors are + * logged, not returned: the new session opens anyway, and anything left goes into it. */ +static void log_catch_up(uint32_t prev) +{ + log_name(prev, log_path, sizeof(log_path)); + fs_file_t_init(&log_f); + /* No FS_O_CREATE: a file deleted from a computer meanwhile is not brought back. */ + int rc = fs_open(&log_f, log_path, FS_O_WRITE | FS_O_APPEND); + if (rc != 0) { + if (rc != -ENOENT) { + LINE("LOG could not reopen %s for the last ON's lines (%d)\n", + log_path + sizeof(DIR_LOGS), rc); + } + return; + } + rc = fs_seek(&log_f, 0, FS_SEEK_END); + const off_t at = (rc == 0) ? fs_tell(&log_f) : -1; + if (at >= 0) { + log_size = (uint32_t)at; + log_full = log_size >= SP1_STORE_LOG_MAX; + piece_cont = false; + rc = log_flush(true); + } + const uint32_t added = (at >= 0) ? log_size - (uint32_t)at : 0u; + (void)fs_close(&log_f); + if ((at < 0 || rc != 0) && !stop) { + LINE("LOG the last ON's lines into %s FAILED (%d)\n", log_path + sizeof(DIR_LOGS), + at < 0 ? (int)at : rc); + } else if (added > 0u && !stop) { + LINE("LOG %u B of the last ON's lines into %s\n", (unsigned)added, + log_path + sizeof(DIR_LOGS)); + } +} + +/* The volume mounted, at the end of the ON job: every ON starts a NEW session, the next + * number (Adara, 2026-10-16: STANDBY then ON is a new file too). The previous session's + * last lines go to its own file first (log_catch_up). */ +static int log_open(void) +{ + int rc = ensure_dir(DIR_WAKES); + if (rc == 0) { + rc = ensure_dir(DIR_LOGS); + } + if (rc != 0) { + return rc; + } + uint32_t last = 0u; + const bool known = log_read_session(&last); + if (session_open) { + log_catch_up(session_n); /* an earlier ON of this boot */ + } else if (sp1_logbuf_continued() && known) { + log_catch_up(last); /* the session a soft reset interrupted */ + } + session_n = (known ? last : (session_open ? session_n : 0u)) + 1u; + log_name(session_n, log_path, sizeof(log_path)); + char num[16]; + const int k = snprintk(num, sizeof(num), "%u\n", (unsigned)session_n); + rc = write_file(LOG_SESSION, num, (size_t)k); + if (rc != 0) { + return rc; + } + /* A file already under this name is from a session 10000 back (or a lost + * counter): this session starts it afresh. */ + (void)fs_unlink(log_path); + if (session_n > SP1_STORE_LOG_KEEP) { + char old[sizeof(log_path)]; + log_name(session_n - SP1_STORE_LOG_KEEP, old, sizeof(old)); + const int urc = fs_unlink(old); + if (urc != 0 && urc != -ENOENT) { + LINE("LOG could not delete %s (%d)\n", old + sizeof(DIR_LOGS), urc); + } + } + fs_file_t_init(&log_f); + rc = fs_open(&log_f, log_path, FS_O_CREATE | FS_O_WRITE | FS_O_APPEND); + if (rc != 0) { + return rc; + } + rc = fs_seek(&log_f, 0, FS_SEEK_END); + const off_t at = (rc == 0) ? fs_tell(&log_f) : -1; + if (at < 0) { + (void)fs_close(&log_f); + return rc != 0 ? rc : (int)at; + } + log_size = (uint32_t)at; + log_full = log_size >= SP1_STORE_LOG_MAX; + piece_cont = false; + char h[160]; + const int n = snprintk(h, sizeof(h), "=== Wakes v" APP_VERSION_STRING ", built %s %s -- " + "log session %u -- resetreas 0x%08x ===\n", __DATE__, __TIME__, + (unsigned)session_n, sp1_logbuf_resetreas()); + rc = log_write(h, (size_t)n); + if (rc != 0) { + (void)fs_close(&log_f); + return rc; + } + session_open = true; + log_live = true; + atomic_set(&log_live_a, 1); + LINE("LOG new session %u: WAKES/LOGS/%s (%u KB)\n", (unsigned)session_n, + log_path + sizeof(DIR_LOGS), (unsigned)(log_size / 1024u)); + return 0; +} + +/* Lines a filtered category leaves out; a long line's later pieces follow its first. */ +static bool keep_piece(const char *d, size_t n) +{ + bool keep; + if (piece_cont) { + keep = piece_keep; + } else { + const uint8_t c = sp1_log_category(d, n); + keep = (c == 0u) || (logs_cfg.cats & c) != 0u; + } + piece_cont = d[n - 1u] != '\n'; + piece_keep = keep; + return keep; +} + +/* Everything new in the RAM log, into the file, then synced: the file's size on the card is + * then current, so a cut-off loses only what came after. `before_standby`: only the lines + * from before the last STANDBY (log_catch_up). */ +static int log_flush(bool before_standby) +{ + const uint32_t t0 = k_uptime_get_32(); + size_t used = 0u; + uint32_t written = 0u; + int rc = 0; + for (;;) { + uint32_t lost = 0u; + const size_t n = before_standby + ? sp1_logbuf_file_take_before_standby(piece, sizeof(piece), &lost) + : sp1_logbuf_file_take(piece, sizeof(piece), &lost); + if (lost > 0u) { + sum_lost += lost; + char m[112]; + const int k = snprintk(m, sizeof(m), "=== LOG: %u bytes lost here -- the RAM log " + "filled before the drive took them ===\n", + (unsigned)lost); + if (used + (size_t)k > sizeof(stage)) { + rc = log_write(stage, used); + written += (uint32_t)used; + used = 0u; + } + memcpy(stage + used, m, (size_t)k); + used += (size_t)k; + piece_cont = false; + } + if (n == 0u || rc != 0 || stop) { + break; + } + if (!keep_piece(piece, n)) { + continue; + } + if (used + n > sizeof(stage)) { + rc = log_write(stage, used); + written += (uint32_t)used; + used = 0u; + if (rc != 0) { + break; + } + } + memcpy(stage + used, piece, n); + used += n; + } + if (rc == 0 && used > 0u) { + rc = log_write(stage, used); + written += (uint32_t)used; + } + if (rc == 0 && written > 0u) { + rc = fs_sync(&log_f); + } + const uint32_t ms = k_uptime_get_32() - t0; + sum_flushes++; + sum_bytes += written; + if (ms > sum_max_ms) { + sum_max_ms = ms; + } + return stop ? -ECANCELED : rc; +} + +/* Close the file and let go of the card: unmount, power down, nobody owns it. */ +static void log_finish(void) +{ + if (log_live) { + (void)fs_close(&log_f); + log_live = false; + } + unmount_vol(); + if (!stop) { + sp1_emmc_power_down(); + } + atomic_set(&owner, OWN_NONE); + atomic_set(&log_live_a, 0); +} + +/* After sp1_store_abort: the card is already off and nobody owns it, so closing the file + * cannot write (every disk call checks the owner); it frees the file and the volume. */ +static void log_teardown(void) +{ + torn = false; + if (log_live) { + (void)fs_close(&log_f); + log_live = false; + } + unmount_vol(); + atomic_set(&log_live_a, 0); +} + +/* Every SP1_STORE_LOG_FLUSH_MS while ON, and once a minute the LOG line. */ +static void log_tick(void) +{ + const uint32_t now = k_uptime_get_32(); + if ((int32_t)(now - log_next) < 0) { + return; + } + log_next = ((int32_t)(now - log_next) > (int32_t)SP1_STORE_LOG_FLUSH_MS) + ? now + SP1_STORE_LOG_FLUSH_MS : log_next + SP1_STORE_LOG_FLUSH_MS; + const int rc = log_flush(false); + if (rc != 0) { + if (!stop) { + LINE("LOG off: writing %s failed (%d) -- no more log on the drive " + "until the next ON; the console still has it\n", + log_path + sizeof(DIR_LOGS), rc); + log_finish(); + } + return; + } + if (now - sum_t0 >= LOG_SUMMARY_MS) { + LINE("LOG %u s: %u flushes, %u B written, longest %u ms, %u B lost; log file %u KB%s\n", + (unsigned)((now - sum_t0) / 1000u), (unsigned)sum_flushes, (unsigned)sum_bytes, + (unsigned)sum_max_ms, (unsigned)sum_lost, (unsigned)(log_size / 1024u), + log_full ? " (full)" : ""); + sum_t0 = now; + sum_flushes = sum_bytes = sum_max_ms = sum_lost = 0u; + } +} + +/* The end of an ON session, after any save: the last lines, then let go of the card. */ +static void log_end(void) +{ + if (!log_live) { + return; + } + const uint32_t t0 = k_uptime_get_32(); + LINE("LOG closing %s (%u KB)\n", log_path + sizeof(DIR_LOGS), + (unsigned)(log_size / 1024u)); + const int rc = log_flush(false); + log_finish(); + if (rc != 0 && !stop) { + LINE("LOG the last flush FAILED (%d) after %u ms\n", rc, + (unsigned)(k_uptime_get_32() - t0)); + } +} + /* ---------------------------------------------------------------- fresh */ #if defined(CONFIG_SP1_FRESH) @@ -353,6 +1026,7 @@ static int format_card(void) * ("block writes against ... expected"); it only scales the progress bar. */ fmt_expected += 5u * 64u + 5u * 4u; #endif + /* (WAKES/CNFG and its files are written by the ON job that follows, #52: not counted.) */ fmt_written = 0u; atomic_set(&progress, 0); counting = true; @@ -765,30 +1439,6 @@ static void prst_load_all(void) LINE("STORE PRST on: slot %d current\n", prst_current + 1); } -/* Verify `path` is a FOLDER; create it if nothing is there (Adara, #50). 0 when there is a - * folder to save into. Something else with that name -- a computer can leave a FILE called - * "3" where slot 3's folder should be -- is -ENOTDIR and is left alone: the save fails with - * that in the log rather than touching a file it did not write. */ -static int ensure_dir(const char *path) -{ - static struct fs_dirent st; - int rc = fs_stat(path, &st); - if (rc == 0) { - if (st.type == FS_DIR_ENTRY_DIR) { - return 0; - } - LINE("STORE PRST: %s is a file, not a folder -- not saving there\n", path); - return -ENOTDIR; - } - if (rc != -ENOENT) { - return rc; - } - rc = fs_mkdir(path); - LINE("STORE PRST: no folder %s -- %s (%d)\n", path, rc == 0 ? "created" : "create FAILED", - rc); - return rc; -} - #if defined(CONFIG_SP1_FRESH) /* wakes-sp1-fresh, right after its format (Adara, #50): WAKES/PRST/1..4, each holding N.prst * with the ROTC default patch, and SLOT = 1. Before the stamp, so a failure here formats @@ -821,20 +1471,24 @@ static int prst_write_defaults(void) } #endif -/* The save, at shutdown. The card was powered down after the ON job, so it starts again. */ +/* The save, at shutdown. With the log on (#52) the card is still on and mounted from the ON + * job; otherwise it was powered down after it, and starts again. */ static void job_save(void) { static char tmp[PATH_MAX_]; static char dst[PATH_MAX_]; const uint32_t t0 = k_uptime_get_32(); const int i = save_slot; - claim_for_wakes(); - struct sp1_emmc_ident id; - int rc = sp1_emmc_init(&id) ? 0 : -EIO; - view_base = 0; - view_count = sp1_emmc_sectors(); - if (rc == 0 && !stop) { - rc = mount_vol(); + int rc = 0; + if (!log_live) { + claim_for_wakes(); + struct sp1_emmc_ident id; + rc = sp1_emmc_init(&id) ? 0 : -EIO; + view_base = 0; + view_count = sp1_emmc_sectors(); + if (rc == 0 && !stop) { + rc = mount_vol(); + } } snprintk(tmp, sizeof(tmp), DIR_PRST "/%d", i + 1); if (rc == 0 && !stop) { @@ -864,17 +1518,23 @@ static void job_save(void) if (stop && rc == 0) { rc = -ECANCELED; } - unmount_vol(); - if (!stop) { - sp1_emmc_power_down(); - } - atomic_set(&owner, OWN_NONE); if (rc == 0) { prst_current = i; } LINE("STORE PRST save slot %d -> %s: %s (%d) in %u ms\n", i + 1, prst_name[i], rc == 0 ? "done" : "FAILED", rc, (unsigned)(k_uptime_get_32() - t0)); atomic_set(&save_state, rc == 0 ? SP1_STORE_SAVE_OK : SP1_STORE_SAVE_FAILED); + /* Then the log's last lines (Adara: the save first, the log in the time left); main + * waits for sp1_store_log_live() to drop. */ + if (log_live) { + log_end(); + } else { + unmount_vol(); + if (!stop) { + sp1_emmc_power_down(); + } + atomic_set(&owner, OWN_NONE); + } } #endif /* CONFIG_SP1_PLAITS */ @@ -903,6 +1563,10 @@ static void claim_for_wakes(void) static void job_on_enter(void) { const uint32_t t0 = k_uptime_get_32(); + if (log_live) { + log_teardown(); /* never expected: every way out of ON closes the log */ + } + cnfg_defaults(); /* until (unless) the drive's files say otherwise (#52) */ claim_for_wakes(); struct sp1_emmc_ident id; const bool ok = sp1_emmc_init(&id); /* a fresh start whoever had the card */ @@ -946,6 +1610,10 @@ static void job_on_enter(void) "written; wakes-sp1-fresh creates one\n", rc); } } + /* #52: the config files, every ON, before PRST and before audio. */ + if (rc == 0 && !stop) { + cnfg_load(); + } #if defined(CONFIG_SP1_PLAITS) /* PRST (#50): all four slots into RAM, before main starts audio. */ if (rc == 0 && !stop) { @@ -954,6 +1622,10 @@ static void job_on_enter(void) atomic_set(&prst_state, SP1_STORE_PRST_OFF); } #endif + /* #52: write any config file that was missing, now that main has what it needs. */ + if (rc == 0 && !stop) { + cnfg_create_missing(); + } #if defined(CONFIG_SP1_STORAGE_TEST) if (rc == 0 && !stop) { file_test(); @@ -961,6 +1633,29 @@ static void job_on_enter(void) sp1_emmc_report_stats(); #endif } + /* #52: with logging on, the card stays on and mounted for the whole ON session (Adara) + * and the log is written every SP1_STORE_LOG_FLUSH_MS; every way out of ON lets go of + * it (log_end at shutdown, log_teardown after sp1_store_abort). Off: as before. */ + if (ok && !stop && atomic_get(&vol_state) == SP1_STORE_VOL_OK) { + if (!logs_cfg.enabled) { + sp1_logbuf_file_skip(); /* ...and this whole ON (sp1_logring.h) */ + } else { + sp1_logbuf_file_keep(); + const int lrc = log_open(); + if (lrc != 0 && !stop) { + LINE("LOG off: the log file in WAKES/LOGS/ cannot be opened (%d) -- no log on " + "the drive this ON\n", lrc); + } + } + } + if (log_live) { + LINE("STORE done after %u ms -- the eMMC stays on for the log\n", + (unsigned)(k_uptime_get_32() - t0)); + sum_t0 = k_uptime_get_32(); + sum_flushes = sum_bytes = sum_max_ms = sum_lost = 0u; + log_next = sum_t0; /* the first flush now: the boot so far */ + return; + } unmount_vol(); if (!stop) { sp1_emmc_power_down(); @@ -971,6 +1666,12 @@ static void job_on_enter(void) (unsigned)(k_uptime_get_32() - t0)); } +/* Shutdown with PRST off but the log on: only the log's last lines. */ +static void job_log_end(void) +{ + log_end(); +} + #if defined(CONFIG_SP1_DRIVE) /* STANDBY with a host attached: power the card and, if it holds a filesystem, hand it to * the host until ON (claim_for_wakes) or power-off (sp1_store_abort). A card WITHOUT one @@ -978,6 +1679,9 @@ static void job_on_enter(void) * which Wakes cannot read), and only wakes-sp1-fresh formats (Adara). */ static void job_host(void) { + if (log_live) { + log_teardown(); /* never expected: STANDBY comes after a closed log */ + } k_mutex_lock(&card_lock, K_FOREVER); struct sp1_emmc_ident id; const bool ok = !stop && sp1_emmc_init(&id); @@ -1023,7 +1727,16 @@ static void store_thread(void *a, void *b, void *c) ARG_UNUSED(b); ARG_UNUSED(c); for (;;) { - k_sem_take(&go, K_FOREVER); + /* With the log on, wake for its next flush (#52); otherwise only for a job. */ + k_timeout_t to = K_FOREVER; + if (log_live) { + const int32_t left = (int32_t)(log_next - k_uptime_get_32()); + to = left > 0 ? K_MSEC(left) : K_NO_WAIT; + } + (void)k_sem_take(&go, to); + if (torn) { + log_teardown(); + } for (;;) { const atomic_val_t jobs = atomic_get(&pending); if (jobs & JOB_ON) { /* ON always wins: Wakes takes the card */ @@ -1034,6 +1747,9 @@ static void store_thread(void *a, void *b, void *c) atomic_and(&pending, ~JOB_SAVE); job_save(); #endif + } else if (jobs & JOB_LOGEND) { + atomic_and(&pending, ~JOB_LOGEND); + job_log_end(); } else if (jobs & JOB_HOST) { atomic_and(&pending, ~JOB_HOST); #if defined(CONFIG_SP1_DRIVE) @@ -1042,6 +1758,9 @@ static void store_thread(void *a, void *b, void *c) } else { break; } + if (torn) { + log_teardown(); + } #if defined(CONFIG_SP1_STORAGE_TEST) size_t unused = 0; if (k_thread_stack_space_get(k_current_get(), &unused) == 0) { @@ -1051,6 +1770,9 @@ static void store_thread(void *a, void *b, void *c) } #endif } + if (log_live && !torn) { + log_tick(); + } } } @@ -1071,6 +1793,9 @@ void sp1_store_on_enter(void) atomic_set(&fmt_result, SP1_STORE_FMT_NONE); atomic_set(&progress, 0); atomic_set(&vol_state, SP1_STORE_VOL_UNKNOWN); /* PRST waits for the ON job's look */ +#if defined(CONFIG_SP1_PLAITS) + atomic_set(&cnfg_ready, 0); /* this ON's files not read yet */ +#endif #if defined(CONFIG_SP1_PLAITS) atomic_set(&prst_state, SP1_STORE_PRST_WAIT); atomic_set(&save_state, SP1_STORE_SAVE_IDLE); @@ -1169,10 +1894,35 @@ enum sp1_store_save sp1_store_save_result(void) } #endif +#if defined(CONFIG_SP1_PLAITS) +bool sp1_store_cnfg(const struct sp1_audio_cfg **audio, const struct sp1_midi_cfg **midi) +{ + *audio = &st_audio; + *midi = &st_midi; + return atomic_get(&cnfg_ready) != 0; +} +#endif + +bool sp1_store_log_live(void) +{ + return atomic_get(&log_live_a) != 0; +} + +void sp1_store_log_end(void) +{ + if (atomic_get(&log_live_a) != 0) { + atomic_or(&pending, JOB_LOGEND); + k_sem_give(&go); + } +} + void sp1_store_abort(void) { stop = true; + torn = true; /* the thread lets go of the log file and the volume */ atomic_clear(&pending); atomic_set(&owner, OWN_NONE); + atomic_set(&log_live_a, 0); /* nothing to wait for: the card is going off now */ sp1_emmc_abort(); + k_sem_give(&go); } diff --git a/firmware/src/sp1_store.h b/firmware/src/sp1_store.h index 376aecf..18ca3a5 100644 --- a/firmware/src/sp1_store.h +++ b/firmware/src/sp1_store.h @@ -31,6 +31,7 @@ #ifndef SP1_STORE_H #define SP1_STORE_H +#include #include /* Once at boot, before any other call: registers the disk and starts the thread. */ @@ -147,6 +148,43 @@ enum sp1_store_save { enum sp1_store_save sp1_store_save_result(void); #endif +/* ---- the config files and the log (#52) ---- + * CONFIG: WAKES/CNFG/.cnfg, read by the ON job every ON, after the volume check and + * before PRST (sp1_cnfg.h has the rules): logs.cnfg (line by line) and engines.cnfg (all + * or nothing: any problem -> the built-in stack). No volume -> the built-in everything. + * + * THE LOG (Adara, #52): with logs.cnfg's `enabled = on` (the default) the ON job opens this + * session's file in WAKES/LOGS/ and the card STAYS on and mounted for the whole ON session; + * every SP1_STORE_LOG_FLUSH_MS the thread appends what the RAM log (sp1_logbuf.h) has + * gathered, filtered by logs.cnfg's categories, and syncs. One file per session, NNNN.logs = + * the session number mod 10000 (9999.logs is followed by 0000.logs); the number keeps + * counting in WAKES/LOGS/SESSION. EVERY ON is a new session (Adara, 2026-10-16: STANDBY then + * ON too): it takes the next number and deletes the file SP1_STORE_LOG_KEEP sessions back, + * after appending to the previous session's file what that one still owed it (its closing + * lines, a backstop's tail, or a crash kept across a soft reset). Each file stops at SP1_STORE_LOG_MAX + * with a last line saying so. STANDBY is not logged. A LOG line once a minute gives the + * flushes, bytes and the longest flush (the CPU check Adara asked for). + * At shutdown the PRST save goes first, then the last lines (main waits on + * sp1_store_log_live(), inside the same 4 s). The 30 s backstop never waits for either + * (rule 5a): sp1_store_abort cuts the card off, and the unsynced tail is lost. */ +#define SP1_STORE_LOG_FLUSH_MS 5000u +#define SP1_STORE_LOG_MAX (8u * 1024u * 1024u) +#define SP1_STORE_LOG_KEEP 5u /* sessions kept, this one included (Adara) */ + +/* The log file is open: the card is on for it. Cleared once it is closed and the card is off. */ +bool sp1_store_log_live(void); + +#if defined(CONFIG_SP1_PLAITS) +/* Main, at ON entry after the PRST gate: audio.cnfg and midi.cnfg as this ON's job read + * them (the built-in values when a file is missing or there is no volume). False if the job + * has not got that far this ON (PRST's 10 s limit ran out): keep the settings in use. */ +struct sp1_audio_cfg; +struct sp1_midi_cfg; +bool sp1_store_cnfg(const struct sp1_audio_cfg **audio, const struct sp1_midi_cfg **midi); +#endif +/* Main, at shutdown when no PRST save is queued: the log's last lines, then the card off. */ +void sp1_store_log_end(void); + /* From sp1_quiesce_peripherals(), on every way out of ON and out of STANDBY: stop the job, * take the card from a host, drop queued jobs, and power the card down now. A job cut short by this fails its remaining steps; a format cut short * leaves no FRESH.ID, so the fresh image formats again at the next ON. Never waits. */ diff --git a/firmware/src/sp1_synth.h b/firmware/src/sp1_synth.h index 89379d2..13b85f2 100644 --- a/firmware/src/sp1_synth.h +++ b/firmware/src/sp1_synth.h @@ -43,7 +43,7 @@ extern "C" { /* Engine the voice is constructed with, before the UI publishes its first parameters * (plaits/dsp/voice.cc order): virtual analog. Only a placeholder: the UI starts on the - * first filled slot of config/engines.csv, whatever that is, and publishes it before the + * first filled slot of config/engines.cnfg, whatever that is, and publishes it before the * first block. */ #define SP1_SYNTH_ENGINE_INITIAL 8 diff --git a/firmware/src/sp1_ui_timing.h b/firmware/src/sp1_ui_timing.h index 8887a40..6899fcb 100644 --- a/firmware/src/sp1_ui_timing.h +++ b/firmware/src/sp1_ui_timing.h @@ -266,7 +266,7 @@ * shorter one was hard to read). A sweep restarts it at each change, as scrolling T2/T3 does. */ #define SP1_DISP_ENGINE_HOLD_MS 700u /* pattern shown solid (Adara: 0.7 s) */ #define SP1_DISP_ENGINE_FADE_MS 350u /* then cross-fades into the page */ -/* ---- an engine OFF the engines.csv list (#50, Adara) ---- +/* ---- an engine OFF the engines.cnfg list (#50, Adara) ---- * It has no glyph (glyphs belong to list positions), so its flash is an animation: all four * face LEDs ramp down from 70 % to 0 every SP1_OFFLIST_RAMP_MS, for the same * SP1_DISP_ENGINE_HOLD_MS, then the same fade. 70 % rather than full because of the flash diff --git a/firmware/src/sp1_usbd.c b/firmware/src/sp1_usbd.c index 7a55305..3a6d270 100644 --- a/firmware/src/sp1_usbd.c +++ b/firmware/src/sp1_usbd.c @@ -23,6 +23,7 @@ #include #include "sp1_midi.h" #include "sp1_midi_usb.h" +#include "sp1_cnfg.h" /* struct sp1_midi_cfg: the script's `clock` (#52) */ #include "usb_rt_parse.h" BUILD_ASSERT(CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == SP1_MIDI_STAMP_HZ, @@ -252,7 +253,7 @@ void sp1_midi_usb_rx(const uint8_t *data, size_t len) rt_cin5 = rt_cin5 + 1u; } if (msg[0] != 0u) { - if (SP1_MIDI_CLOCK) { /* the script's `clock` */ + if (sp1_midi_config()->clock) { /* the script's `clock` */ sp1_midi_push(msg, 1u, now); } continue; @@ -265,7 +266,7 @@ void sp1_midi_usb_rx(const uint8_t *data, size_t len) if (cin >= 0x4u && cin <= 0x7u) { const uint8_t mmc = sp1_midi_mmc_feed(&data[i]); if (mmc > 1u) { - if (SP1_MIDI_CLOCK) { + if (sp1_midi_config()->clock) { msg[0] = mmc; sp1_midi_push(msg, 1u, now); } diff --git a/tools/gen_audio.py b/tools/gen_audio.py index 832591b..f4080a9 100644 --- a/tools/gen_audio.py +++ b/tools/gen_audio.py @@ -1,15 +1,16 @@ #!/usr/bin/env python3 -"""wakes-sp1 -- generate the firmware's audio settings from config/audio.ini. +"""wakes-sp1 -- generate the firmware's audio settings from config/audio.cnfg. - gen_audio.py build step (CMake runs this) + gen_audio.py build step (CMake runs this) -config/audio.ini holds the USER's choices for how Wakes' sound leaves the device: today, how +config/audio.cnfg holds the BUILT-IN DEFAULTS (#52) of the user's choices for how Wakes' sound leaves the device: today, how USB audio out sets its level and whether the speaker plays while a host records over USB. This file holds the facts the user cannot choose (VOL's steps). -The build fails, naming the line, on anything invalid -- an unknown section or key, a value -that is not one of the choices, a level that is not one of VOL's steps. A setting that -half-works is worse than one that refuses to build (the same rule as gen_midi.py). +Users edit the copy on the drive, WAKES/CNFG/audio.cnfg, read at every ON by the firmware's +own reader (firmware/src/sp1_cnfg.c: a bad line keeps its default). The build fails, naming +the line, on anything invalid in the DEFAULT -- an unknown section or key, a value that is +not one of the choices, a level that is not one of VOL's steps. Standard library only. Read as UTF-8 (with or without a BOM). """ @@ -30,12 +31,46 @@ KEYS = {'usb': {'level', 'parked_level', 'speaker'}} DEFAULTS = {'level': 'parked', 'parked_level': '-6', 'speaker': 'off'} +def c_template(name, text): + """The file as a C string for the firmware to write to WAKES/CNFG/ when it is missing (#52). + Non-ASCII as octal escapes (a hex escape would swallow the hex digits after it).""" + out = ['#if defined(SP1_CNFG_TEMPLATES)', 'static const char %s[] =' % name] + for ln in text.splitlines(keepends=True): + lit = '' + for b in ln.encode('utf-8'): + ch = chr(b) + if ch == '\\': + lit += '\\\\' + elif ch == '"': + lit += '\\"' + elif ch == '\n': + lit += '\\n' + elif ch == '\t': + lit += '\\t' + elif 0x20 <= b < 0x7f: + lit += ch + else: + lit += '\\%03o' % b + out.append('\t"%s"' % lit) + out += ['\t;' if text else '\t"";', '#endif'] + return out + + +def check_lines(path, text, fail_fn): + """#52: the first line names the format, and no line is longer than the device reads.""" + if not text.lstrip().startswith(';'): + fail_fn(path, 1, 'the file must start with a comment naming its format ("; Format: ini")') + for i, ln in enumerate(text.splitlines(), 1): + if len(ln.encode('utf-8')) > 160: + fail_fn(path, i, 'line is over 160 bytes: the device would ignore it') + + def fail(path, line, msg): where = '%s:%d' % (path, line) if line else path sys.stderr.write('\n%s: error: %s\n\n' 'The audio settings are checked at build time so a mistake cannot reach\n' - 'the device. See the comments in config/audio.ini.\n' % (where, msg)) + 'the device. See the comments in config/audio.cnfg.\n' % (where, msg)) sys.exit(1) @@ -55,6 +90,7 @@ def line_of(text, section, key): def parse(path): with open(path, encoding='utf-8-sig') as f: text = f.read() + check_lines(path, text, fail) cp = configparser.ConfigParser(inline_comment_prefixes=(';', '#'), comment_prefixes=(';', '#'), strict=True, interpolation=None) @@ -104,7 +140,7 @@ def get(key): return cfg -def header(cfg, src): +def header(cfg, src, text): return '\n'.join([ '/* GENERATED by tools/gen_audio.py from %s -- do not edit. */' % src, '#pragma once', @@ -118,7 +154,11 @@ def header(cfg, src): '/* [usb] speaker: 1 = the speaker keeps playing while a host takes USB audio out. */', '#define SP1_AUDIO_USB_SPEAKER %d' % cfg['speaker'], '', - ]) + '/* struct sp1_audio_cfg (sp1_cnfg.h), field by field (#52). */', + '#define SP1_AUDIO_CFG_DEFAULTS { %d, %d, %d, %d }' + % (cfg['parked'], cfg['parked_db'], cfg['parked_step'], cfg['speaker']), + '', + ] + c_template('SP1_AUDIO_TEMPLATE', text) + ['']) def main(): @@ -126,7 +166,9 @@ def main(): sys.stderr.write(__doc__) sys.exit(2) src, out = sys.argv[1], sys.argv[2] - text = header(parse(src), 'config/audio.ini') + with open(src, encoding='utf-8-sig') as f: + raw = f.read().replace('\r\n', '\n') + text = header(parse(src), 'config/audio.cnfg', raw) try: with open(out, encoding='utf-8') as f: if f.read() == text: diff --git a/tools/gen_engines.py b/tools/gen_engines.py index c0a4e9e..ba0172e 100644 --- a/tools/gen_engines.py +++ b/tools/gen_engines.py @@ -1,29 +1,29 @@ #!/usr/bin/env python3 -"""wakes-sp1 -- generate the firmware's engine table from config/engines.csv. +"""wakes-sp1 -- generate the firmware's engine table from config/engines.cnfg. - gen_engines.py build step (CMake runs this) + gen_engines.py build step (CMake runs this) gen_engines.py --list print every engine a config may name Two inputs, deliberately kept apart: - config/engines.csv the USER's choice: which engine sits in which slot. One row per - slot, at most 24, in slot order -- ROW POSITION is the slot. - Columns Slot, Glyph, Engine. Only Engine is the user's: Slot and - Glyph are printed there so the file reads as the device does, and - the build checks they are unchanged. An empty Engine is an empty - slot, which T2/T3 engine select skips. + config/engines.cnfg the DEFAULT engine stack (ini, #52): `slot = engine` under [engines], + slots 1-24. The file is the whole stack: a slot it does not list, or + lists with no name (or `none`), is empty, and T2/T3 skip it. Each + line may carry the slot's glyph as a comment; the build checks it. this file FACTS the user cannot choose: each slot's glyph (SLOT_GLYPHS) and each engine's index inside Plaits and centre detents (PLAITS_ENGINES, keyed by name). -Glyphs are four symbols, T1 first: U+25CF full, U+25D0 half, U+25CB off. The CSV may -also spell them # + . -- editors and spreadsheets sometimes mangle the circles. +Glyphs are four symbols, T1 first: U+25CF full, U+25D0 half, U+25CB off (or # + .). -Standard library only. The CSV is read as UTF-8 (with or without a BOM, which Excel -writes): Windows' default code page would mangle the glyphs. +The build fails, naming the line, on anything wrong in the default: the repository's copy +must be exactly right. (The device's own reader of the drive's copy, when it comes, keeps +going instead -- sp1_cnfg.h's rules.) + +Standard library only. Read as UTF-8, with or without a BOM. """ -import csv import os +import re import sys # ---- facts: NOT user configuration ------------------------------------------------------- @@ -44,29 +44,29 @@ # (SP1_ENGINE_TABLE[].centre). The reasoning for each is in docs/PLAITS-ENGINES.md, "Why # these detents". Change these only when Plaits itself changes. PLAITS_ENGINES = [ - (0, "VA + VCF", "F3 F4"), - (1, "phase distortion", ""), - (2, "6-op FM A", "F3"), - (3, "6-op FM B", "F3"), - (4, "6-op FM C", "F3"), - (5, "wave terrain", "F3"), - (6, "string machine", "F2"), + (0, "VA-VCF", "F3 F4"), + (1, "phase-distortion", ""), + (2, "6-op-FM-A", "F3"), + (3, "6-op-FM-B", "F3"), + (4, "6-op-FM-C", "F3"), + (5, "wave-terrain", "F3"), + (6, "string-machine", "F2"), (7, "chiptune", ""), - (8, "virtual analog", "F2 F4"), + (8, "virtual-analog", "F2 F4"), (9, "waveshaping", "F4"), - (10, "2-op FM", "F3"), - (11, "grain / formant", "F4"), + (10, "2-op-FM", "F3"), + (11, "grain-formant", "F4"), (12, "additive", ""), (13, "wavetable", ""), (14, "chords", ""), (15, "speech", ""), (16, "swarm", ""), - (17, "filtered noise", "F4"), + (17, "filtered-noise", "F4"), (18, "particle", "F3"), (19, "string", ""), (20, "modal", ""), - (21, "bass drum", ""), - (22, "snare drum", ""), + (21, "bass-drum", ""), + (22, "snare-drum", ""), (23, "hi-hat", ""), ] DETENT_BITS = {"F4": 0x1, "F2": 0x2, "F3": 0x4} # HARMONICS, TIMBRE, MORPH @@ -75,12 +75,12 @@ GLYPH_LEVEL = {"β—‹": 0, ".": 0, "◐": 1, "+": 1, "●": 2, "#": 2} ASCII_GLYPH = {ord("●"): "#", ord("◐"): "+", ord("β—‹"): "."} -COLUMNS = ("slot", "glyph", "engine") -CSV_NAME = "config/engines.csv" +CNFG_NAME = "config/engines.cnfg" +LINE_MAX = 160 # SP1_CNFG_LINE_MAX: the device ignores longer lines def fail(msg): - msg = "\n*** %s: %s\n\n" % (CSV_NAME, msg) + msg = "\n*** %s: %s\n\n" % (CNFG_NAME, msg) try: msg.encode(sys.stderr.encoding or "ascii") except UnicodeEncodeError: @@ -98,6 +98,13 @@ def levels(glyph): return [GLYPH_LEVEL[ch] for ch in syms] +def name_key(name): + """How names are compared, here and on the device (sp1_cnfg.h, sp1_engine_name_eq): + letters and digits only, case ignored -- so "grain / formant", "grain-formant" and + "Grain Formant" are one engine, and a PRST file saved under an older spelling loads.""" + return "".join(ch for ch in name.lower() if ch.isascii() and ch.isalnum()) + + def facts(): assert len({tuple(levels(g)) for g in SLOT_GLYPHS}) == MAX_SLOTS, "slot glyphs must differ" by_name = {} @@ -105,59 +112,74 @@ def facts(): bits = 0 for d in det.split(): bits |= DETENT_BITS[d] - by_name[name.lower()] = dict(plaits=idx, name=name, centre=bits) - assert sorted(e["plaits"] for e in by_name.values()) == list(range(24)) + by_name[name_key(name)] = dict(plaits=idx, name=name, centre=bits) + assert sorted(e["plaits"] for e in by_name.values()) == list(range(24)), "names must differ" return by_name -def parse(csv_path): - known = facts() - with open(csv_path, encoding="utf-8-sig", newline="") as f: - rows = [(n + 1, r) for n, r in enumerate(csv.reader(f)) if r] - if not rows: - fail("the file is empty") - header = [c.strip().lower() for c in rows[0][1]] - if tuple(header[:3]) != COLUMNS: - fail("line %d: the first row must be the header Slot,Glyph,Engine -- got %s" - % (rows[0][0], ",".join(rows[0][1]))) - rows = rows[1:] - if len(rows) > MAX_SLOTS: - fail("%d slots listed; there are at most %d" % (len(rows), MAX_SLOTS)) - - slots, used = [], {} - for n, (line, r) in enumerate(rows): - slot = n + 1 - r = [c.strip() for c in r] + [""] * 3 - slot_t, glyph_t, name_t = r[:3] - where = "line %d (slot %d)" % (line, slot) - # Slot and Glyph are labels, not settings: row position is the slot, and the - # glyph belongs to the slot. A mismatch means a whole row was moved, or edited. - if slot_t != str(slot): - fail("%s: the Slot column says %r, but this is row %d, so slot %d.\n" - " Row position is the slot and cannot be changed. To reorder, move the\n" - " Engine names between rows, not whole rows." % (where, slot_t, slot, slot)) - want = SLOT_GLYPHS[n] - got = levels(glyph_t) - if got != levels(want): - hint = ("" if got is not None else - "\n If the circles came out as '?' or garbage, your editor saved in the" - "\n wrong encoding: save as UTF-8, or write the glyph as `%s`." - % want.translate(ASCII_GLYPH)) - fail("%s: slot %d's glyph is %s and cannot be changed -- the file says `%s`.%s" - % (where, slot, want, glyph_t, hint)) - entry = dict(slot=slot, levels=levels(want), on=False, plaits=0, centre=0, name="") - if name_t: - e = known.get(name_t.lower()) - if e is None: - fail("%s: no engine is called %r. Available engines:\n %s" - % (where, name_t, "\n ".join(n for _, n, _ in PLAITS_ENGINES))) - if e["name"] in used: - fail("%s: %s is already in slot %d; an engine can be listed once" - % (where, e["name"], used[e["name"]])) - used[e["name"]] = slot - entry.update(e, on=True) - slots.append(entry) +def ini_lines(path): + """(line number, key, value, comment) for every setting, split the way the device's + reader splits them (sp1_cnfg.c): ; or # at the value's start or after whitespace starts + a comment.""" + with open(path, encoding="utf-8-sig") as f: + lines = f.read().split("\n") + if not lines[0].lstrip().startswith(";"): + fail('line 1: the file must start with a comment naming its format ("; Format: ini")') + section, out = "", [] + for n, raw in enumerate(lines, 1): + if len(raw.rstrip("\r").encode("utf-8")) > LINE_MAX: + fail("line %d is over %d bytes: the device would ignore it" % (n, LINE_MAX)) + s = raw.strip() + if not s or s[0] in ";#": + continue + if s[0] == "[": + if not s.endswith("]"): + fail("line %d: a section name needs a closing ]" % n) + section = s[1:-1].strip().lower() + if section != "engines": + fail("line %d: unknown section [%s] (expected [engines])" % (n, section)) + continue + if not section: + fail("line %d: %r is not under [engines]" % (n, s)) + if "=" not in s: + fail("line %d: %r is not a setting (slot = engine)" % (n, s)) + key, val = s.split("=", 1) + m = re.search(r"(^|\s)[;#]", val) + comment = val[m.end():].strip() if m else "" + val = (val[:m.start()] if m else val).strip() + out.append((n, key.strip().lower(), val, comment)) + return out + +def parse(path): + known = facts() + slots = [dict(slot=n + 1, levels=levels(g), on=False, plaits=0, centre=0, name="") + for n, g in enumerate(SLOT_GLYPHS)] + seen, used = {}, {} + for line, key, val, comment in ini_lines(path): + where = "line %d" % line + if not key.isdigit() or not 1 <= int(key) <= MAX_SLOTS: + fail("%s: %r is not a slot (1-%d)" % (where, key, MAX_SLOTS)) + slot = int(key) + if slot in seen: + fail("%s: slot %d is already set on line %d" % (where, slot, seen[slot])) + seen[slot] = line + want = SLOT_GLYPHS[slot - 1] + if comment and levels(comment) is not None and levels(comment) != levels(want): + fail("%s: slot %d's glyph is %s; the comment says %s. The glyph belongs to the\n" + " slot: move engine NAMES between slots, not whole lines with their glyphs." + % (where, slot, want, comment)) + if not val or val.lower() == "none": + continue + e = known.get(name_key(val)) + if e is None: + fail("%s: no engine is called %r. Available engines:\n %s" + % (where, val, "\n ".join(n for _, n, _ in PLAITS_ENGINES))) + if e["name"] in used: + fail("%s: %s is already in slot %d; an engine can be listed once" + % (where, e["name"], used[e["name"]])) + used[e["name"]] = slot + slots[slot - 1].update(e, on=True) if not used: fail("every slot is empty; the firmware needs at least one engine") return slots @@ -168,13 +190,13 @@ def c_str(s): return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' -def generate(csv_path, out_path): - slots = parse(csv_path) +def generate(path, out_path): + slots = parse(path) # The device starts on the first slot with an engine in it (M4, Adara: slot 1 by default). default = next(n for n, s in enumerate(slots) if s["on"]) out = [ - "/* GENERATED from config/engines.csv by tools/gen_engines.py.", - " * Do not edit: edit the CSV and rebuild. */", + "/* GENERATED from config/engines.cnfg by tools/gen_engines.py.", + " * Do not edit: edit config/engines.cnfg and rebuild. */", "#ifndef SP1_ENGINES_GEN_H", "#define SP1_ENGINES_GEN_H", "", @@ -183,6 +205,12 @@ def generate(csv_path, out_path): "#define SP1_ENGINE_SLOTS %d" % len(slots), "#define SP1_ENGINE_DEFAULT_SLOT %d /* the first slot with an engine */" % default, "", + "/* The built-in stack as Plaits indices, 255 = an empty slot: the initialiser of the", + " * RAM stack that WAKES/CNFG/engines.cnfg replaces at ON (sp1_plaits_ui.c, #52). */", + "#define SP1_ENGINE_EMPTY 255u", + "#define SP1_ENGINE_DEFAULT_STACK { %s }" % ", ".join( + str(s["plaits"]) if s["on"] else "255" for s in slots), + "", "/* on: 0 = an empty slot, which engine select skips", " * centre: 0x1 = F4 HARMONICS, 0x2 = F2 TIMBRE, 0x4 = F3 MORPH", " * led: T1..T4, 0 = off, 1 = half, 2 = full (the slot's fixed glyph) */", @@ -199,8 +227,8 @@ def generate(csv_path, out_path): % ((s["plaits"], int(s["on"]), s["centre"]) + tuple(s["levels"]) + (c_str(s["name"]), s["slot"]))) # Every engine in the build, listed or not, by its Plaits index (#50): a PRST slot may - # name an engine that is not in this CSV, and the firmware plays it -- every build - # contains all of Plaits' engines; the CSV only chooses which ones T2/T3 reach. + # name an engine that is not in the stack, and the firmware plays it -- every build + # contains all of Plaits' engines; engines.cnfg only chooses which ones T2/T3 reach. by_idx = sorted(facts().values(), key=lambda e: e["plaits"]) out += ["};", "", "#define SP1_PLAITS_ENGINE_COUNT %d" % len(by_idx), "", @@ -211,7 +239,30 @@ def generate(csv_path, out_path): "} SP1_PLAITS_ENGINES[SP1_PLAITS_ENGINE_COUNT] = {"] for e in by_idx: out.append("\t{ 0x%x, %s }, /* plaits %2d */" % (e["centre"], c_str(e["name"]), e["plaits"])) - out += ["};", "", "#endif /* SP1_ENGINES_GEN_H */", ""] + out += ["};", ""] + # #52: the file itself, for the firmware to write to WAKES/CNFG/ when it is missing. + with open(path, encoding="utf-8-sig") as f: + template = f.read().replace("\r\n", "\n") + out += ["#if defined(SP1_CNFG_TEMPLATES)", + "static const char SP1_ENGINES_TEMPLATE[] ="] + for ln in template.splitlines(keepends=True): + lit = "" + for b in ln.encode("utf-8"): + ch = chr(b) + if ch == "\\": + lit += "\\\\" + elif ch == '"': + lit += '\\"' + elif ch == "\n": + lit += "\\n" + elif ch == "\t": + lit += "\\t" + elif 0x20 <= b < 0x7F: + lit += ch + else: + lit += "\\%03o" % b + out.append('\t"%s"' % lit) + out += ["\t;" if template else '\t"";', "#endif", "", "#endif /* SP1_ENGINES_GEN_H */", ""] text = "\n".join(out) os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) try: @@ -230,7 +281,7 @@ def generate(csv_path, out_path): for idx, name, det in PLAITS_ENGINES: print("%-18s Plaits #%-2d detents %s" % (name, idx, det or "-")) elif len(a) == 2: - CSV_NAME = os.path.normpath(a[0]) + CNFG_NAME = os.path.normpath(a[0]) generate(a[0], a[1]) else: sys.stderr.write(__doc__) diff --git a/tools/gen_logs.py b/tools/gen_logs.py new file mode 100644 index 0000000..2b92499 --- /dev/null +++ b/tools/gen_logs.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""wakes-sp1 -- the built-in logging defaults, from config/logs.cnfg (#52). + + gen_logs.py build step (CMake runs this) + +config/logs.cnfg is the DEFAULT: what Wakes does when the drive has no WAKES/CNFG/logs.cnfg, +or a line in it cannot be read. 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_LOGS_TEMPLATE). + +The build fails, naming the line, on anything invalid: a default that half-works is worse +than one that refuses to build (gen_audio.py's rule). The device reads the drive's copy with +its own reader (firmware/src/sp1_cnfg.c), which never fails: a bad line keeps its default. +tools/host-tests/cnfgtest.c runs that reader over this file and checks it agrees. + +Standard library only. Read as UTF-8 (with or without a BOM). +""" +import configparser +import os +import re +import sys + +KEYS = ['enabled', 'performance', 'controls', 'midi', 'usb', 'storage'] +CATS = {'performance': 'SP1_LOG_PERFORMANCE', 'controls': 'SP1_LOG_CONTROLS', + 'midi': 'SP1_LOG_MIDI', 'usb': 'SP1_LOG_USB', 'storage': 'SP1_LOG_STORAGE'} +ONOFF = {'on': 1, 'off': 0} +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 logging defaults are checked at build time. See the\n' + 'comments in config/logs.cnfg.\n' % (where, msg)) + sys.exit(1) + + +def line_of(text, section, key): + cur = None + for i, ln in enumerate(text.splitlines(), 1): + s = ln.strip() + m = re.match(r'^\[(.+)\]$', s) + if m: + cur = m.group(1).strip().lower() + elif cur == section and re.match(r'^%s\s*=' % re.escape(key), s, re.I): + return i + return 0 + + +def parse(path): + 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: ini")') + for i, ln in enumerate(text.splitlines(), 1): + if len(ln.encode('utf-8')) > LINE_MAX: + fail(path, i, 'line is over %d bytes: the device would ignore it' % LINE_MAX) + cp = configparser.ConfigParser(inline_comment_prefixes=(';', '#'), + comment_prefixes=(';', '#'), strict=True, + interpolation=None) + try: + cp.read_string(text, source=path) + except configparser.Error as e: + fail(path, getattr(e, 'lineno', 0), str(e).splitlines()[0]) + for sec in cp.sections(): + if sec != 'logs': + fail(path, 0, 'unknown section [%s] (expected [logs])' % sec) + logs = cp['logs'] if cp.has_section('logs') else {} + cfg = {} + for key in logs: + if key not in KEYS: + fail(path, line_of(text, 'logs', key), 'unknown setting "%s" (expected %s)' + % (key, ', '.join(KEYS))) + for key in KEYS: + v = logs.get(key, 'on').strip().lower() + if v not in ONOFF: + fail(path, line_of(text, 'logs', key), '%s must be on or off, not "%s"' % (key, v)) + cfg[key] = ONOFF[v] + return cfg, text + + +def c_string(text): + """The text as C string literals, one per line; non-ASCII as octal escapes (a hex escape + would swallow the hex digits after it).""" + 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(cfg, text): + cats = [CATS[k] for k in CATS if cfg[k]] + return '\n'.join([ + '/* GENERATED by tools/gen_logs.py from config/logs.cnfg -- do not edit. */', + '#pragma once', + '', + '/* The built-in defaults (sp1_cnfg.h: SP1_LOG_*). */', + '#define SP1_LOGS_DEF_ENABLED %d' % cfg['enabled'], + '#define SP1_LOGS_DEF_CATS (%s)' % (' | '.join(cats) if cats else '0u'), + '', + '/* config/logs.cnfg as the firmware writes it to WAKES/CNFG/ when it is missing; sp1_store.c', + ' * defines SP1_CNFG_TEMPLATES before including this (no other file has a use for it). */', + '#if defined(SP1_CNFG_TEMPLATES)', + 'static const char SP1_LOGS_TEMPLATE[] =', + c_string(text) + ';', + '#endif', + '', + ]) + + +def main(): + if len(sys.argv) != 3: + sys.stderr.write(__doc__) + sys.exit(2) + src, out = sys.argv[1], sys.argv[2] + cfg, text = parse(src) + text = header(cfg, 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/gen_midi.py b/tools/gen_midi.py index 709c9a6..a9f8e55 100644 --- a/tools/gen_midi.py +++ b/tools/gen_midi.py @@ -1,20 +1,23 @@ #!/usr/bin/env python3 -"""wakes-sp1 -- generate the firmware's MIDI tables from the MIDI script, config/midi.ini. +"""wakes-sp1 -- generate the firmware's MIDI tables from the MIDI script, config/midi.cnfg. - gen_midi.py [--chart ] build step (CMake runs this) + gen_midi.py [--chart ] build step (CMake runs this) -Two inputs, deliberately kept apart (as gen_engines.py does for engines.csv): +Two inputs, deliberately kept apart (as gen_engines.py does for engines.cnfg): - config/midi.ini the USER's choices: channel, note priority, legato, portamento, bend - range, the sustain pedal's CC, the CC smoothing time, which CC moves - which parameter, and optional velocity / aftertouch bindings. + config/midi.cnfg the BUILT-IN DEFAULTS (#52): channel, note priority, legato, + portamento, bend range, the sustain pedal's CC, the CC smoothing time, + which CC moves which parameter, and velocity / aftertouch bindings. Users + edit the copy on the drive, WAKES/CNFG/midi.cnfg, which the firmware reads + at every ON with its own reader (firmware/src/sp1_cnfg.c, the same rules + but it never fails: a bad line keeps its default). The firmware writes + this file there when it is missing (SP1_MIDI_TEMPLATE). this file FACTS the user cannot choose: which parameters exist, which thread applies each one, and which CC numbers MIDI itself reserves (DESTS, RESERVED). -The build fails, naming the line, on anything invalid -- an unknown name, a CC used twice, -a reserved CC, a value out of range. A script that half-works is worse than one that -refuses to build. +The build fails, naming the line, on anything invalid in the DEFAULT -- an unknown name, a +CC used twice, a reserved CC, a value out of range: a broken default must never ship. --chart also writes the CC chart for this script, next to the firmware: wakes-sp1-midi.md for people @@ -115,12 +118,46 @@ def polarity_code(k): PICKUP = {'sum': 0, 'shared': 1, 'takeover': 2} SOURCES = ('velocity', 'aftertouch') +def c_template(name, text): + """The file as a C string for the firmware to write to WAKES/CNFG/ when it is missing (#52). + Non-ASCII as octal escapes (a hex escape would swallow the hex digits after it).""" + out = ['#if defined(SP1_CNFG_TEMPLATES)', 'static const char %s[] =' % name] + for ln in text.splitlines(keepends=True): + lit = '' + for b in ln.encode('utf-8'): + ch = chr(b) + if ch == '\\': + lit += '\\\\' + elif ch == '"': + lit += '\\"' + elif ch == '\n': + lit += '\\n' + elif ch == '\t': + lit += '\\t' + elif 0x20 <= b < 0x7f: + lit += ch + else: + lit += '\\%03o' % b + out.append('\t"%s"' % lit) + out += ['\t;' if text else '\t"";', '#endif'] + return out + + +def check_lines(path, text, fail_fn): + """#52: the first line names the format, and no line is longer than the device reads.""" + if not text.lstrip().startswith(';'): + fail_fn(path, 1, 'the file must start with a comment naming its format ("; Format: ini")') + for i, ln in enumerate(text.splitlines(), 1): + if len(ln.encode('utf-8')) > 160: + fail_fn(path, i, 'line is over 160 bytes: the device would ignore it') + + def fail(path, line, msg): where = '%s:%d' % (path, line) if line else path sys.stderr.write('\n%s: error: %s\n\n' 'The MIDI script is checked at build time so a mistake cannot reach\n' - 'the device. See the comments in config/midi.ini.\n' % (where, msg)) + 'the device. See the comments in config/midi.cnfg.\n' % (where, msg)) sys.exit(1) @@ -140,6 +177,7 @@ def line_of(text, section, key): def parse(path): with open(path, encoding='utf-8-sig') as f: text = f.read() + check_lines(path, text, fail) # interpolation=None: a depth is written "50%", and configparser's default # interpolation would read the % as the start of a %(name)s reference and crash. cp = configparser.ConfigParser(inline_comment_prefixes=(';', '#'), @@ -248,7 +286,7 @@ def cc_value(sec, key, raw, allow_none): continue for k, raw in cp[sec].items(): if (sec, k) not in names: - err(sec, k, 'no parameter "%s" in [%s] (see the list in config/midi.ini)' + err(sec, k, 'no parameter "%s" in [%s] (see the list in config/midi.cnfg)' % (k, sec)) n = cc_value(sec, k, raw, True) if n < 0: @@ -268,6 +306,8 @@ def cc_value(sec, key, raw, allow_none): for k, raw in b.items(): if k not in SOURCES: err('bind', k, 'unknown source "%s" (expected velocity or aftertouch)' % k) + if raw.strip().lower() == 'none': + continue # #52: `velocity = none` mm = re.fullmatch(r'([a-z_]+)(?:\s+(-?\d+)\s*%)?', raw.strip().lower()) if not mm: err('bind', k, '"%s" is not " [depth%%]"' % raw.strip()) @@ -289,7 +329,7 @@ def generate(ini, out, chart_dir): for i, n in enumerate(ccs): if n >= 0: cc_dest[n] = i - L = ['/* GENERATED by tools/gen_midi.py from config/midi.ini -- do not edit. */', + L = ['/* GENERATED by tools/gen_midi.py from config/midi.cnfg -- do not edit. */', '#ifndef SP1_MIDI_GEN_H', '#define SP1_MIDI_GEN_H', '', '#include ', '', '#define SP1_MIDI_OMNI 16', '#define SP1_MIDI_CHANNEL %d /* 0-15, or SP1_MIDI_OMNI */' % cfg['channel'], @@ -338,7 +378,21 @@ def generate(ini, out, chart_dir): 'static const int8_t SP1_MIDI_CC_DEST[128] = {'] for r in range(0, 128, 16): L.append('\t' + ' '.join('%d,' % x for x in cc_dest[r:r + 16])) - L += ['};', '#endif /* SP1_MIDI_GEN_TABLES */', '', '#endif /* SP1_MIDI_GEN_H */', ''] + L += ['};', '#endif /* SP1_MIDI_GEN_TABLES */', ''] + # #52: the whole default as ONE initializer of struct sp1_midi_cfg (sp1_cnfg.h), in its field + # order: the firmware's live settings start from it, and the drive's reader resets to it. + vel = binds.get('velocity', (-1, 0.0)) + aft = binds.get('aftertouch', (-1, 0.0)) + L += ['/* struct sp1_midi_cfg (sp1_cnfg.h), field by field. */', + '#define SP1_MIDI_CFG_DEFAULTS { %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %sf, %sf, \\' + % (cfg['channel'], cfg['priority'], cfg['legato'], cfg['portamento'], cfg['bend_range'], + cfg['sustain'], cfg['smooth_ms'], cfg['pickup'], cfg['clock'], cfg['clock_lead'], + vel[0], aft[0], repr(float(vel[1])), repr(float(aft[1]))), + '\t{ %s }, \\' % ', '.join(str(n) for n in ccs), + '\t{ %s } }' % ', '.join(str(x) for x in cc_dest), ''] + with open(ini, encoding='utf-8-sig') as f: + L += c_template('SP1_MIDI_TEMPLATE', f.read().replace('\r\n', '\n')) + L += ['', '#endif /* SP1_MIDI_GEN_H */', ''] write_if_changed(out, '\n'.join(L)) if chart_dir: write_charts(chart_dir, cfg, ccs, binds) @@ -375,7 +429,8 @@ def write_charts(d, cfg, ccs, binds): ' with the value the fader left. Unplug and the fader catches up in turn.'], }[cfg['pickup']] md = ['# Wakes β€” MIDI CC chart', '', - 'Generated from `config/midi.ini` by the build that produced this firmware.', '', + 'The built-in MIDI script (`config/midi.cnfg`) of the build that produced this ' + 'firmware. Your `WAKES/CNFG/midi.cnfg` on the drive may change it.', '', '- Channel: **%s**' % ch, '- Notes play Plaits; pitch bend Β±%d semitones until the host sends RPN 0' % cfg['bend_range'], diff --git a/tools/gen_prst.py b/tools/gen_prst.py index f6cf69e..ccd226e 100644 --- a/tools/gen_prst.py +++ b/tools/gen_prst.py @@ -64,13 +64,13 @@ # ---- the fields, in the order they are written ------------------------------------------- # (section, key, kind, check, path in struct sp1_prst) -# kind engine = an engine NAME (config/engines.csv), resolved to its slot +# kind engine = an engine NAME (config/engines.cnfg), resolved to its slot # pos = a fader value, 0..1 (pot space, before detents) # = 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 # t_dest / x_dest = on that side's destination ring -# Fader keys use config/midi.ini's names, so the two files speak the same vocabulary. +# Fader keys use config/midi.cnfg's names, so the two files speak the same vocabulary. T, TS, XB, Y = 'SP1_MUI_T_BASE', 'SP1_MUI_T_SHIFT', 'SP1_MUI_X_BASE', 'SP1_MUI_Y' B, SH, ST = 'SP1_PUI_BASE', 'SP1_PUI_SHIFT', 'SP1_PUI_SETTINGS' FIELDS = [ diff --git a/tools/host-tests/README.md b/tools/host-tests/README.md index 02f66f2..5b6b3df 100644 --- a/tools/host-tests/README.md +++ b/tools/host-tests/README.md @@ -8,21 +8,22 @@ proved on a laptop, and because there is exactly one SP-1 (`docs/SAFETY.md`). |---|---|---| | `uitest.c` | `sp1_plaits_ui.c` + `sp1_marbles_ui.c`, with stubs | pages, layers, pickup, detents, rings, glyph uniqueness, scale stepping, the DEJA VU toggles, the V/Oct interlock, both rip wipes, `[J]`, GTLT on t SHIFT F1, Unpatch eating its own release (`sp1_release_guard.h`) | | `routetest.cc` | all of Plaits and Marbles (with the overrides applied) + `sp1_synth.cc` + `sp1_marbles.cc` + both UI objects | routing, TRIG edges, the summing clamp, the HARMONICS attenuverter, the FREQUENCY quantizer's note sets, the soft-clip drive, the deferred re-seed, INTELLIGENT's per-channel ranges, GTLT's curve and TRIG exemption | -| `miditest.cc` | the same + `sp1_midi.cc`, against the shipped `config/midi.ini` with its `pickup` set to `sum` | MIDI in (M5a): note priority and legato off, the LEVEL hand-back through a real LPG, sustain, 7- and 14-bit CCs read by polarity, the catch-up across an engine change, smoothing, pitch bend and RPN 0, channel filter, placement inside the audio block, queue overflow, disconnect to neutral, the quantizer bypass, stepped targets, Marbles offsets | +| `miditest.cc` | the same + `sp1_midi.cc`, against the shipped `config/midi.cnfg` with its `pickup` set to `sum` | MIDI in (M5a): note priority and legato off, the LEVEL hand-back through a real LPG, sustain, 7- and 14-bit CCs read by polarity, the catch-up across an engine change, smoothing, pitch bend and RPN 0, channel filter, placement inside the audio block, queue overflow, disconnect to neutral, the quantizer bypass, stepped targets, Marbles offsets | | `miditest_pickup.cc` | the same, against the shipped script with `pickup` set to `shared`, then `takeover`: two binaries, `miditest_pickup_shared` and `miditest_pickup_takeover` | a CC as a second hand on the fader's value: its first value only a reference, Plaits' catch-up both ways between CC and fader, a rip under a CC, a page not on show, Marbles not on show, MODEL still an offset, a disconnect leaving the values; takeover's resting faders and their catch-up after unplugging | | `miditest_clock.cc` | the same as `miditest.cc`, with real cycle-counter stamps on every tick | MIDI clock and transport into Marbles (M5b): tempo and position from ticks, Β±1 ms of USB jitter, a stopped clock waiting, Start arming beat 1 on its own Plaits block, Marbles' beats at the host's tempo, RATE as Marbles' ratio table (Γ—4, Γ—1/4), Stop / Continue, a stalled clock, PLAY on the host's clock, and the cable pulled (Marbles stops, own clock again) | | `miditest_alt.cc` | the same, built against `midi-alt.ini` (pickup `sum`) | omni, legato on, Yarns' portamento curve, velocity -> LEVEL, aftertouch -> TIMBRE, no sustain pedal, bend range | | `third_party/feldd/test/test_usb_rt_parse.c` | feldd's packet validator | feldd's own test, unmodified | | `prsttest.c` | `sp1_prst.c` + both UI files, with the same stubs as `uitest` | PRST slot files (#50): the ROTC defaults come from the rip code and a rip still gives them, write -> read returns the patch, every corrupt field (NaN, inf, out of range, exponent, unknown token, a destination off its ring, a scale not included) loads only THAT field's default and a bad BASE fader the loaded engine's neutral, unknown engine -> slot 1, an unknown or missing format -> the whole slot from defaults, hand-edited text (CRLF, case, comments, duplicates), the writer never overruns, and ~23 000 truncated / damaged / random files all give a safe patch | +| `cnfgtest.c` | `sp1_cnfg.c` + `sp1_logring.c`, nothing else | The config files and the log on the drive (#52): `config/logs.cnfg` as fresh writes it reads back as exactly the built-in defaults at any chunk size; overrides, case, CRLF, a BOM, inline comments; a bad value, an unknown key or section, a line with no `=`, a section with no `]` and an over-long line each keep their defaults and are reported on the right line; the same key twice -> the first wins; every log tag lands in its category and untagged lines are always written; the file's cursor takes whole lines, skips STANDBY, counts what an overrun lost (not the gap's own bytes) and resumes on a whole line, survives the 32-bit wrap, and a kept ring with a bad header is rejected; engines.cnfg all-or-nothing; audio.cnfg and midi.cnfg: their templates read back as exactly the built-in values, every [midi] value form, bad values keep their defaults, and the CC rule -- a user line takes a default's CC (a note), two user lines on one CC (first wins), the sustain pedal as a line, reserved CCs and fine halves, [bind] with depth or none | | `uactest.c` | Ryan Gilmore's USB audio ring and packet regulator (`third_party/sp1-usb-audio`, with Wakes' word-copy patch applied as the firmware will) at Wakes' tuning, `firmware/src/sp1_uac_tuning.h` | USB audio out (M5c): Β±200 ppm of clock drift, a heavy patch starting and stopping, a 200 % block every 997, with no underflow, no lost frame, a margin left in the ring, at most 20 packet-size corrections a second and none from load alone; priming, underflow, overflow | ```sh tools/host-tests/hostbuild.sh routetest.cc uitest.c miditest.cc miditest_alt.cc \ miditest_pickup.cc miditest_clock.cc ../../third_party/feldd/test/test_usb_rt_parse.c \ - uactest.c prsttest.c + uactest.c prsttest.c cnfgtest.c cd /tmp/wakes-sp1-host && ./routetest && ./uitest && ./miditest && ./miditest_alt \ && ./miditest_pickup_shared && ./miditest_pickup_takeover && ./miditest_clock \ - && ./test_usb_rt_parse && ./uactest && ./prsttest + && ./test_usb_rt_parse && ./uactest && ./prsttest && ./cnfgtest ``` Builds go to `$TMPDIR/wakes-sp1-host` (override with `SP1_HOST_BUILD_DIR`); nothing is written diff --git a/tools/host-tests/cnfgtest.c b/tools/host-tests/cnfgtest.c new file mode 100644 index 0000000..2b22452 --- /dev/null +++ b/tools/host-tests/cnfgtest.c @@ -0,0 +1,761 @@ +/* wakes-sp1 #52: host checks of the config-file reader (sp1_cnfg.c) and the log file's cursor + * into the RAM log (sp1_logring.c) -- the cases that would take hours, or a broken drive, to + * make on the device. */ +#include +#include +#include + +#define SP1_CNFG_TEMPLATES +#include "sp1_cnfg.h" +#include "sp1_logring.h" +#include "sp1_logs_gen.h" +#include "sp1_engines_gen.h" +#include "sp1_audio_gen.h" + +static int fails; +#define CHECK(cond, ...) do { if (!(cond)) { printf(" FAIL: "); \ + printf(__VA_ARGS__); printf("\n"); fails++; } } while (0) + +/* ---------------------------------------------------------------- the reader */ + +static int problems_seen; +static int last_line; +static char last_what[200]; + +static void problem(void *ctx, int line, const char *what, const char *why) +{ + (void)ctx; + problems_seen++; + last_line = line; + snprintf(last_what, sizeof(last_what), "%s", what); + if (getenv("CNFGTEST_VERBOSE")) { + printf(" line %d: %s -- %s\n", line, what, why); + } +} + +/* Read `text` over the defaults, `chunk` bytes at a time (0 = all at once). */ +static int read_logs(const char *text, size_t chunk, struct sp1_logs_cfg *c) +{ + struct sp1_logs_reader r; + problems_seen = 0; + last_line = 0; + last_what[0] = '\0'; + sp1_logs_defaults(c); + sp1_logs_begin(&r, c, 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_logs_feed(&r, text + i, (i + chunk <= n) ? chunk : n - i); + } + const int bad = sp1_logs_end(&r); + CHECK(bad == problems_seen, "reader counted %d problems, reported %d", bad, problems_seen); + return bad; +} + +static void reader(void) +{ + printf("[1] logs.cnfg: the reader\n"); + struct sp1_logs_cfg c, d; + sp1_logs_defaults(&d); + CHECK((d.cats & ~SP1_LOG_ALL) == 0u, "the shipped defaults: unknown bits 0x%02x", d.cats); + /* The checks below hold whatever config/logs.cnfg ships with: a line that must be + * IGNORED sets the opposite of its default, so it would show if it were applied. */ + const char *not_midi = (d.cats & SP1_LOG_MIDI) ? "off" : "on"; + const char *not_usb = (d.cats & SP1_LOG_USB) ? "off" : "on"; + char f[96]; + + /* The template the firmware writes when the file is missing reads back as exactly the built-in defaults, 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_logs(SP1_LOGS_TEMPLATE, chunks[k], &c); + CHECK(bad == 0, "template, chunk %u: %d problems (line %d: %s)", (unsigned)chunks[k], bad, + last_line, last_what); + CHECK(c.enabled == d.enabled && c.cats == d.cats, + "template, chunk %u: %d/0x%02x, defaults %d/0x%02x", (unsigned)chunks[k], c.enabled, + c.cats, d.enabled, d.cats); + } + + /* Overrides, case, CRLF, a BOM, inline comments, no newline at the end. */ + CHECK(read_logs("\xEF\xBB\xBF; Format: ini\r\n[LOGS]\r\nEnabled = OFF ; quiet\r\n" + "midi=off\r\nusb = on # yes\r\nstorage = off", 0u, &c) == 0, + "overrides: %d problems (line %d: %s)", problems_seen, last_line, last_what); + CHECK(!c.enabled && c.cats == ((d.cats & (SP1_LOG_PERFORMANCE | SP1_LOG_CONTROLS)) | + SP1_LOG_USB), + "overrides: got %d/0x%02x", c.enabled, c.cats); + + /* A bad value keeps its default; the rest of the file still applies. */ + CHECK(read_logs("[logs]\nenabled = maybe\nmidi = off\n", 0u, &c) == 1 && last_line == 2, + "bad value: %d problems, line %d", problems_seen, last_line); + CHECK(c.enabled == d.enabled && !(c.cats & SP1_LOG_MIDI), "bad value: got %d/0x%02x", + c.enabled, c.cats); + CHECK(strcmp(last_what, "enabled = maybe") == 0, "bad value named as \"%s\"", last_what); + + /* The same key twice: the FIRST is used (Adara's rule, #52). */ + CHECK(read_logs("[logs]\nmidi = off\nmidi = on\n", 0u, &c) == 1 && last_line == 3, + "twice: %d problems, line %d", problems_seen, last_line); + CHECK(!(c.cats & SP1_LOG_MIDI), "twice: the first did not win (0x%02x)", c.cats); + /* ...also when the first one was unreadable: it still counts as set. */ + snprintf(f, sizeof(f), "[logs]\nusb = ?\nusb = %s\n", not_usb); + CHECK(read_logs(f, 0u, &c) == 2 && (c.cats & SP1_LOG_USB) == (d.cats & SP1_LOG_USB), + "twice, first bad: %d problems, 0x%02x", problems_seen, c.cats); + + /* Unknown key, unknown section (reported once, its keys ignored), outside any section, + * no '=', a section without its ']'. */ + CHECK(read_logs("[logs]\nverbose = on\n", 0u, &c) == 1 && last_line == 2, + "unknown key: %d problems, line %d", problems_seen, last_line); + CHECK(read_logs("[midi]\nchannel = 3\nclock = off\n[logs]\nmidi = off\n", 0u, &c) == 1 && + last_line == 2 && !(c.cats & SP1_LOG_MIDI), + "unknown section: %d problems, line %d, 0x%02x", problems_seen, last_line, c.cats); + snprintf(f, sizeof(f), "midi = %s\n[logs]\n", not_midi); + CHECK(read_logs(f, 0u, &c) == 1 && (c.cats & SP1_LOG_MIDI) == (d.cats & SP1_LOG_MIDI), + "outside a section: %d problems, 0x%02x", problems_seen, c.cats); + CHECK(read_logs("[logs]\njust words\n", 0u, &c) == 1 && last_line == 2, + "no '=': %d problems, line %d", problems_seen, last_line); + snprintf(f, sizeof(f), "[logs\nmidi = %s\n", not_midi); + CHECK(read_logs(f, 0u, &c) == 2 && (c.cats & SP1_LOG_MIDI) == (d.cats & SP1_LOG_MIDI), + "no ']': %d problems, 0x%02x", problems_seen, c.cats); + + /* A line over the limit is one problem, and the line after it is read normally -- + * also when the long line arrives a byte at a time. */ + char longf[600]; + memset(longf, 0, sizeof(longf)); + strcpy(longf, "[logs]\n; "); + memset(longf + strlen(longf), 'x', 300); + strcat(longf, "\nusb = off\n"); + CHECK(read_logs(longf, 1u, &c) == 1 && last_line == 2 && !(c.cats & SP1_LOG_USB), + "long line: %d problems, line %d, 0x%02x", problems_seen, last_line, c.cats); + + /* An empty file and a file of comments: the defaults, no problem. */ + CHECK(read_logs("", 0u, &c) == 0 && c.enabled == d.enabled && c.cats == d.cats, "empty file"); + CHECK(read_logs("; nothing\n# here\n\n", 0u, &c) == 0 && c.cats == d.cats, "comments"); + + char b[48]; + CHECK(strcmp(sp1_logs_describe(SP1_LOG_ALL, b, sizeof(b)), + "performance controls midi usb storage") == 0, "describe all: %s", b); + CHECK(strcmp(sp1_logs_describe(0u, b, sizeof(b)), "none") == 0, "describe none: %s", b); +} + +/* ---------------------------------------------------------------- categories */ + +static void categories(void) +{ + printf("[2] the log's categories\n"); + static const struct { + const char *line; + uint8_t cat; + } T[] = { + { "[+00:01:02.345] CPU eng=60.1/70.2\n", SP1_LOG_PERFORMANCE }, + { "[+00:01:02.345] MISS/ms eng=3\n", SP1_LOG_PERFORMANCE }, + { "[+00:01:02.345] THREADS main=1.0\n", SP1_LOG_PERFORMANCE }, + { "[+00:01:02.345] ENGINE 3: 2-op FM\n", SP1_LOG_CONTROLS }, + { "[+00:01:02.345] DEJA VU t on\n", SP1_LOG_CONTROLS }, + { "[+00:01:02.345] MIDI port enabled\n", SP1_LOG_MIDI }, + { "[+00:01:02.345] CLOCK run\n", SP1_LOG_MIDI }, + { "[+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 }, + /* Always written. */ + { "[+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 }, + { "[+00:01:02.345] [ON] batt raw=1234\n", 0u }, + { "[+00:01:02.345] resetreas 0x00000001\n", 0u }, + { "[+00:01:02.345] Singles: 209\n", 0u }, + { "[+00:01:02.345] USBx\n", 0u }, + { "=== RESET (resetreas 0x2) ===\n", 0u }, + { "AUD start rc=0\n", SP1_LOG_PERFORMANCE }, /* no stamp */ + { "", 0u }, + }; + for (size_t i = 0u; i < sizeof(T) / sizeof(T[0]); i++) { + const uint8_t c = sp1_log_category(T[i].line, strlen(T[i].line)); + CHECK(c == T[i].cat, "\"%.40s\": 0x%02x, expected 0x%02x", T[i].line, c, T[i].cat); + } +} + +/* ---------------------------------------------------------------- the ring */ + +#define RSZ 64u +static struct sp1_logring R; +static char data[RSZ]; +static char got[4096]; +static size_t got_n; +static uint32_t lost; + +static void puts_r(const char *s) +{ + for (; *s; s++) { + sp1_logring_put(&R, data, *s); + } +} + +/* Everything the file can take now, into got[] (appended). max = the piece size. */ +static void drain(size_t max) +{ + char out[256]; + size_t n; + while ((n = sp1_logring_take(&R, data, out, max, &lost)) > 0u) { + memcpy(got + got_n, out, n); + got_n += n; + got[got_n] = '\0'; + } +} + +/* ...only what the last ON still owes its own file (sp1_logring_take_before_standby). */ +static void drain_old(size_t max) +{ + char out[256]; + size_t n; + while ((n = sp1_logring_take_before_standby(&R, data, out, max, &lost)) > 0u) { + memcpy(got + got_n, out, n); + got_n += n; + got[got_n] = '\0'; + } +} + +static void reset_ring(void) +{ + sp1_logring_init(&R, RSZ); + got_n = 0u; + got[0] = '\0'; + lost = 0u; +} + +static void ring(void) +{ + printf("[3] the log file's cursor\n"); + + /* Whole lines only; a partial line waits for its end. */ + reset_ring(); + puts_r("one\ntwo\nthr"); + drain(32u); + CHECK(strcmp(got, "one\ntwo\n") == 0 && lost == 0u, "lines: \"%s\" lost %u", got, lost); + puts_r("ee\n"); + drain(32u); + CHECK(strcmp(got, "one\ntwo\nthree\n") == 0, "partial completed: \"%s\"", got); + + /* A line longer than a piece comes in pieces. */ + reset_ring(); + puts_r("abcdefghijklmnop\n"); + drain(6u); + CHECK(strcmp(got, "abcdefghijklmnop\n") == 0, "pieces: \"%s\"", got); + + /* STANDBY (Adara): pause..resume is skipped; lines before and after are kept. */ + reset_ring(); + puts_r("boot\n"); + sp1_logring_pause(&R); + puts_r("[STANDBY] a\n[STANDBY] b\n"); + drain(32u); /* while still in STANDBY: only what came before */ + CHECK(strcmp(got, "boot\n") == 0, "paused: \"%s\"", got); + sp1_logring_resume(&R); + puts_r("on\n"); + drain(32u); + CHECK(strcmp(got, "boot\non\n") == 0 && lost == 0u, "gap: \"%s\" lost %u", got, lost); + + /* A second STANDBY before the file caught up merges with the first (documented). */ + reset_ring(); + puts_r("a\n"); + sp1_logring_pause(&R); + puts_r("s1\n"); + sp1_logring_resume(&R); + puts_r("b\n"); + sp1_logring_pause(&R); + puts_r("s2\n"); + sp1_logring_resume(&R); + puts_r("c\n"); + drain(32u); + CHECK(strcmp(got, "a\nc\n") == 0, "two gaps: \"%s\"", got); + + /* Overrun: what the ring overwrote is counted, and the file resumes on a whole line. */ + reset_ring(); + for (int i = 0; i < 20; i++) { + char l[16]; + snprintf(l, sizeof(l), "line %02d\n", i); /* 8 bytes each: 160 > 64 */ + puts_r(l); + } + drain(32u); + CHECK(lost == 160u - 64u + 0u || lost == 160u - 64u + 8u, + "overrun: lost %u (expected 96, or 104 with the cut line)", lost); + CHECK(got_n > 0u && got[got_n - 1u] == '\n' && strncmp(got, "line ", 5) == 0, + "overrun: resumes on a line: \"%s\"", got); + CHECK(lost + got_n == 160u, "overrun: lost + taken = %u, expected 160", lost + (unsigned)got_n); + + /* Overrun inside a STANDBY gap: the gap's bytes are not a loss. */ + reset_ring(); + puts_r("before\n"); /* 7 */ + drain(32u); + sp1_logring_pause(&R); + for (int i = 0; i < 30; i++) { + puts_r("standby\n"); /* 240 bytes of STANDBY */ + } + sp1_logring_resume(&R); + puts_r("after\n"); + drain(32u); + CHECK(strcmp(got, "before\nafter\n") == 0 && lost == 0u, + "gap overwritten: \"%s\" lost %u", got, lost); + + /* Logging off this ON: nothing so far is owed to the file. */ + reset_ring(); + puts_r("old\n"); + sp1_logring_skip(&R); + puts_r("new\n"); + drain(32u); + CHECK(strcmp(got, "new\n") == 0, "skip: \"%s\"", got); + + /* An ON with logging OFF, then STANDBY, then an ON with logging on (Adara's test, + * 0007.LOGS): none of the logging-off ON's lines reach the file -- not those before the + * ON job's decision, not those after it. */ + reset_ring(); + puts_r("boot\n"); + sp1_logring_pause(&R); /* plugged-in boot: STANDBY */ + puts_r("[STANDBY] a\n"); + sp1_logring_resume(&R); /* ON #1 */ + puts_r("CNFG logging off\n"); + sp1_logring_skip(&R); /* ...the ON job decides: off */ + puts_r("ON1 played\nPRST save\n"); + sp1_logring_pause(&R); /* STANDBY */ + puts_r("[STANDBY] b\n"); + sp1_logring_resume(&R); /* ON #2 */ + puts_r("CNFG logging on\n"); + sp1_logring_keep(&R); /* ...the ON job decides: on */ + puts_r("ON2 played\n"); + drain(32u); + CHECK(strcmp(got, "CNFG logging on\nON2 played\n") == 0 && lost == 0u, + "logging off then on: \"%s\" lost %u", got, lost); + + /* Every ON a new file (Adara, 2026-10-16): what the last ON printed after its last flush + * goes to ITS file first, then the new file gets this ON only -- STANDBY in neither. */ + reset_ring(); + puts_r("ON1 played\n"); + drain(32u); /* ON1's flushes */ + puts_r("LOG closed\n"); /* after the last one */ + sp1_logring_pause(&R); + puts_r("[STANDBY] a\n"); + sp1_logring_resume(&R); + puts_r("ON2\n"); + got_n = 0u; + got[0] = '\0'; + drain_old(32u); + CHECK(strcmp(got, "LOG closed\n") == 0, "catch-up: the old file gets \"%s\"", got); + drain_old(32u); + CHECK(strcmp(got, "LOG closed\n") == 0, "catch-up: stops at STANDBY: \"%s\"", got); + got_n = 0u; + got[0] = '\0'; + drain(32u); + CHECK(strcmp(got, "ON2\n") == 0 && lost == 0u, "catch-up: the new file gets \"%s\" lost %u", + got, lost); + + /* A STANDBY that printed nothing (no gap to jump): the boundary still holds. */ + reset_ring(); + puts_r("tail\n"); + sp1_logring_pause(&R); + sp1_logring_resume(&R); + puts_r("new\n"); + drain_old(32u); + CHECK(strcmp(got, "tail\n") == 0, "empty STANDBY, old: \"%s\"", got); + got_n = 0u; + got[0] = '\0'; + drain(32u); + CHECK(strcmp(got, "new\n") == 0, "empty STANDBY, new: \"%s\"", got); + + /* Nothing owed (the last flush took everything): the old file gets nothing. */ + reset_ring(); + puts_r("all flushed\n"); + drain(32u); + sp1_logring_pause(&R); + puts_r("[STANDBY]\n"); + sp1_logring_resume(&R); + puts_r("new\n"); + got_n = 0u; + got[0] = '\0'; + drain_old(32u); + CHECK(got_n == 0u, "nothing owed: \"%s\"", got); + drain(32u); + CHECK(strcmp(got, "new\n") == 0, "nothing owed, new: \"%s\"", got); + + /* A line STANDBY cut (the backstop mid-print) ends the old file as it is; still in + * STANDBY, nothing is taken. */ + reset_ring(); + puts_r("PWR 29 s\nhal"); + sp1_logring_pause(&R); + drain_old(32u); + CHECK(strcmp(got, "PWR 29 s\nhal") == 0, "cut line while paused: \"%s\"", got); + puts_r("[STANDBY]\n"); + sp1_logring_resume(&R); + puts_r("new\n"); + drain_old(32u); + CHECK(strcmp(got, "PWR 29 s\nhal") == 0, "cut line: nothing more: \"%s\"", got); + + /* The old lines partly overwritten: counted, and the rest still goes to the old file. */ + reset_ring(); + for (int i = 0; i < 12; i++) { + char l[16]; + snprintf(l, sizeof(l), "old %02d\n", i); /* 7 bytes each: 84 > 64 */ + puts_r(l); + } + sp1_logring_pause(&R); + sp1_logring_resume(&R); + drain_old(32u); + CHECK(lost > 0u && got_n > 0u && strncmp(got, "old ", 4) == 0 && + strcmp(got + got_n - 7u, "old 11\n") == 0 && lost + got_n == 84u, + "old overrun: lost %u, got \"%s\"", lost, got); + + /* After a reset: a cursor ahead of the writer is pulled back; a bad header fails. */ + reset_ring(); + puts_r("kept\n"); + R.frd = R.total + 100u; + CHECK(sp1_logring_valid(&R, RSZ), "valid: a sane ring"); + drain(32u); + CHECK(strcmp(got, "kept\n") == 0, "valid: cursor clamped: \"%s\"", got); + R.head = RSZ; + CHECK(!sp1_logring_valid(&R, RSZ), "valid: head out of range"); + sp1_logring_init(&R, RSZ); + CHECK(!sp1_logring_valid(&R, RSZ * 2u), "valid: another size"); + + /* The 32-bit wrap of the position counter is harmless. */ + reset_ring(); + R.total = R.frd = 0xFFFFFFF0u; + R.gap_from = R.gap_to = R.total; + puts_r("wrap one\nwrap two\n"); + drain(32u); + CHECK(strcmp(got, "wrap one\nwrap two\n") == 0 && lost == 0u, "wrap: \"%s\" lost %u", got, + lost); +} + +/* ---------------------------------------------------------------- engines.cnfg */ + +static uint8_t estack[SP1_CNFG_SLOTS]; +static int efilled; + +static int read_engines(const char *text, size_t chunk) +{ + struct sp1_engines_reader r; + problems_seen = 0; + last_line = 0; + last_what[0] = '\0'; + sp1_engines_begin(&r, 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_engines_feed(&r, text + i, (i + chunk <= n) ? chunk : n - i); + } + const int bad = sp1_engines_end(&r, estack, &efilled); + CHECK(bad == problems_seen, "engines: counted %d, reported %d", bad, problems_seen); + return bad; +} + +static bool is_default(void) +{ + static const uint8_t def[SP1_CNFG_SLOTS] = SP1_ENGINE_DEFAULT_STACK; + return memcmp(estack, def, sizeof(def)) == 0; +} + +static int idx(const char *name) +{ + return sp1_engine_index(name, strlen(name)); +} + +static void engines(void) +{ + printf("[4] engines.cnfg: names and the stack\n"); + + /* Names: letters and digits, case ignored -- spaces, hyphens and / + do not matter. */ + static const struct { + const char *name; + const char *as; + } SAME[] = { + { "virtual-analog", "virtual analog" }, { "VIRTUAL ANALOG", "virtual analog" }, + { "grain-formant", "grain / formant" }, { "grain-/-formant", "grain / formant" }, + { "VA-VCF", "VA + VCF" }, { "va + vcf", "VA + VCF" }, + { "2-op-FM", "2-op FM" }, { "6-op-fm-c", "6-op FM C" }, + { "hi hat", "hi-hat" }, { "string-machine", "string machine" }, + { "stringmachine", "string machine" }, + }; + for (size_t i = 0u; i < sizeof(SAME) / sizeof(SAME[0]); i++) { + CHECK(idx(SAME[i].name) >= 0 && idx(SAME[i].name) == idx(SAME[i].as), + "name \"%s\" -> %d, \"%s\" -> %d", SAME[i].name, idx(SAME[i].name), SAME[i].as, + idx(SAME[i].as)); + } + CHECK(idx("string") != idx("string machine"), "string is not string machine"); + CHECK(idx("6-op FM") < 0 && idx("") < 0 && idx("moog") < 0 && idx("-") < 0, + "partial / empty / unknown names are no engine"); + + /* The template written when the file is missing: no problem, exactly the built-in stack, 16 engines. */ + const size_t chunks[] = { 0u, 1u, 128u }; + for (size_t k = 0u; k < sizeof(chunks) / sizeof(chunks[0]); k++) { + CHECK(read_engines(SP1_ENGINES_TEMPLATE, chunks[k]) == 0 && is_default() && + efilled == 16, "template, chunk %u: %d problems (line %d: %s), %d engines", + (unsigned)chunks[k], problems_seen, last_line, last_what, efilled); + } + + /* A user's stack: the file is the WHOLE stack; any spelling of a name. */ + CHECK(read_engines("; Format: ini\r\n[ENGINES]\r\n1 = chords ; ●○○○\r\n3 = Grain-Formant\r\n" + "7 =\r\n8 = none\r\n24 = VA-VCF\r\n", 0u) == 0 && efilled == 3 && + estack[0] == idx("chords") && estack[2] == idx("grain / formant") && + estack[23] == idx("VA + VCF") && estack[1] == SP1_CNFG_EMPTY && + estack[6] == SP1_CNFG_EMPTY && estack[7] == SP1_CNFG_EMPTY, + "user stack: %d problems (line %d: %s), %d engines", problems_seen, last_line, + last_what, efilled); + + /* Anything wrong: the WHOLE file is set aside for the built-in stack, every problem + * reported on its line. */ + static const struct { + const char *text; + int problems; + int line; + } BAD[] = { + { "[engines]\n1 = chords\n2 = moog\n", 1, 3 }, /* not an engine */ + { "[engines]\n1 = chords\n5 = Chords\n", 1, 3 }, /* engine twice */ + { "[engines]\n25 = chords\n", 1, 2 }, /* no slot 25 */ + { "[engines]\n0 = chords\n", 1, 2 }, /* no slot 0 */ + { "[engines]\nx = chords\n", 1, 2 }, /* not a slot */ + { "[engines]\n1 = chords\n1 = speech\n", 1, 3 }, /* slot twice */ + { "[engine]\n1 = chords\n", 1, 2 }, /* not [engines] */ + { "1 = chords\n[engines]\n2 = speech\n", 1, 1 }, /* outside [engines] */ + { "[engines]\n1 =\n2 = none\n", 1, 3 }, /* no engine at all */ + { "", 1, 0 }, /* an empty file */ + { "[engines]\n1 = chords\njust words\n", 1, 3 }, /* not a setting */ + }; + for (size_t i = 0u; i < sizeof(BAD) / sizeof(BAD[0]); i++) { + const int bad = read_engines(BAD[i].text, i % 2 ? 1u : 0u); + CHECK(bad == BAD[i].problems && last_line == BAD[i].line && is_default() && + efilled == 16, "bad file %u: %d problems (want %d), line %d (want %d), %s", + (unsigned)i, bad, BAD[i].problems, last_line, BAD[i].line, + is_default() ? "default stack" : "NOT the default stack"); + } +} + +/* ---------------------------------------------------------------- audio.cnfg */ + +static struct sp1_audio_cfg acfg; + +static int read_audio(const char *text, size_t chunk) +{ + struct sp1_audio_reader r; + problems_seen = 0; + last_line = 0; + sp1_audio_reader_begin(&r, &acfg, 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_audio_reader_feed(&r, text + i, (i + chunk <= n) ? chunk : n - i); + } + const int bad = sp1_audio_reader_end(&r); + CHECK(bad == problems_seen, "audio: counted %d, reported %d", bad, problems_seen); + return bad; +} + +static void audio(void) +{ + printf("[5] audio.cnfg\n"); + struct sp1_audio_cfg d; + sp1_audio_cfg_defaults(&d); + CHECK(d.parked == SP1_AUDIO_USB_LEVEL_PARKED && d.parked_db == SP1_AUDIO_USB_PARKED_DB && + d.parked_step == SP1_AUDIO_USB_PARKED_STEP && d.speaker == SP1_AUDIO_USB_SPEAKER, + "audio defaults differ from the generated ones"); + const size_t chunks[] = { 0u, 1u, 128u }; + for (size_t k = 0u; k < sizeof(chunks) / sizeof(chunks[0]); k++) { + CHECK(read_audio(SP1_AUDIO_TEMPLATE, chunks[k]) == 0 && + memcmp(&acfg, &d, sizeof(d)) == 0, + "template, chunk %u: %d problems (line %d: %s)", (unsigned)chunks[k], + problems_seen, last_line, last_what); + } + CHECK(read_audio("[usb]\nlevel = VOL\nparked_level = -9 dB\nspeaker = on\n", 0u) == 0 && + acfg.parked == 0u && acfg.parked_db == -9 && acfg.parked_step == 3u && + acfg.speaker == 1u, "overrides: %d problems, %d/%d/%u/%u", problems_seen, + acfg.parked, acfg.parked_db, acfg.parked_step, acfg.speaker); + CHECK(read_audio("[usb]\nparked_level = 0\n", 0u) == 0 && acfg.parked_step == 0u, + "0 dB is a step"); + CHECK(read_audio("[usb]\nparked_level = -30db\n", 0u) == 0 && acfg.parked_step == 10u, + "-30 dB is a step"); + /* Not steps: each keeps the default, one problem each. */ + static const char *const BADLVL[] = { "-7", "-33", "6", "+3", "-6 dBFS", "loud", "" }; + for (size_t i = 0u; i < sizeof(BADLVL) / sizeof(BADLVL[0]); i++) { + char t[64]; + snprintf(t, sizeof(t), "[usb]\nparked_level = %s\n", BADLVL[i]); + CHECK(read_audio(t, 0u) == 1 && acfg.parked_db == d.parked_db, + "parked_level = %s: %d problems, %d dB", BADLVL[i], problems_seen, + acfg.parked_db); + } + CHECK(read_audio("[usb]\nspeaker = maybe\nspeaker = on\nvolume = 3\n[out]\nx = 1\n", 0u) + == 4 && acfg.speaker == d.speaker, + "bad value / twice / unknown key / section: %d problems", problems_seen); +} + +/* ---------------------------------------------------------------- midi.cnfg */ + +static struct sp1_midi_cfg mcfg; +static int mnotes; + +static int read_midi(const char *text, size_t chunk) +{ + struct sp1_midi_reader r; + problems_seen = 0; + last_line = 0; + last_what[0] = '\0'; + sp1_midi_reader_begin(&r, &mcfg, 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_midi_reader_feed(&r, text + i, (i + chunk <= n) ? chunk : n - i); + } + const int bad = sp1_midi_reader_end(&r, &mnotes); + CHECK(bad + mnotes == problems_seen, "midi: counted %d + %d notes, reported %d", bad, + mnotes, problems_seen); + return bad; +} + +/* Field by field (the struct has padding), and the two CC tables agree with each other. */ +static bool midi_same(const struct sp1_midi_cfg *a, const struct sp1_midi_cfg *b) +{ + return a->channel == b->channel && a->priority == b->priority && a->legato == b->legato && + a->portamento == b->portamento && a->bend_range == b->bend_range && + a->sustain_cc == b->sustain_cc && a->smooth_ms == b->smooth_ms && + a->pickup == b->pickup && a->clock == b->clock && + a->clock_lead_ms == b->clock_lead_ms && a->vel_dest == b->vel_dest && + a->at_dest == b->at_dest && a->vel_depth == b->vel_depth && + a->at_depth == b->at_depth && + memcmp(a->dest_cc, b->dest_cc, sizeof(a->dest_cc)) == 0 && + memcmp(a->cc_dest, b->cc_dest, sizeof(a->cc_dest)) == 0; +} + +static bool tables_agree(const struct sp1_midi_cfg *c) +{ + for (int cc = 0; cc < 128; cc++) { + const int d = c->cc_dest[cc]; + if (d >= 0 && c->dest_cc[d] != cc) { + return false; + } + } + for (int d = 0; d < SP1_MIDI_DESTS; d++) { + if (c->dest_cc[d] >= 0 && c->cc_dest[(int)c->dest_cc[d]] != d) { + return false; + } + if (c->dest_cc[d] >= 0 && c->dest_cc[d] == c->sustain_cc) { + return false; + } + } + return true; +} + +static void midi(void) +{ + printf("[6] midi.cnfg\n"); + struct sp1_midi_cfg d; + sp1_midi_cfg_defaults(&d); + CHECK(d.channel == SP1_MIDI_CHANNEL && d.pickup == SP1_MIDI_PICKUP && + d.sustain_cc == SP1_MIDI_SUSTAIN_CC && d.dest_cc[SP1_MIDI_D_TIMBRE] == 3 && + d.vel_dest == SP1_MIDI_VELOCITY_DEST && tables_agree(&d), + "midi defaults differ from the generated ones"); + + /* The template written when the file is missing reads back as exactly the built-in script. */ + const size_t chunks[] = { 0u, 1u, 128u }; + for (size_t k = 0u; k < sizeof(chunks) / sizeof(chunks[0]); k++) { + CHECK(read_midi(SP1_MIDI_TEMPLATE, chunks[k]) == 0 && mnotes == 0 && + midi_same(&mcfg, &d), "template, chunk %u: %d problems (line %d: %s)", + (unsigned)chunks[k], problems_seen, last_line, last_what); + } + + /* [midi] values, every form. */ + CHECK(read_midi("[midi]\nchannel = 3\nnote_priority = LOW\nlegato = auto\n" + "portamento = t10\nbend_range = 12\ncc_smoothing = 0\npickup = takeover\n" + "clock = off\nclock_lead = 25\n", 0u) == 0 && + mcfg.channel == 2 && mcfg.priority == 1u && mcfg.legato == 1u && + mcfg.portamento == 10u && mcfg.bend_range == 12u && mcfg.smooth_ms == 0u && + mcfg.pickup == SP1_MIDI_PICKUP_TAKEOVER && mcfg.clock == 0u && + mcfg.clock_lead_ms == 25, "[midi] overrides: %d problems (line %d: %s)", + problems_seen, last_line, last_what); + CHECK(read_midi("[midi]\nchannel = omni\nportamento = r0\nclock_lead = notes\n", 0u) == 0 && + mcfg.channel == SP1_MIDI_OMNI && mcfg.portamento == 51u && mcfg.clock_lead_ms == -2, + "omni / r0 / notes"); + static const char *const BADMIDI[] = { + "channel = 0", "channel = 17", "note_priority = first", "legato = maybe", + "portamento = t0", "portamento = t51", "portamento = r51", "bend_range = 25", + "cc_smoothing = 201", "pickup = both", "clock = yes", "clock_lead = 201", + }; + for (size_t i = 0u; i < sizeof(BADMIDI) / sizeof(BADMIDI[0]); i++) { + char t[64]; + snprintf(t, sizeof(t), "[midi]\n%s\n", BADMIDI[i]); + CHECK(read_midi(t, 0u) == 1 && midi_same(&mcfg, &d), "\"%s\": %d problems, %s", + BADMIDI[i], problems_seen, midi_same(&mcfg, &d) ? "default kept" : "CHANGED"); + } + + /* THE CC RULE (Adara, #52). 1: your line TAKES a default's CC -- MORPH's CC 9 to TIMBRE: + * MORPH has none, a note (not a problem); TIMBRE's own CC 3 is free. */ + CHECK(read_midi("[plaits]\ntimbre = cc 9\n", 0u) == 0 && mnotes == 1 && + mcfg.dest_cc[SP1_MIDI_D_TIMBRE] == 9 && mcfg.dest_cc[SP1_MIDI_D_MORPH] == -1 && + mcfg.cc_dest[9] == SP1_MIDI_D_TIMBRE && mcfg.cc_dest[3] == -1 && tables_agree(&mcfg), + "user takes a default's CC: %d problems, %d notes, timbre %d morph %d", + problems_seen - mnotes, mnotes, mcfg.dest_cc[SP1_MIDI_D_TIMBRE], + mcfg.dest_cc[SP1_MIDI_D_MORPH]); + /* 2: two of YOUR lines on one CC: the first keeps it, the later gets none (a problem). */ + CHECK(read_midi("[plaits]\ntimbre = cc 70\nmorph = cc 70\n", 0u) == 1 && last_line == 3 && + mcfg.dest_cc[SP1_MIDI_D_TIMBRE] == 70 && mcfg.dest_cc[SP1_MIDI_D_MORPH] == -1 && + tables_agree(&mcfg), "two user lines, one CC: %d problems, line %d, morph %d", + problems_seen, last_line, mcfg.dest_cc[SP1_MIDI_D_MORPH]); + /* ...across sections and against the sustain pedal, which is a line like any other. */ + CHECK(read_midi("[midi]\nsustain = cc 70\n[marbles]\nrate = cc 70\n", 0u) == 1 && + mcfg.sustain_cc == 70 && mcfg.dest_cc[SP1_MIDI_D_RATE] == -1 && tables_agree(&mcfg), + "sustain first, rate later: sustain %d rate %d", mcfg.sustain_cc, + mcfg.dest_cc[SP1_MIDI_D_RATE]); + /* 3: a user line taking the DEFAULT sustain CC 64 turns the pedal off (a note). */ + CHECK(read_midi("[plaits]\nlevel = cc 64\n", 0u) == 0 && mnotes == 1 && + mcfg.sustain_cc == -1 && mcfg.dest_cc[SP1_MIDI_D_LEVEL] == 64 && tables_agree(&mcfg), + "user takes the pedal's CC: sustain %d", mcfg.sustain_cc); + /* 4: `none` frees a CC, which a default then keeps nothing of. */ + CHECK(read_midi("[plaits]\ntimbre = none\nmorph = cc 3\n", 0u) == 0 && mnotes == 0 && + mcfg.dest_cc[SP1_MIDI_D_TIMBRE] == -1 && mcfg.dest_cc[SP1_MIDI_D_MORPH] == 3 && + tables_agree(&mcfg), "none then reuse: %d notes", mnotes); + /* Reserved CCs, fine halves, nonsense: the default is kept. */ + static const char *const BADCC[] = { "cc 6", "cc 0", "cc 101", "cc 120", "cc 40", "cc 128", + "ccc", "7", "cc -1" }; + for (size_t i = 0u; i < sizeof(BADCC) / sizeof(BADCC[0]); i++) { + char t[64]; + snprintf(t, sizeof(t), "[plaits]\ntimbre = %s\n", BADCC[i]); + CHECK(read_midi(t, 0u) == 1 && mcfg.dest_cc[SP1_MIDI_D_TIMBRE] == 3, + "timbre = %s: %d problems, cc %d", BADCC[i], problems_seen, + mcfg.dest_cc[SP1_MIDI_D_TIMBRE]); + } + /* A parameter in the wrong section, an unknown one, the same key twice. */ + CHECK(read_midi("[marbles]\ntimbre = cc 70\n", 0u) == 1 && midi_same(&mcfg, &d), + "timbre under [marbles]"); + CHECK(read_midi("[plaits]\ncutoff = cc 70\n", 0u) == 1, "unknown parameter"); + CHECK(read_midi("[plaits]\ntimbre = cc 70\ntimbre = cc 71\n", 0u) == 1 && + mcfg.dest_cc[SP1_MIDI_D_TIMBRE] == 70, "the same key twice: the first wins"); + + /* [bind]. */ + CHECK(read_midi("[bind]\nvelocity = none\naftertouch = MORPH -50%\n", 0u) == 0 && + mcfg.vel_dest == -1 && mcfg.at_dest == SP1_MIDI_D_MORPH && mcfg.at_depth == -0.5f, + "bind: velocity %d aftertouch %d %.2f", mcfg.vel_dest, mcfg.at_dest, + (double)mcfg.at_depth); + CHECK(read_midi("[bind]\naftertouch = rate 100%\n", 0u) == 0 && + mcfg.at_dest == SP1_MIDI_D_RATE && mcfg.at_depth == 1.0f, "bind to a Marbles parameter"); + static const char *const BADBIND[] = { "velocity = cutoff", "velocity = timbre 150%", + "velocity = timbre 50", "breath = timbre" }; + for (size_t i = 0u; i < sizeof(BADBIND) / sizeof(BADBIND[0]); i++) { + char t[64]; + snprintf(t, sizeof(t), "[bind]\n%s\n", BADBIND[i]); + CHECK(read_midi(t, 0u) == 1 && mcfg.vel_dest == d.vel_dest, "\"%s\": %d problems", + BADBIND[i], problems_seen); + } +} + +int main(void) +{ + reader(); + categories(); + ring(); + engines(); + audio(); + midi(); + 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 3b360dc..53e413c 100644 --- a/tools/host-tests/hostbuild.sh +++ b/tools/host-tests/hostbuild.sh @@ -23,23 +23,34 @@ OBJ=$SP/hostobj$SP1_PLAITS_BLOCK python3 "$HERE/mkovr.py" "$OVR" >/dev/null mkdir -p "$GEN" "$OBJ" -python3 "$ROOT/tools/gen_engines.py" "$ROOT/config/engines.csv" "$GEN/sp1_engines_gen.h" >/dev/null +python3 "$ROOT/tools/gen_engines.py" "$ROOT/config/engines.cnfg" "$GEN/sp1_engines_gen.h" >/dev/null # M6 (#50): the PRST field table -- also where a format change without a version bump fails. 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 # 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 # per other pickup (below); miditest_alt.cc uses a second script of its own. # $1 = pickup, $2 = the ini to write. Fails if the script has no `pickup` line to replace. pickup_ini() { - sed -E 's/^pickup[[:space:]]*=.*/pickup = '"$1"'/' "$ROOT/config/midi.ini" > "$2" - grep -Eq "^pickup = $1\$" "$2" || { echo "hostbuild: no pickup line in config/midi.ini" >&2; exit 1; } + sed -E 's/^pickup[[:space:]]*=.*/pickup = '"$1"'/' "$ROOT/config/midi.cnfg" > "$2" + grep -Eq "^pickup = $1\$" "$2" || { echo "hostbuild: no pickup line in config/midi.cnfg" >&2; exit 1; } } pickup_ini sum "$GEN/midi-sum.ini" -# ...and its legato forced to `off`, Yarns' default, whatever the shipped script is set to for -# a hardware test: miditest.cc checks legato off; miditest_alt.cc checks legato on. -sed -i -E 's/^legato[[:space:]]*=.*/legato = off/' "$GEN/midi-sum.ini" -grep -Eq '^legato = off$' "$GEN/midi-sum.ini" || { echo "hostbuild: no legato line in config/midi.ini" >&2; exit 1; } +# ...and four more lines forced, whatever the shipped script says: miditest.cc checks exact +# pitch steps (legato off, portamento 0), the channel filter (channel 1) and the velocity maths +# (velocity = level). miditest_alt.cc checks legato on, a glide, omni and the bindings, and +# miditest_pickup.cc the shipped settings themselves (legato auto, portamento, omni, velocity). +force_line() { # $1 = key, $2 = value + sed -i -E "s/^[[:space:]]*$1[[:space:]]*=.*/$1 = $2/" "$GEN/midi-sum.ini" + grep -Eq "^$1 = $2\$" "$GEN/midi-sum.ini" || { echo "hostbuild: no $1 line in config/midi.cnfg" >&2; exit 1; } +} +force_line legato off +force_line portamento 0 +force_line channel 1 +force_line velocity level python3 "$ROOT/tools/gen_midi.py" "$GEN/midi-sum.ini" "$GEN/sp1_midi_gen.h" >/dev/null INC="-I$OVR -I$SRC/plaits_ovr -I$SRC/plaits_shim -I$ER -I$SRC -I$GEN" @@ -116,6 +127,9 @@ for t in "$@"; do gcc -std=c99 -O2 -Wall -fno-tree-loop-distribute-patterns -fno-unroll-loops \ -include "$SRC/sp1_uac_tuning.h" $EXTRA_UAC_FLAGS -I"$UAC" \ "$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" ;; *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" ;; diff --git a/tools/host-tests/midi-alt.ini b/tools/host-tests/midi-alt.ini index 7d539d9..403cd79 100644 --- a/tools/host-tests/midi-alt.ini +++ b/tools/host-tests/midi-alt.ini @@ -1,5 +1,5 @@ -; The second MIDI script miditest_alt.cc runs against: everything config/midi.ini leaves at -; its default, changed. Not a template for users -- config/midi.ini is. +; The second MIDI script miditest_alt.cc runs against: everything config/midi.cnfg leaves at +; its default, changed. Not a template for users -- config/midi.cnfg is. [midi] channel = omni note_priority = last diff --git a/tools/host-tests/miditest.cc b/tools/host-tests/miditest.cc index 50132bd..cf9de23 100644 --- a/tools/host-tests/miditest.cc +++ b/tools/host-tests/miditest.cc @@ -1,5 +1,7 @@ -// wakes-sp1 M5a: host checks of MIDI in, against the shipped script (config/midi.ini) with -// its pickup set to SUM (hostbuild.sh): this suite checks the offset maths. +// wakes-sp1 M5a: host checks of MIDI in, against the shipped script (config/midi.cnfg) with +// its pickup set to SUM (hostbuild.sh): this suite checks the offset maths. hostbuild.sh also +// sets legato off, portamento 0, channel 1 and velocity = level, whatever the shipped script +// says, for the exact pitch steps, the channel filter and the velocity maths below. // Drives the real sp1_midi core directly, then through sp1_synth / both UIs. // miditest_alt.cc covers the settings this script leaves at their defaults; // miditest_pickup.cc the shipped script under pickup shared and takeover. @@ -14,6 +16,7 @@ extern "C" { #include "sp1_plaits_ui.h" #include "sp1_marbles_ui.h" #include "sp1_engines_gen.h" +#include "sp1_cnfg.h" } static int fails; @@ -97,7 +100,7 @@ int main() { block(); CHECK(!any_trig(), "TRIG struck twice for one note"); - // ---- Β§3 Yarns mono, legato off (the script's default): last-note priority, every new + // ---- Β§3 Yarns mono, legato off (as hostbuild.sh sets it): last-note priority, every new // note strikes, and so does falling back to a key still held (C4) ---- printf("Β§3 last-note priority, legato off\n"); on(67); @@ -178,10 +181,10 @@ int main() { CHECK(last().gate == 0.0f, "pedal up: the held note should end"); reset(); - // ---- Β§4b velocity -> LEVEL, the shipped script's [bind] ---- + // ---- Β§4b velocity -> LEVEL (hostbuild.sh sets it; the shipped script has none) ---- printf("Β§4b velocity opens LEVEL\n"); static_assert(SP1_MIDI_VELOCITY_DEST == SP1_MIDI_D_LEVEL, - "the shipped script: velocity = level"); + "hostbuild.sh builds this suite with velocity = level"); on(60, 64); block(); CHECK(fabsf(last().gate - 64.0f / 127.0f) < 1e-4f, "velocity 64 opens LEVEL to 64/127, %.3f", @@ -705,6 +708,49 @@ int main() { CHECK(rt.gtlt == 0.0f, "GTLT CC 64 should be back on the detent, got %.4f", rt.gtlt); } + // ---- the script from the drive, at ON entry (#52): sp1_midi_set_config ---- + // The same core, a different script without a rebuild: channel 2, TIMBRE on CC 70 instead + // of CC 3, velocity unbound. Then the built-in script again. + printf("Β§21 the script changed at ON entry (midi.cnfg on the drive)\n"); + { + const struct sp1_midi_cfg builtin = *sp1_midi_config(); + struct sp1_midi_cfg c = builtin; + c.channel = 1; // MIDI channel 2 + c.cc_dest[3] = -1; + c.dest_cc[SP1_MIDI_D_TIMBRE] = 70; + c.cc_dest[70] = SP1_MIDI_D_TIMBRE; + c.vel_dest = -1; + sp1_midi_set_config(&c); + sp1_midi_on_enter(); + reset(); + centre = 0x2; + on(60); // channel 1: not ours any more + block(); + CHECK(!any_trig(), "a note on channel 1 struck with the script on channel 2"); + send(0x91, 60, 127); // channel 2 + block(); + CHECK(any_trig(), "a note on channel 2 did not strike"); + send(0x81, 60, 0); + send(0xB1, 3, 127); // CC 3: nothing now + for (int i = 0; i < 100; ++i) block(); + CHECK(fabsf(moff[SP1_MIDI_D_TIMBRE]) < 1e-4f, "CC 3 still moves TIMBRE: %.4f", + moff[SP1_MIDI_D_TIMBRE]); + send(0xB1, 70, 127); // CC 70: TIMBRE, centred + for (int i = 0; i < 100; ++i) block(); + CHECK(fabsf(moff[SP1_MIDI_D_TIMBRE] - 0.5f) < 1e-3f, "CC 70 -> TIMBRE +1/2: %.4f", + moff[SP1_MIDI_D_TIMBRE]); + send(0xB1, 70, 64); + for (int i = 0; i < 100; ++i) block(); + sp1_midi_set_config(&builtin); + sp1_midi_on_enter(); + reset(); + on(60); + block(); + CHECK(any_trig(), "the built-in script (channel 1) is not back"); + off(60); + reset(); + } + printf("\n%s (%d failure%s)\n", fails ? "FAILED" : "all checks passed", fails, fails == 1 ? "" : "s"); return fails ? 1 : 0; diff --git a/tools/host-tests/miditest_pickup.cc b/tools/host-tests/miditest_pickup.cc index fe31234..350aced 100644 --- a/tools/host-tests/miditest_pickup.cc +++ b/tools/host-tests/miditest_pickup.cc @@ -1,7 +1,7 @@ // wakes-sp1 M5a round 4: host checks of the MIDI script's `pickup` = shared and takeover // (Adara), against the shipped script with only that line changed. hostbuild.sh builds this // file twice: miditest_pickup_shared and miditest_pickup_takeover. (Pickup sum is the offset -// maths, miditest.cc.) +// maths, miditest.cc.) Both end with Β§S, the shipped script's other defaults as they are. // // Drives the real MIDI core, both UIs and their pickup the way main.c's control loop does: // audio block, UI tick, sp1_midi_main_tick, sp1_pui_midi / sp1_mui_midi, then the params. @@ -80,6 +80,109 @@ static void start() { run(60); } +// ---- the shipped defaults (Adara, 2026-10-16): omni, legato auto, portamento t9, no velocity. +// miditest.cc builds with channel 1, legato off, portamento 0 and velocity = level for its own +// maths; these are the settings a Wakes ships with, checked as they are. Change the defaults in +// config/midi.cnfg and the static_assert below says this section needs the same change. +static const uint32_t kSBlocks = 240u / SP1_SYNTH_BLOCK; // Plaits blocks per 5 ms +static sp1_midi_frame sf[kSBlocks]; + +static void note(uint8_t status, uint8_t n, uint8_t v) { + const uint8_t m[3] = { status, n, v }; + sp1_midi_push(m, 3, 0); +} +// One audio block of the MIDI core alone, every Plaits block's frame kept. +static void sblock(float lpg = 1.0f) { + const bool work = sp1_midi_audio_begin(0, kSBlocks, kCentre, moff); + for (uint32_t j = 0; j < kSBlocks; ++j) { + sf[j] = sp1_midi_frame{ false, false, 0.0f, 0.0f }; + if (work) { + sp1_midi_audio_block(j, &sf[j]); + sp1_midi_audio_lpg(lpg, false); + } + } +} +static bool strikes() { + for (uint32_t j = 0; j < kSBlocks; ++j) { if (sf[j].trig) return true; } + return false; +} +static const sp1_midi_frame& slast() { return sf[kSBlocks - 1]; } + +static void shipped() { + static_assert(SP1_MIDI_CHANNEL == SP1_MIDI_OMNI && SP1_MIDI_LEGATO == 1 && + SP1_MIDI_PORTAMENTO == 9 && SP1_MIDI_VELOCITY_DEST == -1 && + SP1_MIDI_AFTERTOUCH_DEST == -1, + "config/midi.cnfg's defaults changed: update this section (and hostbuild.sh)"); + printf("Β§S the shipped defaults: omni, legato auto, portamento t9, velocity none\n"); + sp1_midi_port(false); // whatever the pickup checks left: neutral + sp1_midi_port(true); + for (int i = 0; i < 40; ++i) sblock(0.0f); + + // Omni, and velocity binds nothing: a soft note on channel 11 opens LEVEL fully. + note(0x9A, 64, 20); + sblock(); + CHECK(sf[0].trig, "omni: a note on channel 11 must strike"); + CHECK(slast().gate == 1.0f, "velocity = none: velocity 20 must open LEVEL fully, %.3f", + slast().gate); + CHECK(fabsf(slast().note - 4.0f) < 1e-4f, "the first note jumps (nothing to glide from): " + "%.3f", slast().note); + + // Legato auto, an overlapping note: no strike, and a t9 glide that lands on the note at + // Yarns' time, t(18) = (tmin^.25 + (tmax^.25 - tmin^.25) * 18/127)^4 with 0.75 ms / 6 s. + const float a = powf(3.0f / 4000.0f, 0.25f), b = powf(6.0f, 0.25f); + const float r = a + (b - a) * 18.0f / 127.0f; + const float t9_ms = r * r * r * r * 1000.0f; + const float block_ms = static_cast(SP1_SYNTH_BLOCK) / 48.0f; + note(0x90, 67, 127); + int landed = -1; + bool struck = false; + bool between = false; + for (int k = 0; k < 20 && landed < 0; ++k) { + sblock(); + struck = struck || strikes(); + for (uint32_t j = 0; j < kSBlocks && landed < 0; ++j) { + between = between || (sf[j].note > 4.01f && sf[j].note < 6.99f); + if (fabsf(sf[j].note - 7.0f) < 1e-4f) { + landed = k * static_cast(kSBlocks) + static_cast(j); + } + } + } + CHECK(!struck, "legato auto: an overlapping note must not strike"); + CHECK(between, "portamento t9: the pitch must pass between E4 and G4, not jump"); + const float landed_ms = static_cast(landed + 1) * block_ms; + CHECK(landed >= 0 && fabsf(landed_ms - t9_ms) <= 2.0f * block_ms, + "t9 lands on G4 after %.1f ms (Yarns: %.1f ms)", landed_ms, t9_ms); + + // Back to the key still held: a glide again, still no strike. + note(0x80, 67, 0); + sblock(); + CHECK(!strikes(), "legato auto: falling back to a held key must not strike"); + CHECK(slast().note > 4.01f, "falling back glides, not jumps: %.3f", slast().note); + for (int i = 0; i < 20; ++i) sblock(); + CHECK(fabsf(slast().note - 4.0f) < 1e-4f, "...and lands on E4: %.3f", slast().note); + + // Every key up, then a detached note: it strikes and jumps (no glide in auto). + note(0x80, 64, 0); + for (int i = 0; i < 4; ++i) sblock(0.0f); + note(0x90, 60, 90); + sblock(); + CHECK(sf[0].trig, "legato auto: a detached note strikes"); + CHECK(fabsf(sf[0].note) < 1e-4f, "legato auto: a detached note jumps to C4, %.3f", sf[0].note); + + // The same pitch again before its note-off (a sequencer's long step): tied, one note. + note(0x90, 60, 90); + sblock(); + CHECK(!strikes(), "legato auto: the same pitch again before its note-off is tied"); + note(0x80, 60, 0); + sblock(); + CHECK(slast().gate > 0.0f, "the first note-off must not end the tied note"); + note(0x80, 60, 0); + sblock(); + CHECK(slast().gate == 0.0f, "the last note-off ends it"); + sp1_midi_port(false); + for (int i = 0; i < 4; ++i) sblock(0.0f); +} + int main() { #if SP1_MIDI_PICKUP == SP1_MIDI_PICKUP_SHARED printf("pickup = shared\n"); @@ -242,6 +345,7 @@ int main() { #else #error "miditest_pickup.cc is for pickup = shared or takeover (hostbuild.sh)" #endif + shipped(); printf("\n%s (%d failure%s)\n", fails ? "FAILED" : "all checks passed", fails, fails == 1 ? "" : "s"); diff --git a/tools/host-tests/prsttest.c b/tools/host-tests/prsttest.c index 0f6ee60..b516bd7 100644 --- a/tools/host-tests/prsttest.c +++ b/tools/host-tests/prsttest.c @@ -6,7 +6,7 @@ #include #include "sp1_prst.h" -#include "sp1_engines_gen.h" /* which engines config/engines.csv lists */ +#include "sp1_engines_gen.h" /* which engines config/engines.cnfg lists */ /* ---- stubs for the parts that live in the audio thread (as uitest.c) ---- */ uint8_t sp1_marbles_last_gates(void) { return 0u; } @@ -200,7 +200,7 @@ int main(void) sp1_mui_get(&a.marbles); CHECK(diff(&a, &d, "rip vs sp1_prst_rip") == 0, "the rip and the PRST defaults differ"); /* docs/DEFAULTS.md, spot checks: slot 1 = virtual analog, TIMBRE and HARMONICS bipolar */ - CHECK(d.plaits.slot == 0 && strcmp(sp1_pui_slot_name(0), "virtual analog") == 0, + CHECK(d.plaits.slot == 0 && strcmp(sp1_pui_slot_name(0), "virtual-analog") == 0, "slot 1 is not virtual analog"); CHECK(d.plaits.v[SP1_PUI_BASE][0] == 0.5f && d.plaits.v[SP1_PUI_BASE][1] == 0.5f && d.plaits.v[SP1_PUI_BASE][2] == 0.0f && d.plaits.v[SP1_PUI_BASE][3] == 0.5f, @@ -221,7 +221,7 @@ int main(void) sp1_prst_rip(&b, 6); CHECK(b.plaits.slot == 6 && b.plaits.v[SP1_PUI_BASE][1] == 0.0f && b.plaits.v[SP1_PUI_BASE][3] == 0.0f, "chords' neutral BASE is wrong"); - sp1_prst_rip(&b, 23); /* an empty slot (config/engines.csv) -> slot 1 */ + sp1_prst_rip(&b, 23); /* an empty slot (config/engines.cnfg) -> slot 1 */ CHECK(b.plaits.slot == 0, "an empty slot was accepted"); /* ---------- 2. write -> read gives the patch back ---------- */ @@ -496,7 +496,7 @@ int main(void) printf(" %d corrupt files, all safe\n", runs); /* ---------- 9. an engine OFF the list (#50) ---------- */ - printf("9. engines off engines.csv\n"); + printf("9. engines off engines.cnfg\n"); { int off = -1, first = -1, last = -1; for (int i = 0; i < SP1_ENGINE_SLOTS; i++) { @@ -541,6 +541,18 @@ int main(void) sp1_prst_parse(text, (size_t)n, &b, &rep); CHECK(diff(&a, &b, "off-list round trip") == 0 && rep.bad == 0, "an off-list engine does not survive a round trip"); + /* #52: names became hyphenated (VA-VCF, grain-formant); a file saved under the + * old spelling still loads its engine -- names match on letters and digits. */ + static const char *const OLD[] = { "VA + VCF", "grain / formant", + "string machine", "virtual analog" }; + for (size_t k = 0; k < sizeof(OLD) / sizeof(OLD[0]); k++) { + with(text, "engine", OLD[k], buf2, sizeof(buf2)); + sp1_prst_parse(buf2, strlen(buf2), &b, &rep); + const int want = sp1_pui_slot_of(OLD[k], (int)strlen(OLD[k])); + CHECK(want >= 0 && b.plaits.slot == want && rep.bad == 0, + "old name \"%s\" -> slot %d (want %d), bad %d", OLD[k], + b.plaits.slot, want, rep.bad); + } /* the UI plays it, with its own detents and no glyph */ sp1_pui_put(&a.plaits); struct sp1_synth_params sp; diff --git a/tools/host-tests/uitest.c b/tools/host-tests/uitest.c index e9e4308..ce2a179 100644 --- a/tools/host-tests/uitest.c +++ b/tools/host-tests/uitest.c @@ -6,6 +6,7 @@ #include "sp1_marbles_ui.h" #include "sp1_plaits_ui.h" #include "sp1_release_guard.h" +#include "sp1_engines_gen.h" /* the built-in stack (#52) */ /* ---- stubs for the parts that live in the audio thread ---- */ static uint8_t stub_gates; /* t1..t3 as Marbles last rendered them (section 19) */ @@ -1002,6 +1003,54 @@ int main(void) CHECK(pb.timbre > pa.timbre + 0.1f, "a real TIMBRE move after the lock did nothing"); } + printf("21. the engine stack from the drive (#52)\n"); + { + /* A user's engines.cnfg: slots 1-4 empty, chords in 5, speech in 9, VA + VCF in 20 + * (Plaits indices 14, 15, 0). */ + uint8_t st[24]; + memset(st, 255, sizeof(st)); + st[4] = 14; + st[8] = 15; + st[19] = 0; + sp1_pui_init(); + sp1_pui_enter(raw_mid); + sp1_pui_set_stack(st); + sp1_pui_stack_settle(); /* slot 1 is empty now: -> slot 5 */ + CHECK(sp1_pui_slot() == 4 && sp1_pui_engine() == 14, + "settle: slot %d engine %d, want slot 5 (chords)", sp1_pui_slot() + 1, + sp1_pui_engine()); + sp1_pui_engine_step(1); + sp1_pui_engine_step(1); + CHECK(sp1_pui_slot() == 19 && sp1_pui_engine() == 0, + "T3 twice: slot %d, want 20 (VA + VCF)", sp1_pui_slot() + 1); + sp1_pui_engine_step(1); /* wraps past the empty slots */ + CHECK(sp1_pui_slot() == 4, "T3 wrap: slot %d, want 5", sp1_pui_slot() + 1); + sp1_pui_engine_step(-1); + CHECK(sp1_pui_slot() == 19, "T2 wrap: slot %d, want 20", sp1_pui_slot() + 1); + /* ROTC returns to the FIRST FILLED slot of THIS stack (Adara, #52). */ + sp1_pui_rip(); + CHECK(sp1_pui_slot() == 4 && sp1_pui_engine() == 14, + "ROTC: slot %d engine %d, want slot 5 (chords)", sp1_pui_slot() + 1, + sp1_pui_engine()); + /* Names resolve against this stack, any spelling; off it -> off-list. */ + CHECK(sp1_pui_slot_of("VA-VCF", 6) == 19, "VA-VCF -> %d, want slot 20", + sp1_pui_slot_of("VA-VCF", 6)); + CHECK(sp1_pui_slot_of("grain / formant", 15) == SP1_PUI_OFFLIST + 11, + "grain / formant is off this stack: %d", sp1_pui_slot_of("grain / formant", 15)); + CHECK(sp1_pui_slot_of("virtual analog", 14) == SP1_PUI_OFFLIST + 8, + "virtual analog is off this stack"); + /* A stack with no engine is never installed: the built-in one is used. */ + memset(st, 255, sizeof(st)); + sp1_pui_set_stack(st); + sp1_pui_rip(); + CHECK(sp1_pui_slot() == 0 && sp1_pui_engine() == 8, + "empty stack -> built-in: slot %d engine %d", sp1_pui_slot() + 1, + sp1_pui_engine()); + /* And back to the built-in stack for anything after this. */ + const uint8_t def[24] = SP1_ENGINE_DEFAULT_STACK; + sp1_pui_set_stack(def); + } + printf("\n%s (%d failure%s)\n", fails ? "FAILED" : "all checks passed", fails, fails == 1 ? "" : "s"); return fails != 0;