diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml
index 25deab4..bbda699 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.7.2
+ placeholder: v0.8.0
validations:
required: true
diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml
index ec96ebe..6de1b56 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.7.2
+ placeholder: v0.8.0
validations:
required: false
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 701c800..e4d4b19 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
+ uactest.c prsttest.c
"$SP1_HOST_BUILD_DIR/routetest"
"$SP1_HOST_BUILD_DIR/uitest"
"$SP1_HOST_BUILD_DIR/miditest"
@@ -43,17 +43,31 @@ jobs:
"$SP1_HOST_BUILD_DIR/miditest_clock"
"$SP1_HOST_BUILD_DIR/test_usb_rt_parse"
"$SP1_HOST_BUILD_DIR/uactest"
+ "$SP1_HOST_BUILD_DIR/prsttest"
firmware:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
+ # Every Plaits image carries the eMMC storage and drive mode (#49); they differ
+ # only in whether the image FORMATS the card. Adara, 2026-10-08:
+ # plaits -> wakes-sp1.bin never formats (no formatter linked at all)
+ # fresh -> wakes-sp1-fresh.bin formats the eMMC once per build (SP1_FRESH)
+ # fallback -> the test-tone recovery image: no Plaits, never touches the eMMC
include:
- config: plaits
plaits: y
+ extra: ""
+ bin: wakes-sp1
+ - config: fresh
+ plaits: y
+ extra: -DCONFIG_SP1_FRESH=y
+ bin: wakes-sp1-fresh
- config: fallback
plaits: n
+ extra: ""
+ bin: wakes-sp1
defaults:
run:
working-directory: ws
@@ -68,9 +82,9 @@ jobs:
run: |
python -m west build -p always -b stem_player wakes-sp1/firmware -d build \
-- -DBOARD_ROOT="$PWD/wakes-sp1" -DCONFIG_SP1_PLAITS=${{ matrix.plaits }} \
- 2>&1 | tee build.log
+ ${{ matrix.extra }} 2>&1 | tee build.log
- # Both configs build with 0 warnings; keep it that way. This also catches a
+ # Every config builds with 0 warnings; keep it that way. This also catches a
# Kconfig "assigned ... but got ..." warning, i.e. a -DCONFIG_ that did not take.
- name: No warnings
run: |
@@ -83,6 +97,24 @@ jobs:
- name: Check the image (0x20000, SAFETY.md constraints)
run: python wakes-sp1/tools/ci/check_image.py build | tee check.txt
+ # A formatting image must never ship under the plain name, and the others must be
+ # what their names say. Checked from the build's own .config, not from the matrix.
+ - name: The configuration is what the name says
+ run: |
+ cfg=build/zephyr/.config
+ on() { grep -qx "CONFIG_$1=y" "$cfg"; }
+ fail() { echo "::error::${{ matrix.config }}: $1"; exit 1; }
+ case "${{ matrix.config }}" in
+ plaits) { on SP1_STORAGE && on SP1_DRIVE; } || fail "storage or drive mode missing"
+ if on SP1_FRESH; then fail "a formatting image named wakes-sp1"; fi ;;
+ fresh) { on SP1_STORAGE && on SP1_DRIVE && on SP1_FRESH; } || fail "not a fresh image" ;;
+ fallback) if on SP1_STORAGE; then fail "the recovery image must not touch the eMMC"; fi ;;
+ esac
+ for d in SP1_STORAGE_TEST SP1_EMMC_VERIFY; do
+ if on $d; then fail "diagnostic $d is on"; fi
+ done
+ echo "${{ matrix.config }}: OK"
+
- name: Size
run: python wakes-sp1/tools/ci/size_report.py report build -o size-head.json
@@ -106,7 +138,7 @@ jobs:
run: |
if ! python -m west build -p always -b stem_player base/firmware -d build-base \
-- -DBOARD_ROOT="$PWD/base" -DCONFIG_SP1_PLAITS=${{ matrix.plaits }} \
- > build-base.log 2>&1; then
+ ${{ matrix.extra }} > build-base.log 2>&1; then
tail -n 40 build-base.log
exit 1
fi
@@ -136,6 +168,16 @@ jobs:
echo ""
} | tee "size-${{ matrix.config }}.md" >> "$GITHUB_STEP_SUMMARY"
+ # The tools all expect wakes-sp1.bin (CONFIG_KERNEL_BIN_NAME); the fresh image is
+ # RENAMED, not copied, so its artifact holds no file a person could take for the
+ # one that does not format.
+ - name: Name the image (${{ matrix.bin }}.bin)
+ if: always() && matrix.bin != 'wakes-sp1'
+ run: |
+ if [ -f build/zephyr/wakes-sp1.bin ]; then
+ mv build/zephyr/wakes-sp1.bin "build/zephyr/${{ matrix.bin }}.bin"
+ fi
+
- uses: actions/upload-artifact@v7
if: always()
with:
@@ -144,7 +186,7 @@ jobs:
include-hidden-files: true
if-no-files-found: warn
path: |
- ws/build/zephyr/wakes-sp1.bin
+ ws/build/zephyr/${{ matrix.bin }}.bin
ws/build/zephyr/wakes-sp1-midi.md
ws/build/zephyr/wakes-sp1-midi.csv
ws/build/zephyr/wakes-sp1.elf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4ddda6a..2814775 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,7 +1,8 @@
-# Every PR to main, and every push to main, that touches a build input: build both
-# configs, run the host suites, gate on check_image.py, and put the size diff in the
-# run's summary. Administrative changes (see `paths`) run nothing. Tags always build
-# (release.yml), and workflow_dispatch builds on demand.
+# Every PR to main, and every push to main, that touches a build input: build every
+# image (wakes-sp1, wakes-sp1-fresh, fallback), run the host suites, gate on
+# check_image.py, and put the size diff in the run's summary. Administrative changes
+# (see `paths`) run nothing. Tags always build (release.yml), and workflow_dispatch
+# builds on demand.
name: ci
on:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fe4290f..e9be2eb 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -9,8 +9,10 @@
#
# It is attached twice: versioned, and as plain `wakes-sp1.bin`, so that
# releases/latest/download/wakes-sp1.bin (the README's download link) always names
-# the newest PUBLISHED release. GitHub's "latest" skips drafts and pre-releases, so
-# that link moves only when a person publishes a full release.
+# the newest PUBLISHED release. `wakes-sp1-fresh.bin`, the image that FORMATS the eMMC
+# (#49), is attached the same two ways; the fallback is attached versioned only.
+# GitHub's "latest" skips drafts and pre-releases, so that link moves only when a
+# person publishes a full release.
name: release
on:
@@ -85,6 +87,8 @@ jobs:
mkdir dist
cp in/wakes-sp1-plaits/build/zephyr/wakes-sp1.bin "dist/wakes-sp1-$t.bin"
cp in/wakes-sp1-plaits/build/zephyr/wakes-sp1.bin dist/wakes-sp1.bin
+ cp in/wakes-sp1-fresh/build/zephyr/wakes-sp1-fresh.bin "dist/wakes-sp1-$t-fresh.bin"
+ cp in/wakes-sp1-fresh/build/zephyr/wakes-sp1-fresh.bin dist/wakes-sp1-fresh.bin
cp in/wakes-sp1-fallback/build/zephyr/wakes-sp1.bin "dist/wakes-sp1-$t-fallback.bin"
# The MIDI CC chart for exactly this build's script (M5a, tools/gen_midi.py).
cp in/wakes-sp1-plaits/build/zephyr/wakes-sp1-midi.md "dist/wakes-sp1-$t-midi.md"
@@ -105,13 +109,28 @@ jobs:
echo
echo "\`wakes-sp1.bin\` is the same file under a fixed name, for the README's download link."
echo "Check the file against \`SHA256SUMS\` before flashing."
- echo "\`wakes-sp1-$t-fallback.bin\` is the test-tone build without Plaits or Marbles,"
- echo "for diagnosing hardware only. It is not the instrument."
+ echo
+ echo "### Storage: \`wakes-sp1\` vs \`wakes-sp1-fresh\`"
+ echo
+ echo "- **\`wakes-sp1-$t.bin\` never formats the SP-1's internal storage (the eMMC).** Flash"
+ echo " it to update: your presets and files stay where they are."
+ echo "- **\`wakes-sp1-$t-fresh.bin\` FORMATS the eMMC** the first time it turns ON, and"
+ echo " **erases everything on it**, including whatever another firmware left there (stock"
+ echo " stems, tape-looper recordings). Flash it once to set the storage up, or to start"
+ echo " over; a progress bar shows on T1-T4 while it formats. Flashing the same fresh file"
+ echo " again does not format a second time. \`wakes-sp1-fresh.bin\` is the same file under"
+ echo " a fixed name."
+ echo "- Without a formatted card Wakes still plays; the storage features stay off."
+ echo
+ echo "\`wakes-sp1-$t-fallback.bin\` is the test-tone recovery build without Plaits or Marbles."
+ echo "It never touches the eMMC, and is for diagnosing hardware only. It is not the instrument."
echo
echo "## Size${PREV:+ vs $PREV}"
echo
cat in/wakes-sp1-plaits/size-plaits.md
echo
+ cat in/wakes-sp1-fresh/size-fresh.md
+ echo
cat in/wakes-sp1-fallback/size-fallback.md
echo
echo "## SHA-256"
diff --git a/LICENSES/FatFs.txt b/LICENSES/FatFs.txt
new file mode 100644
index 0000000..762a34d
--- /dev/null
+++ b/LICENSES/FatFs.txt
@@ -0,0 +1,14 @@
+FatFs - Generic FAT Filesystem Module R0.16
+Copyright (C) 2025, ChaN, all right reserved.
+
+FatFs module is an open source software. Redistribution and use of FatFs in
+source and binary forms, with or without modification, are permitted provided
+that the following condition is met:
+
+1. Redistributions of source code must retain the above copyright notice,
+ this condition and the following disclaimer.
+
+This software is provided by the copyright holder and contributors "AS IS"
+and any warranties related to this software are DISCLAIMED.
+The copyright owner or contributors be NOT LIABLE for any damages caused
+by use of this software.
diff --git a/LICENSES/README.md b/LICENSES/README.md
index b7f719e..af6c133 100644
--- a/LICENSES/README.md
+++ b/LICENSES/README.md
@@ -11,6 +11,7 @@ what was changed.
| `MIT-feldd.txt` | Benjamin Reece | `third_party/feldd/` (the USB-MIDI 1.0 class and its packet parser) and the build-time patched copy of `usb_midi1.c` |
| `MIT-sp1-tape-looper.txt` | chattock | the board definition, power-off and watchdog sequence, and codec bring-up adapted from chattock/sp1-tape-looper |
| `MIT-SP-1-dev.txt` | Tim Knapen | the SP-1 pin map and hardware documentation from timknapen/SP-1-dev |
+| `FatFs.txt` | ChaN | FatFs, the FAT filesystem on the eMMC (Zephyr's `fatfs` module, `modules/fs/fatfs`), compiled into images built with `CONFIG_SP1_STORAGE` |
| `MIT-sp1-midi.txt` | Eric Lewis | the original `stem_player` Zephyr board that the board definition descends from |
| `Apache-2.0.txt` | the Zephyr Project contributors; Ryan Gilmore | `third_party/sp1-usb-audio/` (USB audio out; it also carries its own `LICENSE` and `NOTICE`), `firmware/src/sp1_uac.{c,h}` and `tools/host-tests/uactest.c` (derived from it), `boards/teenageengineering/stem_player/Kconfig.defconfig`, `Kconfig.stem_player` and `stem_player_defconfig` (inherited from Zephyr's board template), `zephyr-patches/`, `firmware/src/sp1_usbd.c` (derived from Zephyr's USB sample helper), and the Zephyr RTOS compiled into every firmware image |
diff --git a/NOTICE b/NOTICE
index 1041f06..336d87c 100644
--- a/NOTICE
+++ b/NOTICE
@@ -22,19 +22,31 @@ SP-1 board definition and power/watchdog sequence
48 kHz clock topology, the bring-up order, the I2S stream configuration,
and the TAS2505 and CS42L42 register sequences, ported verbatim; and
(M3) the headphone auto-mute: CS42L42 jack sense (reg 0x1B77 bit 7),
- 3-read debounce, TAS2505 speaker driver on/off (page 1 reg 0x2D).
+ 3-read debounce, TAS2505 speaker driver on/off (page 1 reg 0x2D); and
+ (M6) the 1-bit eMMC protocol in firmware/src/sp1_emmc.c: the eMMC pin map,
+ the power/reset/init sequence, the command framing and the response and
+ data sampling points (reduced, read-only and bit-banged here).
SP-1 hardware documentation and pin map
timknapen/SP-1-dev — Copyright (c) 2026 Tim Knapen — MIT
https://github.com/timknapen/SP-1-dev
Licence text: LICENSES/MIT-SP-1-dev.txt
- Source of: the SP-1 pinout in firmware/src/sp1_board.h, and the CS42L42
- headphone-codec init sequence (via sp1-tape-looper) in sp1_audio.c.
+ Source of: the SP-1 pinout in firmware/src/sp1_board.h, the CS42L42
+ headphone-codec init sequence (via sp1-tape-looper) in sp1_audio.c, and the
+ eMMC driver (emmc.c, via sp1-tape-looper) behind firmware/src/sp1_emmc.c.
TAS2505 speaker amplifier configuration
Texas Instruments, TAS2505 Application Reference Guide (SLAU472C), sec. 5.1
The register sequence in sp1_audio.c follows it, via sp1-tape-looper.
+FAT filesystem on the eMMC (M6, images built with CONFIG_SP1_STORAGE)
+ FatFs R0.16 — Copyright (C) 2025, ChaN — FatFs licence (one condition:
+ keep the notice in source redistributions)
+ https://elm-chan.org/fsw/ff/
+ Licence text: LICENSES/FatFs.txt
+ Used unmodified through Zephyr's fatfs module (zephyrproject-rtos/fatfs,
+ pinned by the Zephyr revision in west.yml) and Zephyr's fs layer.
+
Zephyr BSP precedent
ericlewis/sp1-midi — Copyright (c) 2026 Eric Lewis — MIT
https://github.com/ericlewis/sp1-midi
diff --git a/README.md b/README.md
index 2da3582..523a83b 100644
--- a/README.md
+++ b/README.md
@@ -3,34 +3,36 @@
alt="Wakes: a love letter to Mutable Instruments, by Worldwave">
-Wakes is a semimodular synthesizer, built as a custom firmware for the Teenage Engineering SP-1, Teenage Engineering's unreleased stem player.
-It runs two Mutable Instruments modules combined:
+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:
- **Plaits**: A macro-synthesizer voice, featuring multiple sound engines
- **Marbles**: A playful random sequencer
The development of Wakes is unaffiliated with Teenage Engineering or Mutable Instruments.
-IMPORTANT: Flashing custom firmware on the SP-1 is at your own risk. SP-1s are abandonware, they do not have manufacturer support.
-REMEMBER: There is no way to go back to the base firmware once you've flashed it away.
+**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.
## 📖 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, start there.
+**[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.
## Status
-**v0.7.2, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues).
+**v0.8.0, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues).
## Flashing
-1. **Download the latest [`wakes-sp1.bin`](https://github.com/Worldwave/Wakes/releases/latest/download/wakes-sp1.bin)**.
- Older versions and release notes are on the [releases page](https://github.com/Worldwave/Wakes/releases).
-2. Open . Hold down **T1+T4** while connecting the SP-1 over USB-C.
-3. Follow solderless.engineering's instructions on how to connect to your SP-1 to flash it.
+1. Wakes features new storage protocols for the SP-1. If you've never used Wakes before, you need to format your storage partition.
+ To do that, **Download the latest Fresh bin [`wakes-sp1-fresh.bin`](https://github.com/Worldwave/Wakes/releases/latest/download/wakes-sp1-fresh.bin)**.
+2. If you've used Wakes before, and want to avoid touching your storage, **Download the latest regular bin [`wakes-sp1.bin`](https://github.com/Worldwave/Wakes/releases/latest/download/wakes-sp1.bin)**.
+3. Older Wakes versions and release notes are available through the repo's [releases page](https://github.com/Worldwave/Wakes/releases).
+4. Open . Hold down **T1+T4**. Keep them held while connecting the SP-1 over USB-C.
+5. Follow solderless.engineering's instructions on how to connect to your SP-1 to flash it.
3. Select the `.bin` in Solderless Engineering's "firmware utility" page, flash it, and once done, you can unplug.
-The T1+T4 recovery trigger in step 2 lives in Teenage Engineering's bootloader, not in Wakes, so it
-works with whatever firmware is installed. Wakes never writes below `0x20000` (and neither should your CFW's),
+The T1+T4 recovery trigger in step 4 lives in Teenage Engineering's bootloader, not in Wakes, so it
+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.
## Building
diff --git a/docs/BUILD.md b/docs/BUILD.md
index 4996f22..62a5b1f 100644
--- a/docs/BUILD.md
+++ b/docs/BUILD.md
@@ -23,6 +23,20 @@ Artifact: **`build\zephyr\wakes-sp1.bin`**. (`CONFIG_KERNEL_BIN_NAME="wakes-sp1"
`firmware/prj.conf` renames the outputs from Zephyr's default `zephyr.*`. The
`build\zephyr\` directory name itself comes from the CMake target and is unaffected.)
+### The three images
+
+| Image | Build | eMMC |
+|---|---|---|
+| `wakes-sp1.bin` | as above | storage + drive mode; **never formats** (no formatter is linked) |
+| `wakes-sp1-fresh.bin` | add `-DCONFIG_SP1_FRESH=y` after the `--` | **formats the eMMC** on its first ON, once per build |
+| fallback | add `-DCONFIG_SP1_PLAITS=n` | test tone, recovery only; never touches the eMMC |
+
+The fresh build still writes `build\zephyr\wakes-sp1.bin`: **rename it to
+`wakes-sp1-fresh.bin` straight away**, so it is never flashed by mistake as the image that
+does not format. CI does the same, and checks each image's `.config` against its name.
+Storage diagnostics, off in every shipped image: `-DCONFIG_SP1_STORAGE_TEST=y` (eMMC report
++ a 512 KB pattern test on each ON) and `-DCONFIG_SP1_EMMC_VERIFY=y` (every write read back).
+
### Three things that are not optional
**Quote `BOARD_ROOT` and use forward slashes.** Unquoted, the argument splits at the
@@ -83,7 +97,7 @@ The failure modes that recur on this board:
| a `pwm*`/`adc` node not found | the DTS label, and that the matching `CONFIG_*` driver is enabled |
| `zephyr,deferred-init` unknown property, or `device_init()` undeclared | see **Deferred PWM init** below — there is a fallback |
| pinctrl error on a `PSEL` | spelling in `stem_player-pinctrl.dtsi` |
-| missing module | `west.yml`'s allowlist — `cmsis`, `cmsis_6`, `hal_nordic` are all required |
+| missing module | `west.yml`'s allowlist — `cmsis`, `cmsis_6`, `fatfs`, `hal_nordic` are all required |
| **LEDs work but wrong ones, or wrong order** | **not a build error.** pinctrl channel order vs LED index — see the comment block in `sp1_board.h` |
| **ADC reads nonsense** | **not a build error.** Channel `reg` vs `io-channels` index vs the index used in C |
@@ -261,6 +275,7 @@ git config --global --add safe.directory C:/sp1-ws/zephyr
git config --global --add safe.directory C:/sp1-ws/modules/hal/cmsis
git config --global --add safe.directory C:/sp1-ws/modules/hal/cmsis_6
git config --global --add safe.directory C:/sp1-ws/modules/hal/nordic
+git config --global --add safe.directory C:/sp1-ws/modules/fs/fatfs
git config --global --add safe.directory C:/sp1-ws/wakes-sp1
```
diff --git a/docs/DEFAULTS.md b/docs/DEFAULTS.md
index 4a0c5cb..74516f8 100644
--- a/docs/DEFAULTS.md
+++ b/docs/DEFAULTS.md
@@ -171,10 +171,11 @@ A ROTC on MARBLES now leaves the drive alone, deliberately.
| parameter | boot | ROTC |
|---|---|---|
| t1 destination | none | none |
-| t2 destination | TRIG | none |
+| t2 destination | TRIG | **TRIG** (#50) |
| t3 destination | none | none |
| X1 destination | V/Oct | none |
-| X2, X3, Y destination | none | none |
+| X2 destination | none | **V/Oct** (#50) |
+| X3, Y destination | none | none |
### Transport
@@ -246,8 +247,13 @@ Adara's answers, 2026-09-24. **This is the build list.**
| 11 | re-draw the DEJA VU loop? | **yes**, as the consequence of 10 |
| 12 | reset both modules? | **no — only the foreground module** |
-Routing on ROTC is the headline change: **every destination goes to `none`.** "Rip out the
-cables" now means what it says.
+Routing on ROTC: **t2 → TRIG and X2 → V/Oct, every other destination `none`** (Adara, #50 —
+through v0.7.2 every destination went to `none`). PRST's default slots carry the same routing.
+Because X2 lands on V/Oct, a MARBLES ROTC also turns the PLAITS quantizer off and opens the
+FREQUENCY range, exactly as routing V/Oct by hand does (the M4b interlock).
+
+⚠️ **The first bullet below describes M4d's all-`none` rip and no longer applies** — after a
+MARBLES ROTC, PLAY plays (t2 fires a note on every tick, X2 sets its pitch).
⚠️ **Two consequences of the routing decision, both intended as far as I can tell, both worth a
sentence before they surprise anyone on hardware:**
diff --git a/docs/UI-PAGES.md b/docs/UI-PAGES.md
index 89e9c48..c3083a9 100644
--- a/docs/UI-PAGES.md
+++ b/docs/UI-PAGES.md
@@ -111,7 +111,7 @@ So the combination space is exactly: **`••` + one button**, on either ladder
| **T2** | previous engine (flashes its glyph) | held 2 s: **UNPATCH TIMBRE** |
| **T3** | next engine | held 2 s: **UNPATCH MORPH** |
| **T4** | **swap module** → MARBLES | held 2 s: **UNPATCH HARMONICS** · a short press does nothing (output select moved to SETTINGS T4 in v0.4.6) |
-| **PLAY** | Marbles' clock **run / stop** | held 3 s: **rip out the cables** (see below) |
+| **PLAY** | Marbles' clock **run / stop** | **PRST**: a press shows the current slot (one LED, T1–T4, ramping at 10 Hz for 1.6 s); a press while it shows = the **next slot** (4 → 1), loaded at once; letting go of `••` leaves the browser and the page returns. Held 3 s from a press that did not change slot: **rip out the cables** (see below) |
| **RWD** | one **TRIG** | **coarser** burst division |
| **FFWD** | held: **burst** — re-triggers on the 1/div grid, running or stopped | **finer** burst division |
| **VOL− / VOL+** | output level, 3 dB steps | **the soft-clip drive** — see below |
@@ -126,11 +126,20 @@ 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`
+ 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
+ list position 1. A name no engine of the build has loads list position 1.
- **Rip out the cables** = `••` + PLAY held 3 s: a **full patch wipe** of the module on show
(`docs/DEFAULTS.md` is the spec). On PLAITS: engine → slot 1, the four BASE faders → that
engine's neutral state (0.5 for a bipolar parameter, 0 for a unipolar one, F1 → centre = C4),
all four attenuverters → 0, SETTINGS → defaults, quantizer → off, output → OUT, division → 1/32.
- The row flickers twice, fades to black, and only commits at 3 s; letting go earlier cancels.
+ The row shows the PRST slot glyph for 1.6 s, goes black for 0.25 s, rises to full over 0.4 s,
+ then plays the Unpatch animation and commits at 3 s (#50); letting go once it is past the glyph
+ cancels and returns to the SHIFT screen. After a PRST slot change in the same `••` hold it does
+ not start at all until `••` is released. With PRST off (no filesystem) there is no glyph: the
+ first 1.6 s are a slow fade of the face LEDs to black (Adara), then the same; a press is ROTC only.
⚠️ Until M4b this kept the engine and BASE and was a modulation reset. It is a patch wipe now.
⚠️ **The faders do not move** — pickup catches them up on the next touch, so straight after a
rip the instrument sounds neutral while the faders still look wrong. By design.
@@ -287,7 +296,7 @@ TIMBRE, MORPH or HARMONICS.
| **`••` + T1 / T2 / T3** | **t1 / t2 / t3 destination** · held 2 s: **UNPATCH** that output | **X1 / X2 / X3 destination** · held 2 s: **UNPATCH** that output | — |
| **`••` + T4** | **Y destination** · held 2 s: **UNPATCH Y** | **Y destination** · held 2 s: **UNPATCH Y** | — |
| **`••` + FFWD / RWD** | *(free)* | **next / previous scale**, no wrap, excluded scales skipped | *(free)* |
-| **`••` + PLAY** | held 3 s: **rip out the cables** | the same | the same |
+| **`••` + PLAY** | PRST slot / next slot; held 3 s: **rip out the cables** | the same | the same |
| **VOL− / VOL+** | output level | output level | output level |
⚠️ **T4 is `[J]` on the SETTINGS page, so the module swap is unavailable there.** Tap `••` once
@@ -391,7 +400,7 @@ internal envelope between gates and the attenuverter would change meaning severa
| | |
|---|---|
| routing at **boot** | **t2 → TRIG** (the master clock, so every tick fires a note — the most predictable "press PLAY and hear something" default, with no rhythmic randomness); **X1 → V/Oct**; everything else → none |
-| routing after a **rip** | **everything → none.** "Rip out the cables" means what it says, so PLAY makes no sound until something is dialled back in |
+| routing after a **rip** | **t2 → TRIG, X2 → V/Oct**, everything else → none (#50; through v0.7.2 a rip cleared everything). X2 on V/Oct turns the PLAITS quantizer off, as routing it by hand does |
| a rip also | **re-seeds and re-draws the DEJA VU loop**, and **leaves the clock running** — its phase jumps once. Every t and X BASE fader resets; the page you are standing on is kept |
| t | coin toss, ×1 range, RATE centre = **120 BPM**, BIAS centre, no jitter, DEJA VU locked |
| X | SPREAD centre, BIAS centre, STEPS 0.66 (so X is quantized and Y is not), DEJA VU locked, `[J]` **INTELLIGENT** (X and Y), identical diversity, **major** |
diff --git a/docs/UI-SPEC.md b/docs/UI-SPEC.md
index a41190a..f121ecb 100644
--- a/docs/UI-SPEC.md
+++ b/docs/UI-SPEC.md
@@ -387,7 +387,7 @@ low gate is 0 V, not "nothing", or the attenuverter would change meaning several
### Defaults — also what `••` + PLAY held 3 s restores on MARBLES ("rip out the cables")
-coin toss · **t2 → TRIG** (v0.12; t1 + t3 until v0.11) · **X1 → V/Oct** *(boot only — a rip now disconnects everything)* (V/Oct has no attenuverter, so TIMBRE,
+coin toss · **t2 → TRIG** (v0.12; t1 + t3 until v0.11) · **X1 → V/Oct** *(boot only — a rip routes **X2** to V/Oct instead, with t2 → TRIG and everything else out; #50)* (V/Oct has no attenuverter, so TIMBRE,
MORPH and FM stay on Plaits' internal envelope) · X2, X3, Y → none · RATE at centre =
**120 BPM** · clock range ×1 · `[J]` **INTELLIGENT**, one setting for X and Y (v0.13/v0.14; X was
0–2 V and Y was ±5 V before it existed) · STEPS just above centre, so X is quantized and Y is not ·
@@ -439,12 +439,16 @@ below — the lock is unreachable by feel otherwise.
| Gesture | Result |
|---|---|
| **Press** Play | start Marbles' clock (on a beat: the first t2 tick is immediate, and the DEJA VU loop restarts from its first step); the next press stops it. On either module |
-| `••` + Play held 3 s | **rip out the cables** on the module on show: PLAITS — SHIFT + SETTINGS pages; MARBLES — the defaults above. With `••` down first, PLAY does not touch the clock |
-
-The rip animation, on the track row, all while held: two quick flickers (70 ms on / off),
-a fade to black, black for the last 0.5 s. At 3 s the reset happens and the page fades back
-in over 0.5 s. Letting go before 3 s cancels (the page returns over 150 ms). It is a shift
-use, so it never starts a power-off; the 20 s backstop still applies.
+| `••` + Play | **PRST** (#50): the current slot's glyph; pressed again while it shows, the next slot (4 → 1), loaded at once. Letting go of `••` leaves the browser: the glyph ends and the page you were on returns. With `••` down first, PLAY does not touch the clock |
+| `••` + Play held 3 s | **rip out the cables** on the module on show: PLAITS — the full patch wipe (docs/DEFAULTS.md); MARBLES — the defaults above. Not after a PRST slot change in the same `••` hold |
+
+The rip animation, on the track row, all while held (#50; through v0.7.2 two flickers, a
+fade and black): the PRST slot glyph for 1.6 s, black 0.25 s, a rise to full over 0.4 s, the
+Unpatch animation (0.75 s). At 3 s the reset happens and the page fades back in over 0.5 s.
+With PRST off the glyph's 1.6 s are a slow fade of the face LEDs to black instead.
+Letting go during the glyph is just a PRST press; letting go after it cancels (the SHIFT
+screen returns over 150 ms). It is a shift use, so it never starts a power-off; the 30 s
+backstop still applies.
~~Tap = TRIG, hold = clock~~ (v0.1–v0.8, built in M3): **Play no longer fires a TRIG** —
RWD does, and the FFWD burst. Simpler: one button, one job.
diff --git a/docs/Wakes - Manual.pdf b/docs/Wakes - Manual.pdf
index fd44f61..f7f2ae4 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 151e114..becb3c3 100644
--- a/firmware/CMakeLists.txt
+++ b/firmware/CMakeLists.txt
@@ -72,6 +72,20 @@ add_custom_command(
add_custom_target(sp1_audio_gen DEPENDS ${SP1_AUDIO_H})
add_dependencies(app sp1_audio_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).
+set(SP1_PRST_GEN ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_prst.py)
+set(SP1_PRST_H ${CMAKE_CURRENT_BINARY_DIR}/sp1_generated/sp1_prst_gen.h)
+add_custom_command(
+ OUTPUT ${SP1_PRST_H}
+ COMMAND ${Python3_EXECUTABLE} ${SP1_PRST_GEN} ${SP1_PRST_H}
+ DEPENDS ${SP1_PRST_GEN}
+ COMMENT "Generating the PRST field table (tools/gen_prst.py)"
+)
+add_custom_target(sp1_prst_gen DEPENDS ${SP1_PRST_H})
+add_dependencies(app sp1_prst_gen)
+
target_sources(app PRIVATE
src/main.c
src/sp1_led.c
@@ -91,6 +105,14 @@ target_sources(app PRIVATE
src/sp1_plaits_ui.c
)
+# ---- 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_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)
+endif()
+
# ---- M3: the Plaits voice (third_party/eurorack, vendored unmodified) ----
# Built as its own Zephyr library so it gets its OWN optimisation flags. The rest of
# the firmware is built -Os (CONFIG_SIZE_OPTIMIZATIONS); the DSP is the one place where
@@ -398,7 +420,7 @@ if(CONFIG_SP1_PLAITS)
)
# A Zephyr library declared from the APPLICATION is not linked on its own.
target_link_libraries(app PRIVATE sp1_plaits)
- target_sources(app PRIVATE src/sp1_marbles_ui.c)
+ target_sources(app PRIVATE src/sp1_marbles_ui.c src/sp1_prst.c)
target_include_directories(app PRIVATE src)
# ---- M5a: USB-MIDI in (the MIDI script is generated above, with the engines) ----
diff --git a/firmware/Kconfig b/firmware/Kconfig
index 1d4b8c0..40abf54 100644
--- a/firmware/Kconfig
+++ b/firmware/Kconfig
@@ -87,6 +87,99 @@ config SP1_PROFILE_ICACHE
engine. Reads the NVMC counter a few times per Plaits block (~0.05 % CPU). Off in
release builds.
+config SP1_STORAGE
+ bool "eMMC storage: a FAT32 volume and its own thread (M6, #43)"
+ default SP1_PLAITS
+ select FILE_SYSTEM
+ select FAT_FILESYSTEM_ELM
+ select DISK_ACCESS
+ help
+ The eMMC driver (src/sp1_emmc.c), FatFs on top of it, and a low-priority thread
+ that does all the work (src/sp1_store.h): below audio, main and USB, so it costs
+ the audio block nothing. Never formats -- that is SP1_FRESH alone. On in every
+ Plaits image (wakes-sp1, wakes-sp1-fresh); off in the fallback, the recovery image
+ that never touches the eMMC.
+
+config SP1_STORAGE_TEST
+ bool "Diagnostics: eMMC report and file test on every entry to ON (#43)"
+ depends on SP1_STORAGE
+ select INIT_STACKS # the storage thread's stack headroom, in the report
+ help
+ The card's identity, EXT_CSD and partition table (lines starting "EMMC"), then a
+ file test on the volume (lines starting "STORE"): a counter of ON entries that
+ survives power cycles and reflashes, 512 KB written in bursts, read back, compared
+ and deleted, free space and the WAKES directory. Off in release builds.
+
+config SP1_EMMC_VERIFY
+ bool "Diagnostics: read every eMMC write back and log any mismatch (#43)"
+ depends on SP1_STORAGE
+ help
+ Every written block is read straight back; a block that reads back wrong is logged
+ ("EMMC VERIFY FAIL": where in its burst, the card's token and busy, whether a slow
+ re-read agrees) and rewritten on its own. Halves write speed. Off in release builds.
+ (Built for the 2026-10-07 data hunt: every write verified; the fault was in burst
+ READS, src/sp1_emmc.c.)
+
+config SP1_FRESH
+ bool "wakes-sp1-fresh: FORMAT the eMMC on the first entry to ON (#43)"
+ depends on SP1_STORAGE
+ select FILE_SYSTEM_MKFS
+ select FS_FATFS_EXTRA_NATIVE_API # f_setlabel: the volume is labelled "SP-1"
+ help
+ ⚠️ Erases the whole eMMC: one FAT32 partition from 4 MB, the build's ID written to
+ WAKES/FRESH.ID, never again while that file matches (src/sp1_store.h). A normal
+ build contains no formatter at all, and tools/ci/check_image.py fails one that does.
+
+config SP1_DRIVE
+ bool "Drive mode: the eMMC as a USB drive in STANDBY (#43)"
+ depends on SP1_STORAGE
+ default y
+ select USBD_MSC_CLASS
+ help
+ A USB mass-storage interface, always in the descriptor (so going STANDBY <-> ON
+ never re-enumerates and MIDI / audio are never disturbed). In STANDBY with a host
+ attached the card is the host's; turning ON takes it back -- the host then sees "no
+ medium" -- after any command already in progress finishes (src/sp1_store.h). The
+ interface goes LAST, after CDC, MIDI and audio, so their numbers do not move, and
+ bcdDevice changes (SP1_USB_BCD_DEVICE) because the function set did.
+
+config SP1_USB_BCD_DEVICE
+ hex "USB bcdDevice"
+ default 0x0500 if SP1_DRIVE
+ default 0x0403
+ help
+ The device release number. 0x0403 is what Zephyr 4.3 put there by default
+ (USB_BCD_DRN) and every release through v0.7.2 shipped with it. One PID for good:
+ when the set of USB functions changes, this changes instead (M5c), so a host that
+ cached the old layout treats the device as new. 0x0500 = + the drive (M6).
+
+# The drive's transfers: 16 blocks per disk call, so a host's large reads and writes become
+# CMD18 / CMD25 bursts (sp1_emmc.h). 8 KB of RAM, only in drive builds.
+config USBD_MSC_SCSI_BUFFER_SIZE
+ default 8192 if SP1_DRIVE
+
+config USBD_MSC_STACK_SIZE
+ default 2048 if SP1_DRIVE
+
+# ⚠️ Zephyr formats a volume it cannot mount unless told not to. The card arrives holding
+# whatever an earlier firmware left there, so a failed mount must NEVER format: only
+# SP1_FRESH formats, and only on purpose. These defaults come before Kconfig.zephyr's, so
+# they win; check_image.py also fails an image built with MOUNT_MKFS on.
+config FS_FATFS_MOUNT_MKFS
+ default n
+
+# Long file names (Adara, M6): presets are ".prst", which 8.3 cannot hold, and samples
+# will want readable names. ~0.5 KB of RAM for the name buffer (BSS mode), a few KB of flash;
+# nothing in the audio path.
+config FS_FATFS_LFN
+ default y if SP1_STORAGE
+
+config FS_FATFS_CUSTOM_MOUNT_POINT_COUNT
+ default 1 if SP1_STORAGE
+
+config FS_FATFS_CUSTOM_MOUNT_POINTS
+ default "EMMC" if SP1_STORAGE
+
config SP1_LOGBUF_KB
int "Stored log, in KB of RAM"
default 96
diff --git a/firmware/VERSION b/firmware/VERSION
index 4cfaf44..485e9ed 100644
--- a/firmware/VERSION
+++ b/firmware/VERSION
@@ -1,5 +1,5 @@
VERSION_MAJOR = 0
-VERSION_MINOR = 7
-PATCHLEVEL = 2
+VERSION_MINOR = 8
+PATCHLEVEL = 0
VERSION_TWEAK = 0
EXTRAVERSION =
diff --git a/firmware/src/main.c b/firmware/src/main.c
index c653411..cdb3ae4 100644
--- a/firmware/src/main.c
+++ b/firmware/src/main.c
@@ -84,11 +84,15 @@
#include "sp1_audio.h"
#include "sp1_meter.h"
#include "sp1_playrow.h"
+#if defined(CONFIG_SP1_STORAGE)
+#include "sp1_store.h"
+#endif
#if defined(CONFIG_SP1_PLAITS)
#include "sp1_synth.h"
#include "sp1_plaits_ui.h"
#include "sp1_marbles.h"
#include "sp1_marbles_ui.h"
+#include "sp1_prst.h" /* M6 (#50): the ROTC defaults main.c owns */
#include "sp1_release_guard.h"
#include "sp1_midi.h"
#endif
@@ -165,13 +169,13 @@ static uint32_t batt_fade_ms;
/* FFWD burst subdivision as a power of two: 1/(1 << g_burst_div). Kept across ON
* sessions (RAM), default 1/32. "••" + FFWD finer, "••" + RWD coarser (M3d). */
#define SP1_BURST_DIV_MAX 7 /* 1/128 */
-static uint8_t g_burst_div = 5; /* 1/32 */
+static uint8_t g_burst_div = SP1_PRST_DEF_BURST; /* 1/32 */
/* Output select (M3f): OUT / AUX / OUT+AUX / OUTxAUX, cycled by T4 on the PLAITS
* SETTINGS panel (#11; it was "••" + T4 until v0.4.6). RAM only, like the burst
* division: a real power-off returns to OUT.
* Shown by flashing one track LED per mode, T1 = OUT ... T4 = OUTxAUX. */
-static uint8_t g_out_mode = SP1_OUT_MAIN;
+static uint8_t g_out_mode = SP1_PRST_DEF_OUT;
static const char *const out_mode_name[SP1_OUT_COUNT] = {
"OUT", "AUX", "OUT+AUX", "OUTxAUX",
@@ -196,7 +200,13 @@ static bool burst_was; /* FFWD burst running (PLAITS, clock stop
static bool ffwd_consumed; /* FFWD pressed with "••": not transport */
static uint32_t burst_n0;
static uint32_t rip_ms; /* "••" + PLAY held, towards SP1_RIP_HOLD_MS */
+static bool rip_armed; /* this PLAY press may still become ROTC */
+static bool rip_glyph; /* ...and it opened the PRST glyph (PRST on) */
static bool rip_show_page; /* rip done, still held: draw the page */
+/* PRST's browser (#50): the slot glyph on show, and whether this "••" hold changed slot. */
+static bool prst_showing;
+static uint32_t prst_show_ms;
+static bool prst_changed;
static uint32_t beats_seen; /* Marbles t2 ticks already shown */
static uint32_t trig_print0; /* TRIG edges at the last AUD line */
@@ -206,27 +216,6 @@ static const char *const x_range_name[SP1_MRB_RANGE_COUNT] = {
};
static const char *const diversity_name[3] = { "identical", "bump", "tilt" };
-/* The rip animation (Adara, M4): two quick flickers of the whole row, a fade to black,
- * black -- all while "••" + PLAY are held -- then, once it completes, a fade back to
- * the page (sp1_display_flash). Times in sp1_ui_timing.h. */
-static void rip_levels(uint32_t t, uint8_t lv[4])
-{
- uint32_t v;
- if (t < 4u * SP1_RIP_FLICKER_MS) {
- /* on, off, on, off */
- v = ((t / SP1_RIP_FLICKER_MS) & 1u) ? 0u : 255u;
- } else if (t < SP1_RIP_HOLD_MS - SP1_RIP_BLACK_MS) {
- const uint32_t t0 = 4u * SP1_RIP_FLICKER_MS;
- const uint32_t span = SP1_RIP_HOLD_MS - SP1_RIP_BLACK_MS - t0;
- v = 255u - ((t - t0) * 255u) / span;
- } else {
- v = 0u;
- }
- for (int i = 0; i < 4; i++) {
- lv[i] = (uint8_t)v;
- }
-}
-
/* ================= UNPATCH: "••" held + Tn held (Adara, M4e) =================
* The one long press in this UI, and deliberately so: it is destructive, it reaches ONE
* cable rather than the whole patch, and it must be hard to do by accident.
@@ -306,6 +295,124 @@ static void unpatch_levels(uint32_t t, uint8_t lv[4])
lv[3] = (uint8_t)out;
}
+/* ---- PRST's slot glyph (Adara, #50) ----
+ * One LED per slot, T1..T4: that LED ramps 100 % -> 0 every SP1_PRST_RAMP_MS (10 Hz), the
+ * other three face LEDs BLACK (Adara) -- sp1_display_flash() is opaque while it holds, so
+ * nothing of the page shows through. The play row carries on as normal (Adara: face LEDs
+ * only). `t` = ms since it appeared. */
+static void prst_glyph_levels(int slot, uint32_t t, uint8_t lv[4])
+{
+ const uint32_t f = t % SP1_PRST_RAMP_MS;
+ for (int i = 0; i < 4; i++) {
+ lv[i] = (i == slot) ? (uint8_t)(255u - (f * 255u) / SP1_PRST_RAMP_MS) : 0u;
+ }
+}
+
+/* ---- 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
+ * 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. */
+static uint32_t offlist_ms; /* 0 = not animating; else ms into it + 1 */
+static uint32_t offlist_count; /* sp1_display_flash_count() after our own flash */
+
+static void offlist_levels(uint32_t t, uint8_t lv[4])
+{
+ const uint32_t f = t % SP1_OFFLIST_RAMP_MS;
+ const uint8_t v = (uint8_t)(SP1_OFFLIST_LEVEL - (f * SP1_OFFLIST_LEVEL) / SP1_OFFLIST_RAMP_MS);
+ for (int i = 0; i < 4; i++) {
+ lv[i] = v;
+ }
+}
+
+static void engine_flash(void)
+{
+ uint8_t lv[4];
+ if (sp1_pui_offlist(sp1_pui_eslot())) {
+ offlist_levels(0u, lv);
+ sp1_display_flash(lv, 100u, SP1_DISP_ENGINE_FADE_MS);
+ offlist_ms = 1u;
+ offlist_count = sp1_display_flash_count();
+ return;
+ }
+ offlist_ms = 0u;
+ sp1_pui_engine_leds(lv);
+ sp1_display_engine(lv);
+}
+
+static void offlist_glyph_tick(uint32_t dt)
+{
+ if (offlist_ms == 0u) {
+ return;
+ }
+ if (sp1_display_flash_count() != offlist_count) {
+ offlist_ms = 0u; /* something else took the row */
+ return;
+ }
+ offlist_ms += dt;
+ const uint32_t t = offlist_ms - 1u;
+ uint8_t lv[4];
+ offlist_levels(t, lv);
+ if (t >= SP1_DISP_ENGINE_HOLD_MS) {
+ offlist_ms = 0u;
+ sp1_display_flash(lv, 0u, SP1_DISP_ENGINE_FADE_MS);
+ } else {
+ sp1_display_flash(lv, 100u, SP1_DISP_ENGINE_FADE_MS);
+ offlist_count = sp1_display_flash_count();
+ }
+}
+
+/* "slot 3" in the log, or "off-list" (#50). Two buffers: one printk may use two. */
+static const char *slot_label(int s)
+{
+ static char b[2][20];
+ static int k;
+ k ^= 1;
+ if (sp1_pui_offlist(s)) {
+ return "off-list";
+ }
+ snprintk(b[k], sizeof(b[k]), "slot %d", s + 1);
+ return b[k];
+}
+
+/* ---- ROTC's animation past the glyph (Adara, #50): t = ms since PLAY went down ----
+ * black SP1_ROTC_BLACK_MS, fade up to full over SP1_ROTC_RISE_MS, then the Unpatch
+ * animation; the wipe commits at SP1_RIP_HOLD_MS (sp1_ui_timing.h checks the sum). */
+BUILD_ASSERT(SP1_ROTC_UNPATCH_AT + SP1_UNPATCH_ANIM_MS == SP1_RIP_HOLD_MS,
+ "ROTC: glyph + black + rise + Unpatch must be SP1_RIP_HOLD_MS (Adara: still 3 s)");
+BUILD_ASSERT(SP1_PRST_GLYPH_MS == 16u * SP1_PRST_RAMP_MS, "16 ramps (Adara)");
+
+static void rotc_levels(uint32_t t, uint8_t lv[4])
+{
+ const uint32_t rise_at = SP1_PRST_GLYPH_MS + SP1_ROTC_BLACK_MS;
+ if (t >= SP1_ROTC_UNPATCH_AT) {
+ unpatch_levels(t - SP1_ROTC_UNPATCH_AT, lv);
+ return;
+ }
+ const uint32_t v = (t < rise_at) ? 0u : ((t - rise_at) * 255u) / SP1_ROTC_RISE_MS;
+ for (int i = 0; i < 4; i++) {
+ lv[i] = (uint8_t)(v > 255u ? 255u : v);
+ }
+}
+
+/* ---- ROTC with PRST off (Adara, #50): a slower fade where the glyph would be ----
+ * No slot to show, so the first SP1_PRST_GLYPH_MS are a slow fade of the face LEDs from what
+ * the page shows (the SHIFT layer, "••" being held) down to black; then the same black, rise
+ * and Unpatch animation as with PRST on. Past the glyph's span it is rotc_levels(). */
+static void rotc_or_fade_levels(uint32_t t, bool marbles, uint8_t lv[4])
+{
+ if (t >= SP1_PRST_GLYPH_MS) {
+ rotc_levels(t, lv);
+ return;
+ }
+ (marbles ? sp1_mui_leds : sp1_pui_leds)(lv);
+ const uint32_t k = 256u - (t * 256u) / SP1_PRST_GLYPH_MS;
+ for (int i = 0; i < 4; i++) {
+ lv[i] = (uint8_t)(((uint32_t)lv[i] * k) >> 8);
+ }
+}
+
#if defined(CONFIG_SP1_PLAITS)
/* The tempo the synth's FFWD burst uses while Marbles is stopped (running, the burst locks to
* Marbles' ramp): Marbles' RATE, or the host's beat while MIDI clocks Marbles (M5b). */
@@ -460,9 +567,7 @@ static void midi_tick(uint32_t dt, bool busy)
if (es != midi_eslot_was && sel == midi_sel_was) {
printk("MODEL %s (MIDI)\n", sp1_pui_engine_name());
if (!busy) {
- uint8_t g[4];
- sp1_pui_engine_leds(g);
- sp1_display_engine(g);
+ engine_flash();
}
}
midi_eslot_was = es;
@@ -589,25 +694,22 @@ static void plaits_buttons(bool fnc, bool running, uint32_t dt)
if (!settings) {
/* T1: flash the engine we are on -- "what am I playing?" (Adara, M4b). */
if (!fnc && sp1_button_pressed(SP1_BTN_T1)) {
- uint8_t elv[4];
- sp1_pui_engine_leds(elv);
- sp1_display_engine(elv);
- printk("ENGINE slot %d: %s (plaits %d) [shown]%s\n",
- sp1_pui_eslot() + 1, sp1_pui_engine_name(), sp1_pui_engine(),
+ engine_flash();
+ printk("ENGINE %s: %s (plaits %d) [shown]%s\n",
+ slot_label(sp1_pui_eslot()), sp1_pui_engine_name(), sp1_pui_engine(),
sp1_pui_eslot() != sp1_pui_slot() ? " (MODEL offset)" : "");
}
/* T2 previous engine, T3 next (UI-SPEC). */
if (step != 0) {
const int sl = sp1_pui_engine_step(step);
- uint8_t elv[4];
- sp1_pui_engine_leds(elv); /* the engine PLAYING (MODEL offset included) */
- sp1_display_engine(elv);
+ engine_flash(); /* the engine PLAYING (MODEL offset included) */
if (sp1_pui_eslot() != sl) {
- printk("ENGINE slot %d selected, slot %d playing: %s (plaits %d)"
- " (MODEL offset)\n", sl + 1, sp1_pui_eslot() + 1,
- sp1_pui_engine_name(), sp1_pui_engine());
+ printk("ENGINE %s selected, %s playing: %s (plaits %d)"
+ " (MODEL offset)\n", slot_label(sl),
+ slot_label(sp1_pui_eslot()), sp1_pui_engine_name(),
+ sp1_pui_engine());
} else {
- printk("ENGINE slot %d: %s (plaits %d)\n", sl + 1,
+ printk("ENGINE %s: %s (plaits %d)\n", slot_label(sl),
sp1_pui_engine_name(), sp1_pui_engine());
}
}
@@ -868,6 +970,250 @@ static void marbles_buttons(bool fnc, uint32_t dt)
#endif
/* Survives a warm reset so a crash leaves a trace for the next boot. */
+#if defined(CONFIG_SP1_FRESH)
+/* ---- the fresh format holds ON entry (M6 #43, Adara 2026-10-07) ----
+ * "Formatting the eMMC should hold up the rest of the UI while the device is being turned
+ * on. We can still turn the SP-1 off during the process in case it hangs, using the 30s
+ * SHFT hold backstop." So between queuing the storage job and starting audio, main waits
+ * here: through the check (~0.1 s, nothing drawn), and through a format (several seconds)
+ * with the track row as a progress bar, ending in two 0 -> 100 % flickers and a quick
+ * fade into the page (sp1_ui_timing.h). A normal image never formats and never waits.
+ *
+ * ⚠️ POWER: sp1_power_tick() runs every tick with "••", so the 30 s backstop works exactly
+ * as in the ON loop -- it is evaluated first and unconditionally (rule 5a). Only the
+ * ordinary 3 s gesture is held off, through the existing shift suppression, because a
+ * format must not be cut short by an ordinary press (Adara). If the backstop completes
+ * while plugged in, sp1_power_tick() has already quiesced (which stops the format) and
+ * this returns false: the caller goes to STANDBY. Unplugged it powers off itself.
+ * The watchdog is fed here, by main -- never by the storage thread (sp1_emmc.h). */
+static bool storage_gate(void)
+{
+ int64_t last = k_uptime_get();
+ bool announced = false;
+ uint32_t end_ms = 0u; /* into the completion animation */
+
+ for (;;) {
+ sp1_wdt_feed();
+ const int64_t now = k_uptime_get();
+ int64_t delta = now - last;
+ last = now;
+ if (delta < 1) {
+ delta = 1;
+ } else if (delta > 4 * TICK_MS) {
+ delta = 4 * TICK_MS;
+ }
+ const uint32_t dt = (uint32_t)delta;
+
+ const bool fnc = sp1_fnc_pressed();
+ if (fnc) {
+ (void)sp1_shift_used(); /* no 3 s shutdown mid-format; the backstop stays */
+ }
+ const enum sp1_power_result pwr = sp1_power_tick(dt, fnc);
+ if (pwr == SP1_PWR_TO_STANDBY) {
+ printk("STORE format interrupted by the 30 s hold -- STANDBY\n");
+ return false;
+ }
+ const bool row_free = (pwr != SP1_PWR_ANIMATING);
+ sp1_console_poll(dt, "FORMAT");
+
+ const enum sp1_store_phase ph = sp1_store_phase();
+ if (ph == SP1_STORE_FORMATTING) {
+ if (!announced) {
+ printk("STORE formatting: the UI waits; only the 30 s \"••\" hold "
+ "powers off\n");
+ announced = true;
+ }
+ if (row_free) {
+ sp1_led_bar(SP1_ROW_TRACK, sp1_store_progress(), 255u);
+ }
+ } else if (ph == SP1_STORE_READY) {
+ const enum sp1_store_format fr = sp1_store_format_result();
+ if (fr == SP1_STORE_FMT_NONE) {
+ return true; /* nothing to show */
+ }
+ if (fr == SP1_STORE_FMT_FAILED) {
+ /* No flicker: the bar as it stood, faded into the page. */
+ uint8_t lv[4];
+ const uint32_t p = sp1_store_progress();
+ for (int i = 0; i < 4; i++) {
+ const uint32_t lo = (uint32_t)i * 255u / 4u;
+ const uint32_t hi = (uint32_t)(i + 1) * 255u / 4u;
+ lv[i] = (uint8_t)(p >= hi ? 255u
+ : (p > lo ? (p - lo) * 255u / (hi - lo) : 0u));
+ }
+ sp1_display_flash(lv, 0u, SP1_FMT_FAIL_FADE_MS);
+ return true;
+ }
+ /* Done: off, on, off, on -- then full into the page. */
+ end_ms += dt;
+ const uint32_t step = end_ms / SP1_FMT_FLICKER_MS;
+ if (step >= 4u) {
+ static const uint8_t full[4] = { 255u, 255u, 255u, 255u };
+ sp1_display_flash(full, 0u, SP1_FMT_DONE_FADE_MS);
+ return true;
+ }
+ if (row_free) {
+ sp1_led_bar(SP1_ROW_TRACK, (step & 1u) ? 255u : 0u, 255u);
+ }
+ }
+ /* SP1_STORE_CHECKING: draw nothing -- the power-on fill finishes fading. */
+
+ sp1_led_tick(dt);
+ k_msleep(TICK_MS);
+ }
+}
+#endif
+
+#if defined(CONFIG_SP1_STORAGE) && defined(CONFIG_SP1_PLAITS)
+/* ---- PRST (M6, #50): ON waits for the slots, shutdown saves one ----
+ * Adara: "Hold ON entry until the four slots are read, with a time limit of 10 seconds. If it
+ * can't load from storage, disable PRST and move to default patch." The storage thread reads
+ * them in the ON job (sp1_store.h); main waits here, between the fresh format and audio, with
+ * the power path exactly as in storage_gate(): sp1_power_tick() every tick, so the 30 s
+ * backstop is untouched (rule 5a), and the ordinary 3 s gesture held off by shift
+ * suppression. Nothing is drawn: the power-on fill finishes fading.
+ *
+ * g_prst_on is decided HERE, once per ON session: an answer that arrives after the limit is
+ * ignored, and with PRST off nothing is loaded and nothing is saved. */
+static bool g_prst_on;
+static int g_prst_slot;
+
+static bool prst_gate(void)
+{
+ int64_t last = k_uptime_get();
+ uint32_t waited = 0u;
+ g_prst_on = false;
+ for (;;) {
+ const enum sp1_store_prst st = sp1_store_prst();
+ if (st == SP1_STORE_PRST_READY) {
+ g_prst_on = true;
+ g_prst_slot = sp1_store_prst_current();
+ printk("PRST on: slot %d, read in %u ms\n", g_prst_slot + 1, (unsigned)waited);
+ return true;
+ }
+ if (st == SP1_STORE_PRST_OFF) {
+ printk("PRST off this session: the patch in memory, nothing saved\n");
+ return true;
+ }
+ if (waited >= SP1_PRST_LOAD_MS) {
+ printk("PRST off this session: the slots took over %u ms\n",
+ (unsigned)SP1_PRST_LOAD_MS);
+ return true;
+ }
+
+ sp1_wdt_feed();
+ const int64_t now = k_uptime_get();
+ int64_t delta = now - last;
+ last = now;
+ if (delta < 1) {
+ delta = 1;
+ } else if (delta > 4 * TICK_MS) {
+ delta = 4 * TICK_MS;
+ }
+ const uint32_t dt = (uint32_t)delta;
+ const bool fnc = sp1_fnc_pressed();
+ if (fnc) {
+ (void)sp1_shift_used(); /* no 3 s shutdown while loading; the backstop stays */
+ }
+ if (sp1_power_tick(dt, fnc) == SP1_PWR_TO_STANDBY) {
+ printk("PRST load interrupted by the 30 s hold -- STANDBY\n");
+ return false;
+ }
+ sp1_console_poll(dt, "PRST");
+ sp1_led_tick(dt);
+ k_msleep(TICK_MS);
+ waited += dt;
+ }
+}
+
+/* Load a slot from RAM. The faders do not move; pickup catches them up (Adara, as after a
+ * rip). Safe while audio runs: the same calls a rip makes, and the output / burst / drive
+ * changes are slewed by the synth as from the buttons. */
+static void prst_load(const struct sp1_prst *p)
+{
+ sp1_pui_put(&p->plaits);
+ sp1_mui_put(&p->marbles);
+ g_out_mode = (uint8_t)p->out_mode;
+ sp1_synth_set_output((enum sp1_synth_output)g_out_mode);
+ g_burst_div = (uint8_t)p->burst_div;
+ sp1_synth_set_burst_div(1u << g_burst_div);
+ sp1_synth_set_drive(p->drive);
+}
+
+/* At ON, before audio starts. Wakes always comes up in PLAITS (Adara: the module and page
+ * are not part of a slot). */
+static void prst_apply(const struct sp1_prst *p)
+{
+ prst_load(p);
+ g_module = SP1_MODULE_PLAITS;
+}
+
+/* Every PRST feature and key combination asks this (Adara, #43/#50): a volume that mounted
+ * AND a slot loaded this ON session. UNKNOWN counts as no. */
+static bool prst_available(void)
+{
+ return g_prst_on && sp1_store_volume() == SP1_STORE_VOL_OK;
+}
+
+/* "••" + PLAY's next slot (#50): loaded at once from RAM, the old slot's unsaved changes
+ * dropped. The module and page on show are kept. Saved at the next shutdown. */
+static void prst_select(int slot)
+{
+ g_prst_slot = slot;
+ prst_load(sp1_store_prst_slot(slot));
+ printk("PRST slot %d: %s%s\n", slot + 1, sp1_pui_engine_name(),
+ sp1_pui_offlist(sp1_pui_slot()) ? " (not on the engine list)" : "");
+}
+
+static void prst_gather(struct sp1_prst *p)
+{
+ sp1_pui_get(&p->plaits);
+ sp1_mui_get(&p->marbles);
+ p->out_mode = g_out_mode;
+ p->burst_div = g_burst_div;
+ p->drive = sp1_synth_drive();
+}
+
+/* ---- the save: sp1_power_tick() calls this when the shutdown animation completes ----
+ * 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)
+{
+ if (!g_prst_on) {
+ 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;
+ }
+ 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));
+}
+#elif defined(CONFIG_SP1_PLAITS)
+/* Without storage there is no PRST: "••" + PLAY is ROTC alone. */
+#define SP1_PRST_SLOTS 4
+static int g_prst_slot;
+static bool prst_available(void) { return false; }
+static void prst_select(int slot) { ARG_UNUSED(slot); }
+#endif
+
static __noinit uint32_t g_fault_key;
static __noinit uint32_t g_fault_reason;
static __noinit uint32_t g_fault_pc;
@@ -1019,10 +1365,16 @@ int main(void)
/* The audio thread is created here and parks immediately. It does no work
* until ON starts it, and it is never created on a tap-and-release wake. */
sp1_audio_init();
+#if defined(CONFIG_SP1_STORAGE)
+ sp1_store_init(); /* the thread parks until an ON entry queues a job */
+#endif
#if defined(CONFIG_SP1_PLAITS)
sp1_pui_init(); /* page defaults: once per boot, kept across ON */
sp1_mui_init();
#endif
+#if defined(CONFIG_SP1_STORAGE) && defined(CONFIG_SP1_PLAITS)
+ sp1_power_set_save_hook(prst_save_at_shutdown); /* PRST (#50) */
+#endif
/* ---- top-level state machine ----
* STANDBY: plugged in and not running. ON: running.
@@ -1062,6 +1414,29 @@ int main(void)
* cannot be mis-assembled. Off once the tables exist. */
sp1_controls_reset_buttons();
+#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_store_on_enter();
+#if defined(CONFIG_SP1_FRESH)
+ /* The fresh image's format holds ON entry, before audio (storage_gate). */
+ if (!storage_gate()) {
+ standby = true; /* the 30 s backstop, plugged in */
+ continue;
+ }
+#endif
+#if defined(CONFIG_SP1_PLAITS)
+ /* PRST (#50): the current slot, read by the same job, applied before audio. */
+ if (!prst_gate()) {
+ standby = true; /* the 30 s backstop, plugged in */
+ continue;
+ }
+ if (g_prst_on) {
+ prst_apply(sp1_store_prst_slot(g_prst_slot));
+ }
+#endif
+#endif
+
/* ---- M2: audio up on every entry to ON ----
* The way into STANDBY powers the codecs, the amp and the oscillator
* down (sp1_quiesce_peripherals), so they are brought back here each
@@ -1114,7 +1489,11 @@ int main(void)
sp1_rg_init(&unpatch_eat);
burst_n0 = 0u;
rip_ms = 0u;
+ rip_armed = false;
+ rip_glyph = false;
rip_show_page = false;
+ prst_showing = false;
+ prst_changed = false;
sp1_synth_set_burst_div(1u << g_burst_div);
sp1_synth_set_output((enum sp1_synth_output)g_out_mode);
#if defined(CONFIG_SP1_MIDI)
@@ -1478,95 +1857,147 @@ int main(void)
}
}
- /* ---- "••" + PLAY held: rip out the cables ----
- * ⚠️ A FULL PATCH WIPE of the module on show since M4d; through M4b
- * it kept the engine and the BASE faders. docs/DEFAULTS.md is the
- * spec. 3 s, with the rip animation owning the track row; letting go
- * before the end cancels. A "••" + PLAY press is a shift use, so it
- * can never start a power-off.
+ /* ---- "••" + PLAY: PRST and ROTC (Adara, #50) ----
+ * 1. PLAY pressed with "••" held: the current slot's glyph at
+ * once, its LED ramping at 10 Hz for 1.6 s, then the page.
+ * 2. PLAY pressed again while it shows: the NEXT slot (4 -> 1),
+ * loaded at once -- the old slot's unsaved changes dropped, the
+ * faders not moved (pickup) -- and its glyph shown. No
+ * double-tap delay, so slots can be browsed.
+ * 3. PLAY kept held from a press that did not change slot: ROTC,
+ * 3 s in all -- the glyph, black, a rise to full, the Unpatch
+ * animation, the wipe (rotc_levels, sp1_ui_timing.h).
+ * 4. After a slot change, no ROTC until "••" is released.
+ * 5. Letting go once ROTC's animation has begun (past the glyph)
+ * fades back to the SHIFT screen; nothing is wiped.
+ * 6. Letting go of "••" leaves the browser at once: the glyph ends,
+ * PLAY no longer changes slot, the page fades back in.
+ * Every PRST part asks prst_available() (the volume is OK and this
+ * ON session loaded a slot); without it this is ROTC alone, the glyph's
+ * 1.6 s a slow fade to black instead (Adara; rotc_or_fade_levels).
*
- * Only the FOREGROUND module is wiped (Adara) -- and the page you
- * are standing on inside it is kept. The soft-clip drive is the one
- * exception that is cleared from either module, because "••" + VOL
- * reaches it from both. */
- if (fnc && sp1_button_held(SP1_BTN_PLAY) && !shutdown_active) {
- if (rip_ms < SP1_RIP_HOLD_MS) {
- rip_ms += dt;
- if (rip_ms >= SP1_RIP_HOLD_MS) {
- if (marbles) {
- sp1_mui_rip();
- /* Re-seed AND re-draw the DEJA VU
- * loop, deferred into the audio
- * thread so it cannot race the
- * generators. The clock keeps
- * running and its phase jumps once
- * (Adara, M4d). */
- sp1_marbles_reseed(
- k_cycle_get_32());
- g_seeded = true;
- printk("RIP marbles: every output "
- "disconnected, %d BPM, %s, "
- "re-seeded%s\n",
- (int)sp1_mui_bpm(),
- sp1_marbles_model_name(
- sp1_mui_model()),
- sp1_marbles_running()
- ? " (clock still running)" : "");
- } else {
- sp1_pui_rip();
- /* ⚠️ The drive is a PLAITS parameter
- * and only a PLAITS rip clears it
- * (Adara, M4e). M4d cleared it from
- * either module on the grounds that
- * "••" + VOL reaches it from both --
- * but Marbles makes no audio, so the
- * drive is not part of its patch and
- * a Marbles rip has no business
- * touching it. */
- sp1_synth_set_drive(0);
- /* PLAITS-side output controls go
- * back too (docs/DEFAULTS.md).
- * VOL is deliberately kept. */
- g_out_mode = SP1_OUT_MAIN;
- sp1_synth_set_output(
- (enum sp1_synth_output)g_out_mode);
- g_burst_div = 5u; /* 1/32 */
- sp1_synth_set_burst_div(
- 1u << g_burst_div);
- printk("RIP plaits: patch wiped -- %s, "
- "faders neutral, attenuverters 0, "
- "quantizer off, drive off, OUT, "
- "1/32\n",
- sp1_pui_engine_name());
- }
- static const uint8_t dark[4] = { 0u, 0u, 0u, 0u };
- sp1_display_flash(dark, 0u,
- SP1_RIP_FADEBACK_MS);
- /* ⚠️ Fade back to the PAGE, not the SHIFT
- * layer "••" would otherwise show: the rip
- * has just zeroed every attenuverter, which
- * draws DARK, so the fade went black -> black
- * and the rip looked unfinished until "••"
- * was let go (issue #4). */
- rip_show_page = true;
+ * ROTC is a FULL PATCH WIPE of the module on show (docs/DEFAULTS.md);
+ * the page you are standing on is kept. A "••" + PLAY press is a
+ * shift use, so it can never start a power-off. */
+ const bool play_down = sp1_button_held(SP1_BTN_PLAY);
+ if (fnc && sp1_button_pressed(SP1_BTN_PLAY) && !shutdown_active) {
+ if (prst_showing && prst_available()) {
+ prst_select((g_prst_slot + 1) % SP1_PRST_SLOTS);
+ prst_changed = true;
+ prst_show_ms = 0u; /* the new slot's glyph */
+ rip_armed = false;
+ } else {
+ prst_showing = prst_available();
+ prst_show_ms = 0u;
+ rip_armed = !prst_changed;
+ rip_glyph = prst_showing;
+ }
+ rip_ms = 0u;
+ }
+
+ if (rip_armed && fnc && play_down && !shutdown_active) {
+ rip_ms += dt;
+ if (rip_ms >= SP1_PRST_GLYPH_MS) {
+ prst_showing = false; /* ROTC's animation now */
+ }
+ if (rip_ms >= SP1_RIP_HOLD_MS) {
+ rip_armed = false;
+ if (marbles) {
+ sp1_mui_rip();
+ /* The rip routes X2 to V/Oct (#50), so the
+ * M4b interlock applies: the quantizer off,
+ * the range opened. */
+ voct_took_over(SP1_DEST_VOCT);
+ /* Re-seed AND re-draw the DEJA VU loop,
+ * deferred into the audio thread so it cannot
+ * race the generators. The clock keeps running
+ * and its phase jumps once (Adara, M4d). */
+ sp1_marbles_reseed(k_cycle_get_32());
+ g_seeded = true;
+ printk("RIP marbles: t2 -> TRIG, X2 -> V/Oct, the rest "
+ "out, %d BPM, %s, re-seeded%s\n",
+ (int)sp1_mui_bpm(),
+ sp1_marbles_model_name(sp1_mui_model()),
+ sp1_marbles_running()
+ ? " (clock still running)" : "");
} else {
- uint8_t lv[4];
- rip_levels(rip_ms, lv);
- sp1_display_flash(lv, 100u, SP1_RIP_CANCEL_FADE_MS);
+ sp1_pui_rip();
+ /* ⚠️ The drive is a PLAITS parameter and only a
+ * PLAITS rip clears it (Adara, M4e): Marbles
+ * makes no audio, so the drive is not part of
+ * its patch. */
+ sp1_synth_set_drive(SP1_PRST_DEF_DRIVE);
+ /* PLAITS-side output controls go back too
+ * (docs/DEFAULTS.md). VOL is deliberately kept. */
+ g_out_mode = SP1_PRST_DEF_OUT;
+ sp1_synth_set_output(
+ (enum sp1_synth_output)g_out_mode);
+ g_burst_div = SP1_PRST_DEF_BURST; /* 1/32 */
+ sp1_synth_set_burst_div(1u << g_burst_div);
+ printk("RIP plaits: patch wiped -- %s, faders "
+ "neutral, attenuverters 0, quantizer off, "
+ "drive off, OUT, 1/32\n",
+ sp1_pui_engine_name());
}
+ static const uint8_t dark[4] = { 0u, 0u, 0u, 0u };
+ sp1_display_flash(dark, 0u, SP1_RIP_FADEBACK_MS);
+ /* ⚠️ Fade back to the PAGE, not the SHIFT layer "••"
+ * would otherwise show: the rip has just zeroed every
+ * attenuverter, which draws DARK, so the fade went
+ * black -> black and the rip looked unfinished until
+ * "••" was let go (issue #4). */
+ rip_show_page = true;
+ } else if (rip_ms >= SP1_PRST_GLYPH_MS || !rip_glyph) {
+ uint8_t lv[4];
+ rotc_or_fade_levels(rip_ms, marbles, lv);
+ sp1_display_flash(lv, 100u, SP1_RIP_CANCEL_FADE_MS);
}
- } else {
- if (rip_ms > 0u && rip_ms < SP1_RIP_HOLD_MS) {
- /* cancelled: hand the row straight back */
+ } else if (rip_armed) {
+ /* PLAY (or "••") let go before the wipe. Within the glyph it
+ * was a tap: the glyph carries on. Past it -- or anywhere
+ * with PRST off, where the slow fade is ROTC's own -- ROTC
+ * is cancelled: back to the SHIFT screen. */
+ if (rip_ms >= SP1_PRST_GLYPH_MS || !rip_glyph) {
uint8_t lv[4];
- rip_levels(rip_ms, lv);
+ rotc_or_fade_levels(rip_ms, marbles, lv);
sp1_display_flash(lv, 0u, SP1_RIP_CANCEL_FADE_MS);
printk("RIP cancelled\n");
}
+ rip_armed = false;
rip_ms = 0u;
- /* The gesture is over: the ordinary layer rules again. */
+ }
+ if (!(fnc && play_down)) {
+ /* The rip's hold is over: the ordinary layer rules again. */
rip_show_page = false;
}
+ if (!fnc) {
+ prst_changed = false; /* (4) */
+ if (prst_showing) {
+ /* (6) Letting go of "••" leaves the browser (Adara): the
+ * glyph ends, a PLAY tap no longer changes slot, and the
+ * page you were on fades back in. */
+ prst_showing = false;
+ uint8_t lv[4];
+ prst_glyph_levels(g_prst_slot, prst_show_ms, lv);
+ sp1_display_flash(lv, 0u, SP1_PRST_FADEBACK_MS);
+ }
+ }
+
+ /* An off-list engine's flash, if one is running (engine_flash). */
+ offlist_glyph_tick(dt);
+
+ /* The slot glyph, while it shows (and ROTC has not taken the row). */
+ if (prst_showing) {
+ prst_show_ms += dt;
+ uint8_t lv[4];
+ prst_glyph_levels(g_prst_slot, prst_show_ms, lv);
+ if (prst_show_ms >= SP1_PRST_GLYPH_MS) {
+ prst_showing = false;
+ sp1_display_flash(lv, 0u, SP1_PRST_FADEBACK_MS);
+ } else {
+ sp1_display_flash(lv, 100u, SP1_PRST_FADEBACK_MS);
+ }
+ }
/* ================= UNPATCH ("••" + Tn held, M4e) =================
* Runs BEFORE the button handlers. A commit arms `unpatch_eat`, which
@@ -1676,9 +2107,7 @@ int main(void)
if (marbles) {
g_module = SP1_MODULE_PLAITS;
sp1_pui_resume(raw, fnc);
- uint8_t elv[4];
- sp1_pui_engine_leds(elv);
- sp1_display_engine(elv);
+ engine_flash();
sp1_playrow_set_fg(SP1_FG_METER);
printk("MODULE plaits (%s)\n", sp1_pui_engine_name());
} else {
@@ -1747,7 +2176,7 @@ int main(void)
#if defined(CONFIG_SP1_MIDI)
/* ---- MIDI (M5a): the prompt, and the control-loop smoothing of
* the offsets the two UIs are about to read ---- */
- midi_tick(dt, shutdown_active || rip_ms > 0u ||
+ midi_tick(dt, shutdown_active || rip_ms > 0u || prst_showing ||
unpatch_ms >= SP1_UNPATCH_START_MS);
sp1_midi_main_tick(dt);
/* Pickup shared / takeover: the CCs move the stored values of
diff --git a/firmware/src/sp1_board.h b/firmware/src/sp1_board.h
index 6e686ad..168889d 100644
--- a/firmware/src/sp1_board.h
+++ b/firmware/src/sp1_board.h
@@ -41,6 +41,14 @@
#define SP1_OSC_EN_PIN 13u
#define SP1_EMMC_VCCQ_PORT NRF_P0 /* eMMC I/O rail, active high */
#define SP1_EMMC_VCCQ_PIN 14u
+/* eMMC bus (M6, #43): 1-bit MMC, bit-banged -- the nRF52840 has no SD/MMC peripheral.
+ * CLK, DAT0 and CMD must stay on port 0: sp1_emmc.c clocks data through NRF_P0's
+ * registers directly. Used only by sp1_emmc.c. */
+#define SP1_EMMC_CLK_PIN 6u /* P0.06 */
+#define SP1_EMMC_DAT0_PIN 7u /* P0.07 */
+#define SP1_EMMC_CMD_PIN 8u /* P0.08 */
+#define SP1_EMMC_RST_PORT NRF_P1 /* RST_n, active low */
+#define SP1_EMMC_RST_PIN 8u /* P1.08 */
#define SP1_BT_RST_PORT NRF_P0 /* CYBT module, active low */
#define SP1_BT_RST_PIN 10u
diff --git a/firmware/src/sp1_display.c b/firmware/src/sp1_display.c
index b1e77fc..d35263c 100644
--- a/firmware/src/sp1_display.c
+++ b/firmware/src/sp1_display.c
@@ -89,6 +89,7 @@ static uint8_t eng_level[4];
static uint32_t eng_ms; /* 0 = inactive; counts UP */
static uint32_t eng_hold = SP1_DISP_ENGINE_HOLD_MS;
static uint32_t eng_fade = SP1_DISP_ENGINE_FADE_MS;
+static uint32_t eng_count; /* every flash: sp1_display_flash_count() */
void sp1_display_flash(const uint8_t level[4], uint32_t hold_ms, uint32_t fade_ms)
{
@@ -98,6 +99,12 @@ void sp1_display_flash(const uint8_t level[4], uint32_t hold_ms, uint32_t fade_m
eng_hold = hold_ms;
eng_fade = fade_ms > 0u ? fade_ms : 1u;
eng_ms = 1u; /* (re)start: hold, then fade */
+ eng_count++;
+}
+
+uint32_t sp1_display_flash_count(void)
+{
+ return eng_count;
}
void sp1_display_engine(const uint8_t level[4])
diff --git a/firmware/src/sp1_display.h b/firmware/src/sp1_display.h
index a45450c..10e86dd 100644
--- a/firmware/src/sp1_display.h
+++ b/firmware/src/sp1_display.h
@@ -77,6 +77,9 @@ void sp1_display_engine(const uint8_t level[4]);
* SP1_DISP_ENGINE_HOLD_MS / SP1_DISP_ENGINE_FADE_MS. Calling it every tick with a
* hold longer than a tick keeps `level` on the row (the rip animation). */
void sp1_display_flash(const uint8_t level[4], uint32_t hold_ms, uint32_t fade_ms);
+/* How many flashes have been started: an animation that redraws itself every tick compares
+ * it with its own last call, and stands down when something else took the row (#50). */
+uint32_t sp1_display_flash_count(void);
/* Resting display when nothing else is showing. Defaults to dark. Identical
* storage to sp1_display_meter(); use whichever name says what you mean. */
diff --git a/firmware/src/sp1_emmc.c b/firmware/src/sp1_emmc.c
new file mode 100644
index 0000000..80de8b9
--- /dev/null
+++ b/firmware/src/sp1_emmc.c
@@ -0,0 +1,880 @@
+/*
+ * wakes-sp1 — the SP-1's eMMC (M6, #43). See sp1_emmc.h.
+ *
+ * Derived from chattock/sp1-tape-looper firmware/src/sp1_emmc.c, Copyright (c) 2026
+ * chattock, MIT, which is ported from timknapen/SP-1-dev emmc.c, Copyright (c) 2026
+ * Tim Knapen, MIT. Licence texts: LICENSES/MIT-sp1-tape-looper.txt and
+ * LICENSES/MIT-SP-1-dev.txt.
+ *
+ * ---- the sampling points, which are the whole trick ----
+ * They are the tape-looper's, unchanged, because they are what works on this board.
+ * The card changes CMD and DAT0 after a FALLING clock edge and the host reads them
+ * while CLK is high, so:
+ * - a response is found by pulsing CLK and reading CMD after the falling edge. The
+ * first read with CLK high afterwards sees the START BIT AGAIN -- so a captured
+ * response begins with its start bit: index 0 = start, 1 = transmission, 2..7 =
+ * the command index (or 111111), then the payload MSB first.
+ * (The tape-looper's own R1 parsing -- READY_FOR_DATA = r1[3] & 0x01,
+ * SWITCH_ERROR = r1[4] & 0x80 -- is only right with this alignment.)
+ * - a data block is found by reading DAT0 with CLK high; the bit after the start bit
+ * arrives after the next falling edge, so there is no re-read there.
+ * - a write puts each bit on DAT0 while CLK is low; the card latches it on the
+ * rising edge. The card's CRC-status token and its busy are read like data.
+ * Hardware 2026-10-07 (logs/sp1-20261007-152119.log, -173828.log): the CID's CRC7
+ * matched at alignment 0; reads, writes and a FAT32 format ran with no error.
+ *
+ * ---- fast transfer (M6, Adara: "yes" to doing it with drive mode) ----
+ * The tape-looper's, again: the 512-byte payloads (and their CRC16) ride SPIM3 + EasyDMA
+ * -- SPI mode 0 is the same wire format as eMMC DAT0 at default speed -- while the start
+ * bit hunt, the CRC-status token, the busy and every command stay bit-banged. SPIM3 is the
+ * only SPIM above 8 MHz and nothing else in Wakes uses it. We run it at 16 MHz, inside the
+ * card's 26 MHz default-speed limit (the looper's 32 MHz overclock glitched at 24 kHz).
+ * After identification, commands drop the 1 us half-period (the looper's CMDFAST: same
+ * edges, register-speed). Multi-block CMD18 / CMD25 + CMD12 replace one command per block.
+ * EVERY fast step has a slow one behind it: a failed multi-block transfer finishes block by
+ * block, a failed block is retried bit-banged (then at the 1 us clock), and a command that
+ * misses its response at speed is retried at the identification clock.
+ * ⚠️ nRF52840 anomaly 198 (SPIM3 TX data can be corrupted by CPU access to the same RAM
+ * block): harmless here BY DESIGN -- the card checks the CRC16 we computed from the source
+ * buffer before the DMA, rejects a corrupted block (token 101), and the block is retried.
+ */
+#include "sp1_emmc.h"
+#include "sp1_board.h"
+
+#include
+#include
+#include
+
+#define PIN_CLK NRF_GPIO_PIN_MAP(0, SP1_EMMC_CLK_PIN)
+#define PIN_DAT0 NRF_GPIO_PIN_MAP(0, SP1_EMMC_DAT0_PIN)
+#define PIN_CMD NRF_GPIO_PIN_MAP(0, SP1_EMMC_CMD_PIN)
+#define PIN_RST NRF_GPIO_PIN_MAP(1, SP1_EMMC_RST_PIN) /* SP1_EMMC_RST_PORT = NRF_P1 */
+#define PIN_VCCQ NRF_GPIO_PIN_MAP(0, SP1_EMMC_VCCQ_PIN) /* SP1_EMMC_VCCQ_PORT = NRF_P0 */
+
+/* CLK, DAT0 and CMD through port 0's registers. A few NOPs of settle around each edge
+ * (the tape-looper's EDGE_SETTLE; JEDEC's minimum clock high/low is 10 ns, a NOP is
+ * 15.6 ns). The "slow" variants use a 1 us half-period: identification (400 kHz limit)
+ * and the last retry of anything. */
+#define P0_CLK (1u << SP1_EMMC_CLK_PIN)
+#define P0_DAT0 (1u << SP1_EMMC_DAT0_PIN)
+#define P0_CMD (1u << SP1_EMMC_CMD_PIN)
+#define CLK_HI() (NRF_P0->OUTSET = P0_CLK)
+#define CLK_LO() (NRF_P0->OUTCLR = P0_CLK)
+#define DAT_HI() (NRF_P0->OUTSET = P0_DAT0)
+#define DAT_LO() (NRF_P0->OUTCLR = P0_DAT0)
+#define DAT0() ((NRF_P0->IN >> SP1_EMMC_DAT0_PIN) & 1u)
+#define CMD_IN() ((NRF_P0->IN >> SP1_EMMC_CMD_PIN) & 1u)
+#define SETTLE() __asm__ volatile("nop\nnop\nnop")
+#define SLOW_HALF_US 1u
+
+#define INIT_TIMEOUT_MS 1000u /* CMD1 until ready: JEDEC's 1 s */
+#define DATA_TIMEOUT_MS 100u /* start bit of a data block */
+#define BUSY_TIMEOUT_MS 500u /* programming busy after a write / CMD12 */
+
+#define R1_BITS_DATA 38u /* a response followed by a data block (send_cmd) */
+#define R1_BITS 48u
+#define R2_BITS 138u /* 136 + 2 spare, for the CID alignment check */
+
+/* Card-status bits in CMD24/25's own R1 that mean "this write must not go ahead": 31
+ * ADDRESS_OUT_OF_RANGE, 30 ADDRESS_MISALIGN, 29 BLOCK_LEN_ERROR, 26 WP_VIOLATION, 25
+ * DEVICE_IS_LOCKED. Deliberately NOT the whole JEDEC error set: COM_CRC_ERROR and
+ * ILLEGAL_COMMAND report the PREVIOUS command, so after any retried command they would
+ * refuse a perfectly good write. */
+#define WRITE_FATAL 0xe6000000u
+
+/* How a data block moves: SPIM3 DMA, bit-banged at register speed, or at 1 us. */
+enum mode { M_SPIM, M_FAST, M_SLOW };
+
+static bool ready;
+static volatile bool aborted;
+static bool cmd_fast; /* identification done: commands at register speed */
+static bool spim_on; /* SPIM3 configured (power_down undoes it) */
+static uint32_t rca; /* relative card address, already << 16 */
+static uint32_t sectors;
+static struct sp1_emmc_stats st;
+
+/* ---------------------------------------------------------------- CRCs */
+
+static uint8_t crc7(const uint8_t *d, uint32_t n)
+{
+ uint8_t crc = 0;
+ for (uint32_t i = 0; i < n; i++) {
+ for (int b = 7; b >= 0; b--) {
+ crc <<= 1;
+ if ((((d[i] >> b) & 1u) ^ ((crc >> 7) & 1u)) != 0u) {
+ crc ^= 0x09;
+ }
+ crc &= 0x7f;
+ }
+ }
+ return (uint8_t)((crc << 1) | 1u); /* with the end bit, as it sits in a frame */
+}
+
+/* CRC-16/XMODEM (0x1021), table-driven: the bit loop costs ~0.5 ms a block, which at
+ * fast-transfer rates is most of the time. The table is built at init and checked
+ * against the standard answer ("123456789" -> 0x31C3); init fails if it is wrong. */
+static uint16_t crc_tab[256];
+
+static void crc16_build(void)
+{
+ for (uint32_t i = 0; i < 256u; i++) {
+ uint16_t c = (uint16_t)(i << 8);
+ for (int b = 0; b < 8; b++) {
+ c = (c & 0x8000u) ? (uint16_t)((c << 1) ^ 0x1021u) : (uint16_t)(c << 1);
+ }
+ crc_tab[i] = c;
+ }
+}
+
+static uint16_t crc16(const uint8_t *d, uint32_t n)
+{
+ uint16_t crc = 0;
+ while (n--) {
+ crc = (uint16_t)((crc << 8) ^ crc_tab[((crc >> 8) ^ *d++) & 0xffu]);
+ }
+ return crc;
+}
+
+/* ---------------------------------------------------------------- SPIM3 */
+
+#define SPIM_FREQ_16M 0x0A000000u
+
+static void spim_setup(void)
+{
+ NRF_SPIM3->ENABLE = 0;
+ NRF_SPIM3->PSEL.SCK = PIN_CLK;
+ NRF_SPIM3->PSEL.MOSI = 0xffffffffu; /* attached per transfer */
+ NRF_SPIM3->PSEL.MISO = 0xffffffffu;
+ NRF_SPIM3->PSEL.CSN = 0xffffffffu;
+ NRF_SPIM3->FREQUENCY = SPIM_FREQ_16M;
+ NRF_SPIM3->CONFIG = 0; /* MSB first, CPOL 0 / CPHA 0 (mode 0) */
+ NRF_SPIM3->ORC = 0xff; /* idle high */
+ spim_on = true;
+}
+
+/* One blocking DMA transfer with SPIM3 owning CLK and DAT0. On disable the pins fall
+ * back to their GPIO latches (CLK low, DAT0 as configured), so the bit-banged phases
+ * either side carry on. 516 bytes at 16 MHz is ~260 us. Bounded. */
+static bool spim_xfer(const uint8_t *tx, uint32_t txn, uint8_t *rx, uint32_t rxn)
+{
+ NRF_SPIM3->PSEL.MOSI = tx ? PIN_DAT0 : 0xffffffffu;
+ NRF_SPIM3->PSEL.MISO = rx ? PIN_DAT0 : 0xffffffffu;
+ NRF_SPIM3->ENABLE = 7;
+ NRF_SPIM3->TXD.PTR = (uint32_t)tx;
+ NRF_SPIM3->TXD.MAXCNT = tx ? txn : 0u;
+ NRF_SPIM3->RXD.PTR = (uint32_t)rx;
+ NRF_SPIM3->RXD.MAXCNT = rx ? rxn : 0u;
+ NRF_SPIM3->EVENTS_END = 0;
+ NRF_SPIM3->TASKS_START = 1;
+ const uint32_t c0 = k_cycle_get_32();
+ while (NRF_SPIM3->EVENTS_END == 0u &&
+ k_cyc_to_us_floor32(k_cycle_get_32() - c0) < 5000u) {
+ }
+ /* ⚠️ Read END AGAIN after the time check. This thread is the lowest priority there
+ * is: at ~70 % audio load it can be held off for several ms BETWEEN reading END and
+ * reading the clock, and then a transfer that finished meanwhile looked timed out.
+ * Hardware 2026-10-07 (logs/sp1-20261007-193746.log): 38 such false timeouts in
+ * 512 KB, each one dropping its burst to block-by-block -- data intact, speed lost. */
+ const bool done = (NRF_SPIM3->EVENTS_END != 0u);
+ if (!done) {
+ st.spim_timeouts++;
+ NRF_SPIM3->TASKS_STOP = 1;
+ }
+ NRF_SPIM3->ENABLE = 0;
+ return done;
+}
+
+/* ---------------------------------------------------------------- command phase */
+
+static inline void half(bool slow)
+{
+ if (slow) {
+ k_busy_wait(SLOW_HALF_US);
+ } else {
+ SETTLE();
+ }
+}
+
+static inline void pulse(bool slow)
+{
+ CLK_HI();
+ half(slow);
+ CLK_LO();
+ half(slow);
+}
+
+/* Send one command; capture `nbits` of the response (0 = none expected) into `resp`,
+ * MSB first, index 0 = the start bit (see the top of the file). False = no response.
+ *
+ * ⚠️ For a command followed by a data block FROM the card (CMD8, CMD17, CMD18), capture
+ * R1_BITS_DATA and no more: the block can start on DAT0 a couple of clocks after the
+ * response, and every extra clock here is one the data hunt never sees (the
+ * tape-looper found this the hard way). */
+static bool send_cmd(uint8_t index, uint32_t arg, uint8_t *resp, uint32_t nbits, bool slow)
+{
+ if (aborted) {
+ return false;
+ }
+ uint8_t f[6];
+ f[0] = (uint8_t)(0x40u | (index & 0x3fu));
+ f[1] = (uint8_t)(arg >> 24);
+ f[2] = (uint8_t)(arg >> 16);
+ f[3] = (uint8_t)(arg >> 8);
+ f[4] = (uint8_t)arg;
+ f[5] = crc7(f, 5);
+
+ /* The gap before a command, on a RELEASED line: the tail of the previous response
+ * plus JEDEC's Nrc, without driving against the card's last bits. */
+ nrf_gpio_cfg_input(PIN_CMD, NRF_GPIO_PIN_PULLUP);
+ for (int i = 0; i < 24; i++) {
+ pulse(slow);
+ }
+ NRF_P0->OUTSET = P0_CMD;
+ nrf_gpio_cfg_output(PIN_CMD);
+ for (int i = 0; i < 6; i++) {
+ for (int b = 7; b >= 0; b--) {
+ if ((f[i] >> b) & 1u) {
+ NRF_P0->OUTSET = P0_CMD;
+ } else {
+ NRF_P0->OUTCLR = P0_CMD;
+ }
+ pulse(slow);
+ }
+ }
+ nrf_gpio_cfg_input(PIN_CMD, NRF_GPIO_PIN_PULLUP);
+
+ if (nbits == 0u) {
+ return true;
+ }
+ bool found = false;
+ for (int t = 0; t < 200 && !found; t++) {
+ pulse(slow);
+ found = (CMD_IN() == 0u);
+ }
+ if (!found) {
+ return false;
+ }
+ memset(resp, 0, (nbits + 7u) / 8u);
+ for (uint32_t i = 0; i < nbits; i++) {
+ CLK_HI();
+ half(slow);
+ const uint32_t bit = CMD_IN();
+ CLK_LO();
+ half(slow);
+ resp[i / 8u] |= (uint8_t)(bit << (7u - (i % 8u)));
+ }
+ return true;
+}
+
+/* Up to 8 tries; after identification the first four are at register speed and the
+ * rest at the identification clock, so a speed problem costs time, not the command. */
+static bool send_cmd_retry(uint8_t index, uint32_t arg, uint8_t *resp, uint32_t nbits)
+{
+ for (int t = 0; t < 8 && !aborted; t++) {
+ const bool slow = !cmd_fast || t >= 4;
+ if (send_cmd(index, arg, resp, nbits, slow)) {
+ return true;
+ }
+ st.cmd_retries++;
+ if (t == 0) {
+ for (int c = 0; c < 16; c++) {
+ pulse(slow);
+ }
+ } else {
+ k_msleep(2);
+ }
+ }
+ return false;
+}
+
+/* `n` bits of a captured response from bit `first`, as an integer, MSB first. */
+static uint32_t resp_bits(const uint8_t *r, uint32_t first, uint32_t n)
+{
+ uint32_t v = 0;
+ for (uint32_t i = first; i < first + n; i++) {
+ v = (v << 1) | ((r[i / 8u] >> (7u - (i % 8u))) & 1u);
+ }
+ return v;
+}
+
+/* ---------------------------------------------------------------- data phase */
+
+/* One data block from the card, after its command's response (or the previous block of
+ * a CMD18): 512 bytes, the card's CRC16, the end bit. True only if the CRC matched. */
+static bool read_data(uint8_t *buf, enum mode m)
+{
+ const bool slow = (m == M_SLOW);
+ nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP);
+
+ /* Start-bit hunt, bit-banged. The card only moves on our clock, so stopping to look
+ * at the time can never miss it. */
+ const uint32_t t0 = k_uptime_get_32();
+ bool got = false;
+ while (!got) {
+ for (int i = 0; i < 64; i++) {
+ CLK_HI();
+ half(slow);
+ if (DAT0() == 0u) {
+ got = true; /* leave with CLK high */
+ break;
+ }
+ CLK_LO();
+ half(slow);
+ }
+ if (!got && ((k_uptime_get_32() - t0) >= DATA_TIMEOUT_MS || aborted)) {
+ st.hunt_timeouts++;
+ return false;
+ }
+ }
+ CLK_LO();
+ half(slow);
+
+ uint8_t c2[2];
+ if (m == M_SPIM) {
+ /* The start bit is consumed, so the payload and CRC are byte-aligned: two DMA
+ * receives straight into the caller's buffer and c2 (no copy). */
+ if (!spim_xfer(NULL, 0, buf, SP1_EMMC_BLOCK) || !spim_xfer(NULL, 0, c2, 2)) {
+ /* counted in spim_xfer */
+ return false;
+ }
+ } else {
+ for (uint32_t i = 0; i < SP1_EMMC_BLOCK + 2u; i++) {
+ uint32_t byte = 0;
+ for (int b = 7; b >= 0; b--) {
+ CLK_HI();
+ half(slow);
+ byte |= DAT0() << b;
+ CLK_LO();
+ half(slow);
+ }
+ if (i < SP1_EMMC_BLOCK) {
+ buf[i] = (uint8_t)byte;
+ } else {
+ c2[i - SP1_EMMC_BLOCK] = (uint8_t)byte;
+ }
+ }
+ }
+ pulse(slow); /* end bit */
+
+ if (crc16(buf, SP1_EMMC_BLOCK) != (uint16_t)((c2[0] << 8) | c2[1])) {
+ st.crc_errs++;
+ return false;
+ }
+ return true;
+}
+
+/* Wait while the card holds DAT0 low (programming). True once it lets go. The first
+ * clock here carries the token's end bit; each read comes after a falling edge and its
+ * settle, as the tape-looper's busy wait does -- read straight after the edge, it can
+ * still see the previous bit and call the card free one clock early. */
+static bool busy_wait(bool slow)
+{
+ nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP);
+ const uint32_t c0 = k_cycle_get_32();
+ const uint32_t t0 = k_uptime_get_32();
+ for (;;) {
+ for (int i = 0; i < 64; i++) {
+ pulse(slow);
+ if (DAT0() != 0u) {
+ const uint32_t us = k_cyc_to_us_floor32(k_cycle_get_32() - c0);
+ if (us > st.wr_busy_max_us) {
+ st.wr_busy_max_us = us;
+ }
+ return true;
+ }
+ }
+ const uint32_t el = k_uptime_get_32() - t0;
+ if (el >= BUSY_TIMEOUT_MS || aborted) {
+ st.busy_timeouts++;
+ return false;
+ }
+ if (el >= 1u) {
+ k_usleep(50); /* a long program: let others run */
+ }
+ }
+}
+
+/* The frame a write puts on DAT0 through SPIM3: Nwr idle (0xFF), 7 idle bits + the start
+ * bit (0xFE), the payload, its CRC16. ⚠️ It ends EXACTLY at the CRC's last bit: the end
+ * bit is clocked by hand right after, because the card's token comes 2 clocks after it
+ * and a trailing idle byte inside the DMA would let it fly past (the tape-looper). */
+static uint8_t txf[2u + SP1_EMMC_BLOCK + 2u];
+
+/* The last write_data()'s CRC-status token (-1 = none seen) and busy, for the verify
+ * trace below. */
+static int last_tok;
+static uint32_t last_busy_us;
+
+/* One data block TO the card after CMD24's response (or the previous block of a CMD25);
+ * then its CRC-status token (010 = accepted) and its busy. True only if accepted and
+ * programmed. */
+static bool write_data(const uint8_t *buf, enum mode m)
+{
+ const bool slow = (m == M_SLOW);
+ const uint16_t crc = crc16(buf, SP1_EMMC_BLOCK);
+
+ DAT_HI();
+ nrf_gpio_cfg(PIN_DAT0, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT,
+ NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE);
+ if (m == M_SPIM) {
+ txf[0] = 0xff;
+ txf[1] = 0xfe;
+ memcpy(&txf[2], buf, SP1_EMMC_BLOCK); /* also makes a flash source DMA-able */
+ txf[2u + SP1_EMMC_BLOCK] = (uint8_t)(crc >> 8);
+ txf[3u + SP1_EMMC_BLOCK] = (uint8_t)crc;
+ if (!spim_xfer(txf, sizeof(txf), NULL, 0)) {
+ nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP);
+ /* counted in spim_xfer */
+ return false;
+ }
+ } else {
+ for (int i = 0; i < 8; i++) { /* Nwr: idle high, so no early start bit */
+ half(slow);
+ pulse(slow);
+ }
+ DAT_LO(); /* start bit */
+ half(slow);
+ pulse(slow);
+ for (uint32_t i = 0; i < SP1_EMMC_BLOCK + 2u; i++) {
+ const uint32_t byte = (i < SP1_EMMC_BLOCK) ? buf[i]
+ : (i == SP1_EMMC_BLOCK ? (uint32_t)(crc >> 8) : (uint32_t)(crc & 0xffu));
+ for (int b = 7; b >= 0; b--) {
+ if ((byte >> b) & 1u) {
+ DAT_HI();
+ } else {
+ DAT_LO();
+ }
+ half(slow);
+ pulse(slow);
+ }
+ }
+ }
+ DAT_HI(); /* end bit (SPIM left DAT0 on its latch) */
+ half(slow);
+ pulse(slow);
+ nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); /* the card drives from here */
+
+ /* CRC-status token: start bit (0), three status bits, end bit. */
+ int status = -1;
+ for (int i = 0; i < 16 && status < 0; i++) {
+ CLK_HI();
+ half(slow);
+ const uint32_t start = DAT0();
+ CLK_LO();
+ half(slow);
+ if (start == 0u) {
+ status = 0;
+ for (int k = 0; k < 3; k++) {
+ CLK_HI();
+ half(slow);
+ status = (status << 1) | (int)DAT0();
+ CLK_LO();
+ half(slow);
+ }
+ }
+ }
+ /* Wait out the busy whatever the token said: a rejected block can still leave the
+ * card busy, and the next command must not land on it. */
+ const uint32_t b0 = k_cycle_get_32();
+ const bool done = busy_wait(slow);
+ last_tok = status;
+ last_busy_us = k_cyc_to_us_floor32(k_cycle_get_32() - b0);
+ if (status != 0x2) {
+ st.wr_rejects++;
+ return false;
+ }
+ return done;
+}
+
+/* A command followed by one data block from the card; the block retried bit-banged, then
+ * at 1 us. */
+static bool read_cmd_block(uint8_t index, uint32_t arg, uint8_t *buf)
+{
+ static const enum mode modes[] = { M_SPIM, M_FAST, M_SLOW };
+ uint8_t r[(R1_BITS_DATA + 7u) / 8u];
+ for (unsigned t = 0; t < ARRAY_SIZE(modes) && !aborted; t++) {
+ if (!send_cmd_retry(index, arg, r, R1_BITS_DATA)) {
+ return false;
+ }
+ if (read_data(buf, modes[t])) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* CMD12 STOP_TRANSMISSION. After a write burst it is R1b: the card holds DAT0 low while
+ * it commits, and returning before that makes the next command miss its response. */
+static bool stop_transmission(bool after_write)
+{
+ uint8_t r[(R1_BITS + 7u) / 8u];
+ const bool ok = send_cmd_retry(12, 0, r, R1_BITS);
+ return (after_write ? busy_wait(false) : true) && ok;
+}
+
+/* ---- burst READS are closed-ended (M6, proven 2026-10-07) ----
+ * ⚠️ Open-ended CMD18 (the tape-looper's way: run until CMD12) RETURNS JUNK on this card.
+ * CMD12 lands while the card is already fetching the block after the last one wanted, and
+ * some later burst then hands back, as its SECOND block, the card's internal buffer -- with a
+ * valid CRC, so nothing below this layer can see it. Measured on hardware
+ * (logs/sp1-20261007-221018.log, 4 ON entries x 3 rounds of FAT scan + 512 KB read):
+ * open-ended 5 bad blocks, every one at position 1 of its burst, every one the same
+ * buffer-like bytes give or take a few bits; closed-ended 0. Earlier runs: the host's own
+ * FAT scan set it up and Wakes' next read caught it (-202944, -210404, -215523).
+ * So every burst read is CMD23 SET_BLOCK_COUNT + CMD18: the card stops itself after exactly
+ * n blocks, and CMD12 is sent only to cut a failed burst short.
+ * Burst WRITES stay open-ended (CMD25 ... CMD12): ~10 000 verified blocks, 0 wrong. */
+static bool set_block_count(uint32_t n)
+{
+ uint8_t r[(R1_BITS + 7u) / 8u];
+ return send_cmd_retry(23, n & 0xffffu, r, R1_BITS);
+}
+
+/* ---------------------------------------------------------------- API */
+
+bool sp1_emmc_init(struct sp1_emmc_ident *id)
+{
+ struct sp1_emmc_ident local;
+ if (id == NULL) {
+ id = &local;
+ }
+ memset(id, 0, sizeof(*id));
+ id->cid_shift = -128;
+ memset(&st, 0, sizeof(st));
+ ready = false;
+ cmd_fast = false;
+ sectors = 0;
+ aborted = false;
+
+ crc16_build();
+ if (crc16((const uint8_t *)"123456789", 9) != 0x31c3u) {
+ return false; /* never move data with a broken check */
+ }
+
+ nrf_gpio_cfg(PIN_CLK, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT,
+ NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE);
+ CLK_LO();
+ NRF_P0->OUTSET = P0_CMD;
+ nrf_gpio_cfg_output(PIN_CMD);
+ nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); /* driven only while writing */
+ nrf_gpio_cfg_output(PIN_RST);
+ nrf_gpio_cfg_output(PIN_VCCQ);
+ spim_setup();
+
+ /* Power and reset, as the tape-looper does it. RST_n only acts if the card's
+ * RST_n_FUNCTION is enabled -- it is not on this unit (EXT_CSD[162] = 0). */
+ const uint32_t t_on = k_uptime_get_32();
+ nrf_gpio_pin_set(PIN_VCCQ);
+ k_msleep(10);
+ nrf_gpio_pin_clear(PIN_RST);
+ k_msleep(1);
+ nrf_gpio_pin_set(PIN_RST);
+ k_msleep(2);
+
+ for (int i = 0; i < 80; i++) { /* >= 74 clocks before the first command */
+ pulse(true);
+ }
+
+ (void)send_cmd(0, 0, NULL, 0, true); /* CMD0 GO_IDLE_STATE, no response */
+ k_msleep(1);
+
+ /* CMD1 SEND_OP_COND, sector addressing (HCS), until the power-up bit (OCR[31],
+ * response bit 8) is set. */
+ uint8_t r[(R2_BITS + 7u) / 8u];
+ bool up = false;
+ while (!up && !aborted && (k_uptime_get_32() - t_on) < INIT_TIMEOUT_MS) {
+ id->ocr_tries++;
+ if (send_cmd(1, 0x40ff8000u, r, R1_BITS, true)) {
+ id->ocr = resp_bits(r, 8, 32);
+ up = (id->ocr & 0x80000000u) != 0u;
+ }
+ if (!up) {
+ k_msleep(1);
+ }
+ }
+ id->ready_ms = k_uptime_get_32() - t_on;
+ if (!up) {
+ return false;
+ }
+
+ /* CMD2 ALL_SEND_CID: R2, CID[127:0] from bit 8. Checked against the CID's own CRC7
+ * at three alignments; the report says which matched. */
+ if (!send_cmd_retry(2, 0, r, R2_BITS)) {
+ return false;
+ }
+ static const int8_t shifts[] = { 0, -1, 1 };
+ for (unsigned s = 0; s < ARRAY_SIZE(shifts); s++) {
+ uint8_t cid[16];
+ for (uint32_t k = 0; k < 16u; k++) {
+ cid[k] = (uint8_t)resp_bits(r, (uint32_t)(8 + shifts[s]) + 8u * k, 8);
+ }
+ if (crc7(cid, 15) == cid[15] || s == 0u) {
+ memcpy(id->cid, cid, sizeof(cid));
+ }
+ if (crc7(cid, 15) == cid[15]) {
+ id->cid_shift = shifts[s];
+ break;
+ }
+ }
+
+ rca = 1u << 16; /* CMD3 SET_RELATIVE_ADDR: we choose 1 */
+ if (!send_cmd_retry(3, rca, r, R1_BITS) ||
+ !send_cmd_retry(7, rca, r, R1_BITS) || /* CMD7 SELECT_CARD -> transfer */
+ !send_cmd_retry(16, SP1_EMMC_BLOCK, r, R1_BITS)) { /* CMD16 SET_BLOCKLEN */
+ return false;
+ }
+ ready = true;
+ cmd_fast = true; /* identification over: full speed */
+
+ /* The size, from EXT_CSD SEC_COUNT [215:212]. */
+ static uint8_t xcsd[SP1_EMMC_BLOCK];
+ if (!read_cmd_block(8, 0, xcsd)) {
+ ready = false;
+ return false;
+ }
+ sectors = (uint32_t)xcsd[212] | ((uint32_t)xcsd[213] << 8) |
+ ((uint32_t)xcsd[214] << 16) | ((uint32_t)xcsd[215] << 24);
+ return sectors != 0u;
+}
+
+bool sp1_emmc_ready(void)
+{
+ return ready && !aborted;
+}
+
+uint32_t sp1_emmc_sectors(void)
+{
+ return sp1_emmc_ready() ? sectors : 0u;
+}
+
+bool sp1_emmc_status(uint32_t *status)
+{
+ uint8_t r[(R1_BITS + 7u) / 8u];
+ if (!send_cmd_retry(13, rca, r, R1_BITS)) {
+ return false;
+ }
+ *status = resp_bits(r, 8, 32);
+ return true;
+}
+
+bool sp1_emmc_read_ext_csd(uint8_t buf[SP1_EMMC_BLOCK])
+{
+ return sp1_emmc_ready() && read_cmd_block(8, 0, buf);
+}
+
+bool sp1_emmc_read_block(uint32_t block, uint8_t buf[SP1_EMMC_BLOCK])
+{
+ return sp1_emmc_ready() && block < sectors && read_cmd_block(17, block, buf);
+}
+
+static bool write_block_raw(uint32_t block, const uint8_t *buf)
+{
+ static const enum mode modes[] = { M_SPIM, M_FAST, M_SLOW };
+ uint8_t r[(R1_BITS + 7u) / 8u];
+ for (unsigned t = 0; t < ARRAY_SIZE(modes) && !aborted; t++) {
+ /* CMD24 WRITE_BLOCK. Its R1 reports this command's own errors (address out
+ * of range, write protect, ...): never send data after one of those. */
+ if (!send_cmd_retry(24, block, r, R1_BITS)) {
+ return false;
+ }
+ if ((resp_bits(r, 8, 32) & WRITE_FATAL) != 0u) {
+ return false;
+ }
+ if (write_data(buf, modes[t])) {
+ return true;
+ }
+ }
+ return false;
+}
+
+#if defined(CONFIG_SP1_EMMC_VERIFY)
+/* ---- read every write back (diagnostics, M6) ----
+ * Hardware 2026-10-07 (logs/sp1-20261007-202944.log, -210404.log): in about a third of ON
+ * entries the 512 KB test file read back with one or two blocks still holding the card's
+ * OLD contents -- every token "accepted", no CRC error, no timeout, all in CMD25 bursts.
+ * So a write was lost or landed elsewhere. This reads each written block straight back,
+ * and on a mismatch says where in its burst it was, what the card answered for it, and
+ * whether a slow re-read agrees (a lost WRITE) or not (a READ problem); then rewrites it
+ * on its own and checks again. */
+static uint8_t vbuf[SP1_EMMC_BLOCK];
+static uint8_t vbuf2[SP1_EMMC_BLOCK];
+
+static bool read_back(uint32_t block, uint8_t *dst, enum mode m)
+{
+ uint8_t r[(R1_BITS_DATA + 7u) / 8u];
+ return send_cmd_retry(17, block, r, R1_BITS_DATA) && read_data(dst, m);
+}
+
+static void hex16(char *out, const uint8_t *d)
+{
+ static const char hx[] = "0123456789abcdef";
+ for (int i = 0; i < 16; i++) {
+ out[3 * i] = ' ';
+ out[3 * i + 1] = hx[d[i] >> 4];
+ out[3 * i + 2] = hx[d[i] & 15u];
+ }
+ out[48] = '\0';
+}
+
+static bool verify_block(uint32_t block, const uint8_t *src, const char *how, uint32_t pos,
+ uint32_t n, int tok, uint32_t busy_us, uint32_t prev_busy_us)
+{
+ if (read_back(block, vbuf, M_SPIM) && memcmp(vbuf, src, SP1_EMMC_BLOCK) == 0) {
+ return true;
+ }
+ st.verify_fails++;
+ const bool slow_ok = read_back(block, vbuf2, M_SLOW);
+ const bool slow_right = slow_ok && memcmp(vbuf2, src, SP1_EMMC_BLOCK) == 0;
+ const bool same = slow_ok && memcmp(vbuf2, vbuf, SP1_EMMC_BLOCK) == 0;
+ uint32_t diff = 0;
+ for (uint32_t i = 0; i < SP1_EMMC_BLOCK; i++) {
+ diff += (vbuf[i] != src[i]);
+ }
+ printk("EMMC VERIFY FAIL: %s LBA %u = block %u of %u; token %d, busy %u us (block before: "
+ "%u us); %u bytes differ; slow re-read %s\n", how, (unsigned)block, (unsigned)pos,
+ (unsigned)n, tok, (unsigned)busy_us, (unsigned)prev_busy_us, (unsigned)diff,
+ !slow_ok ? "FAILED" : (slow_right ? "is RIGHT -> a READ problem"
+ : (same ? "agrees -> the WRITE was lost"
+ : "differs from both")));
+ char a[49], b[49];
+ hex16(a, vbuf);
+ hex16(b, src);
+ printk("EMMC VERIFY FAIL: read %s\nEMMC VERIFY FAIL: wrote %s\n", a, b);
+ const bool fixed = write_block_raw(block, src) && read_back(block, vbuf, M_SPIM) &&
+ memcmp(vbuf, src, SP1_EMMC_BLOCK) == 0;
+ if (fixed) {
+ st.verify_fixed++;
+ }
+ printk("EMMC VERIFY: rewritten on its own: %s\n", fixed ? "now right" : "STILL WRONG");
+ return fixed;
+}
+#endif
+
+bool sp1_emmc_write_block(uint32_t block, const uint8_t buf[SP1_EMMC_BLOCK])
+{
+ if (!sp1_emmc_ready() || block >= sectors || !write_block_raw(block, buf)) {
+ return false;
+ }
+#if defined(CONFIG_SP1_EMMC_VERIFY)
+ return verify_block(block, buf, "CMD24", 0, 1, last_tok, last_busy_us, 0);
+#else
+ return true;
+#endif
+}
+
+bool sp1_emmc_read_blocks(uint32_t block, uint8_t *buf, uint32_t n)
+{
+ if (!sp1_emmc_ready() || n == 0u || block >= sectors || n > sectors - block) {
+ return false;
+ }
+ /* The card reads ahead in a CMD18; ending one on the very last block can trip
+ * ADDRESS_OUT_OF_RANGE, so the device's last block always goes on its own. */
+ uint32_t multi = (block + n == sectors) ? n - 1u : n;
+ uint32_t done = 0;
+ if (multi >= 2u) {
+ uint8_t r[(R1_BITS_DATA + 7u) / 8u];
+ if (set_block_count(multi) && send_cmd_retry(18, block, r, R1_BITS_DATA)) {
+ while (done < multi && read_data(buf + done * SP1_EMMC_BLOCK, M_SPIM)) {
+ done++;
+ }
+ /* Complete: the card stopped by itself. Cut short: it must be told. */
+ if (done < multi) {
+ (void)stop_transmission(false);
+ }
+ st.multi_blocks += done;
+ if (done < multi) {
+ st.multi_fallbacks++;
+ }
+ }
+ }
+ for (; done < n; done++) { /* the rest, or all of it, one by one */
+ if (!sp1_emmc_read_block(block + done, buf + done * SP1_EMMC_BLOCK)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool sp1_emmc_write_blocks(uint32_t block, const uint8_t *buf, uint32_t n)
+{
+ if (!sp1_emmc_ready() || n == 0u || block >= sectors || n > sectors - block) {
+ return false;
+ }
+ uint32_t done = 0;
+ if (n >= 2u) {
+ uint8_t r[(R1_BITS + 7u) / 8u];
+#if defined(CONFIG_SP1_EMMC_VERIFY)
+ static int8_t btok[64];
+ static uint32_t bbusy[64];
+#endif
+ if (send_cmd_retry(25, block, r, R1_BITS) &&
+ (resp_bits(r, 8, 32) & WRITE_FATAL) == 0u) {
+ while (done < n && write_data(buf + done * SP1_EMMC_BLOCK, M_SPIM)) {
+#if defined(CONFIG_SP1_EMMC_VERIFY)
+ if (done < 64u) {
+ btok[done] = (int8_t)last_tok;
+ bbusy[done] = last_busy_us;
+ }
+#endif
+ done++;
+ }
+ if (!stop_transmission(true)) {
+ done = 0; /* unsure what landed: rewrite it all */
+ }
+ st.multi_blocks += done;
+ if (done < n) {
+ st.multi_fallbacks++;
+ }
+#if defined(CONFIG_SP1_EMMC_VERIFY)
+ for (uint32_t j = 0; j < done; j++) {
+ const bool rec = j < 64u;
+ if (!verify_block(block + j, buf + j * SP1_EMMC_BLOCK, "CMD25", j, n,
+ rec ? btok[j] : -2, rec ? bbusy[j] : 0u,
+ (rec && j > 0u) ? bbusy[j - 1u] : 0u)) {
+ return false;
+ }
+ }
+#endif
+ }
+ }
+ for (; done < n; done++) { /* rewriting a block is harmless */
+ if (!sp1_emmc_write_block(block + done, buf + done * SP1_EMMC_BLOCK)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void sp1_emmc_get_stats(struct sp1_emmc_stats *s)
+{
+ *s = st;
+}
+
+void sp1_emmc_power_down(void)
+{
+ ready = false;
+ cmd_fast = false;
+ if (spim_on) {
+ NRF_SPIM3->ENABLE = 0;
+ NRF_SPIM3->PSEL.SCK = 0xffffffffu;
+ NRF_SPIM3->PSEL.MOSI = 0xffffffffu;
+ NRF_SPIM3->PSEL.MISO = 0xffffffffu;
+ /* nRF52840 anomaly 195: SPIM3 keeps drawing current after disable unless
+ * this is written (nrfx_spim_uninit does the same). */
+ *(volatile uint32_t *)0x4002F004 = 1;
+ spim_on = false;
+ }
+ nrf_gpio_pin_clear(PIN_RST);
+ nrf_gpio_cfg_default(PIN_CLK);
+ nrf_gpio_cfg_default(PIN_CMD);
+ nrf_gpio_cfg_default(PIN_DAT0);
+ nrf_gpio_cfg_default(PIN_RST);
+ nrf_gpio_cfg_output(PIN_VCCQ);
+ nrf_gpio_pin_clear(PIN_VCCQ); /* rail off; sp1_quiesce_peripherals agrees */
+}
+
+void sp1_emmc_abort(void)
+{
+ aborted = true;
+ sp1_emmc_power_down();
+}
diff --git a/firmware/src/sp1_emmc.h b/firmware/src/sp1_emmc.h
new file mode 100644
index 0000000..111012b
--- /dev/null
+++ b/firmware/src/sp1_emmc.h
@@ -0,0 +1,96 @@
+/*
+ * wakes-sp1 — the SP-1's eMMC (M6, #43): Toshiba THGBMNG5D1LBAIL, 4 GB, wired 1-bit
+ * (CLK, CMD, DAT0, RST_n, VCCQ -- sp1_board.h). The nRF52840 has no SD/MMC peripheral,
+ * so the bus is bit-banged.
+ *
+ * Protocol from chattock/sp1-tape-looper firmware/src/sp1_emmc.c (MIT), itself ported
+ * from Tim Knapen's SP-1-dev emmc.c (MIT): the command framing, the response sampling
+ * points, the init sequence and the write framing are theirs, proven on this board.
+ * Payloads ride SPIM3 DMA at 16 MHz with bit-banged fallbacks (sp1_emmc.c, "fast
+ * transfer"); every block read is CRC-checked and every block write must get the card's
+ * "accepted" token.
+ *
+ * ⚠️ Commands sent: 0, 1, 2, 3, 7, 8, 12, 13, 16, 17, 18, 23, 24, 25. Nothing that touches EXT_CSD
+ * (CMD6), nothing that erases (CMD35/36/38), nothing that partitions. The card's OTP
+ * settings are never written.
+ *
+ * ⚠️ NOT watchdog-fed: this runs in the storage thread (sp1_store.c), and a background
+ * thread that fed the watchdog would hide a hung main loop. Every wait here is bounded.
+ *
+ * One caller at a time (the storage thread); sp1_emmc_abort() may come from main.
+ */
+#ifndef SP1_EMMC_H
+#define SP1_EMMC_H
+
+#include
+#include
+
+#define SP1_EMMC_BLOCK 512u
+
+/* What came back during identification, for the report. */
+struct sp1_emmc_ident {
+ uint32_t ocr; /* CMD1's final OCR */
+ uint32_t ocr_tries; /* CMD1s until ready */
+ uint32_t ready_ms; /* power-on to ready */
+ uint8_t cid[16]; /* CID[127:0], MSB first */
+ int8_t cid_shift; /* bit alignment the CID's CRC7 matched at (0 expected), */
+ /* or -128 if no alignment matched */
+};
+
+/* Counters since sp1_emmc_init(). */
+struct sp1_emmc_stats {
+ uint32_t cmd_retries; /* a command that needed more than one try */
+ uint32_t crc_errs; /* data blocks whose CRC16 did not match (then retried) */
+ uint32_t hunt_timeouts; /* a data block's start bit never came (100 ms) */
+ uint32_t busy_timeouts; /* the card stayed busy after a write (500 ms) */
+ uint32_t spim_timeouts; /* an SPIM3 transfer did not end (5 ms) */
+ uint32_t wr_rejects; /* writes the card did not accept (then retried) */
+ uint32_t wr_busy_max_us; /* longest programming busy after a write */
+ uint32_t multi_blocks; /* blocks moved inside CMD18 / CMD25 bursts */
+ uint32_t multi_fallbacks;/* bursts that had to finish block by block */
+ uint32_t verify_fails; /* CONFIG_SP1_EMMC_VERIFY: written blocks read back wrong */
+ uint32_t verify_fixed; /* ...and right after a single-block rewrite */
+};
+
+/* Power the card, identify it, select it, block length 512, read its size. Bounded:
+ * gives up after ~1 s of CMD1 (JEDEC's allowance). `id` may be NULL. False = not
+ * usable; call sp1_emmc_power_down() either way. Clears a previous abort. */
+bool sp1_emmc_init(struct sp1_emmc_ident *id);
+
+bool sp1_emmc_ready(void);
+
+/* User-area size in blocks (EXT_CSD SEC_COUNT), 0 before a good init. */
+uint32_t sp1_emmc_sectors(void);
+
+/* CMD13: card status (bits 31..0). */
+bool sp1_emmc_status(uint32_t *status);
+
+/* CMD8 SEND_EXT_CSD: the 512-byte extended CSD. */
+bool sp1_emmc_read_ext_csd(uint8_t buf[SP1_EMMC_BLOCK]);
+
+/* CMD17 / CMD24: one block of the user area, by block number (sector-addressed card).
+ * Read: CRC-checked. Write: the card's CRC-status token must say "accepted", then its
+ * programming busy is waited out (bounded). Both retried up to 3 times. */
+bool sp1_emmc_read_block(uint32_t block, uint8_t buf[SP1_EMMC_BLOCK]);
+bool sp1_emmc_write_block(uint32_t block, const uint8_t buf[SP1_EMMC_BLOCK]);
+
+/* `n` consecutive blocks in one CMD18 / CMD25 burst (fast transfer). A burst that fails
+ * part-way is stopped and the rest done block by block through the calls above, so the
+ * result is the same as n single calls, only faster. Reads are closed-ended (CMD23 first:
+ * open-ended reads return junk on this card -- sp1_emmc.c). `buf` must be in RAM for reads
+ * (SPIM3 DMAs into it); writes copy through a RAM frame, so any source works. */
+bool sp1_emmc_read_blocks(uint32_t block, uint8_t *buf, uint32_t n);
+bool sp1_emmc_write_blocks(uint32_t block, const uint8_t *buf, uint32_t n);
+
+void sp1_emmc_get_stats(struct sp1_emmc_stats *s);
+
+/* Release the bus pins (disconnected inputs: nothing may back-feed an unpowered rail),
+ * RST_n low, VCCQ off. Safe at any time, and when init was never run. */
+void sp1_emmc_power_down(void);
+
+/* From the power-off path (sp1_store_abort): power down AND make every call fail until
+ * the next sp1_emmc_init(), so a storage thread caught mid-operation cannot drive the
+ * pins of a card whose rail is gone. */
+void sp1_emmc_abort(void);
+
+#endif /* SP1_EMMC_H */
diff --git a/firmware/src/sp1_emmc_report.c b/firmware/src/sp1_emmc_report.c
new file mode 100644
index 0000000..dc5196e
--- /dev/null
+++ b/firmware/src/sp1_emmc_report.c
@@ -0,0 +1,303 @@
+/*
+ * wakes-sp1 — the eMMC report (M6, #43). See sp1_emmc_report.h.
+ *
+ * Began as the read-only probe (2026-10-07, logs/sp1-20261007-152119.log): that run's
+ * full EXT_CSD and block-0 hex are in the log and private/docs/M6-PRST-PLAN.md, so the
+ * report now prints the decoded lines and only dumps a block it cannot classify.
+ *
+ * EXT_CSD field positions are JEDEC JESD84-B51 (eMMC 5.1), section 7.4. MBR and GPT
+ * layouts are the usual ones; FAT and exFAT boot sectors per Microsoft's specs.
+ */
+#include "sp1_emmc_report.h"
+#include "sp1_emmc.h"
+#include "sp1_console.h"
+
+#include
+#include
+
+static uint8_t blk[SP1_EMMC_BLOCK];
+static uint8_t aux[SP1_EMMC_BLOCK];
+
+static uint32_t le32(const uint8_t *p)
+{
+ return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
+ ((uint32_t)p[3] << 24);
+}
+
+static uint16_t le16(const uint8_t *p)
+{
+ return (uint16_t)(p[0] | (p[1] << 8));
+}
+
+/* printk is paced line by line: CDC ACM drops what it cannot send (sp1_console.c).
+ * No watchdog feed: this runs in the storage thread (sp1_emmc.h). */
+#define LINE(...) do { printk(__VA_ARGS__); sp1_console_pace(); } while (0)
+
+static void hexdump(const char *tag, const uint8_t *d, uint32_t n)
+{
+ for (uint32_t o = 0; o < n; o += 16u) {
+ char s[16 * 3 + 1];
+ char *p = s;
+ for (uint32_t i = 0; i < 16u && o + i < n; i++) {
+ static const char hx[] = "0123456789abcdef";
+ *p++ = ' ';
+ *p++ = hx[d[o + i] >> 4];
+ *p++ = hx[d[o + i] & 15u];
+ }
+ *p = '\0';
+ LINE("EMMC %s %03x:%s\n", tag, (unsigned)o, s);
+ }
+}
+
+/* Printable copy of a fixed-width text field. */
+static const char *text(const uint8_t *p, uint32_t n)
+{
+ static char s[40];
+ if (n >= sizeof(s)) {
+ n = sizeof(s) - 1u;
+ }
+ for (uint32_t i = 0; i < n; i++) {
+ s[i] = (p[i] >= 0x20 && p[i] < 0x7f) ? (char)p[i] : '.';
+ }
+ s[n] = '\0';
+ return s;
+}
+
+static void fill_counts(const uint8_t *d, uint32_t *zeros, uint32_t *ffs)
+{
+ *zeros = 0;
+ *ffs = 0;
+ for (uint32_t i = 0; i < SP1_EMMC_BLOCK; i++) {
+ *zeros += (d[i] == 0x00u);
+ *ffs += (d[i] == 0xffu);
+ }
+}
+
+/* A volume boot sector: what filesystem, if any, starts at `lba`. Reads into aux. */
+static void boot_sector(const char *what, uint32_t lba)
+{
+ if (!sp1_emmc_read_block(lba, aux)) {
+ LINE("EMMC %s boot sector (block %u): READ FAILED\n", what, (unsigned)lba);
+ return;
+ }
+ const bool sig = (aux[510] == 0x55u && aux[511] == 0xaau);
+ if (memcmp(&aux[3], "EXFAT ", 8) == 0) {
+ LINE("EMMC %s: exFAT, %u-byte sectors, %u sectors/cluster, volume %u sectors, "
+ "sig %s\n", what, 1u << aux[108], 1u << aux[109], (unsigned)le32(&aux[72]),
+ sig ? "55aa" : "MISSING");
+ } else if (memcmp(&aux[82], "FAT32", 5) == 0) {
+ LINE("EMMC %s: FAT32, OEM \"%s\"", what, text(&aux[3], 8));
+ LINE(" label \"%s\", %u-byte sectors, %u sectors/cluster, %u reserved, %u FATs"
+ " of %u sectors, %u sectors total, sig %s\n", text(&aux[71], 11),
+ le16(&aux[11]), aux[13], le16(&aux[14]), aux[16], (unsigned)le32(&aux[36]),
+ (unsigned)le32(&aux[32]), sig ? "55aa" : "MISSING");
+ } else if (memcmp(&aux[54], "FAT", 3) == 0) {
+ LINE("EMMC %s: %s,", what, text(&aux[54], 8));
+ LINE(" OEM \"%s\",", text(&aux[3], 8));
+ LINE(" label \"%s\", %u-byte sectors, %u sectors/cluster, sig %s\n",
+ text(&aux[43], 11), le16(&aux[11]), aux[13], sig ? "55aa" : "MISSING");
+ } else if (memcmp(&aux[3], "NTFS", 4) == 0) {
+ LINE("EMMC %s: NTFS\n", what);
+ } else {
+ LINE("EMMC %s: no FAT/exFAT/NTFS boot sector (sig %s)\n", what,
+ sig ? "55aa" : "none");
+ }
+ hexdump("vbr", aux, 64);
+}
+
+static void decode_ext_csd(const uint8_t *x)
+{
+ static const char *const rev[] = { "4.0", "4.1", "4.2", "4.3", "?", "4.41", "4.5",
+ "5.0", "5.1" };
+ const uint32_t sectors = le32(&x[212]);
+ LINE("EMMC EXT_CSD rev %u (eMMC %s), %u sectors = %u MB, device type 0x%02x\n",
+ x[192], x[192] < ARRAY_SIZE(rev) ? rev[x[192]] : "?", (unsigned)sectors,
+ (unsigned)(sectors / 2048u), x[196]);
+ LINE("EMMC EXT_CSD boot partitions 2 x %u KB, RPMB %u KB, boot config 0x%02x,"
+ " partitioning support 0x%02x, setting completed %u\n",
+ x[226] * 128u, x[168] * 128u, x[179], x[160], x[155]);
+ LINE("EMMC EXT_CSD erase group %u KB (HC, def %u), WP group %u, trim mult %u,"
+ " sec features 0x%02x\n", x[224] * 512u, x[175], x[221], x[230], x[229]);
+ LINE("EMMC EXT_CSD reliable write: param 0x%02x set 0x%02x sectors %u\n",
+ x[166], x[167], x[222]);
+ LINE("EMMC EXT_CSD cache %u (ctrl %u), power-off notify %u, RST_n function %u,"
+ " HPI 0x%02x, BKOPS support %u\n", (unsigned)le32(&x[249]), x[33], x[34], x[162],
+ x[503], x[502]);
+ LINE("EMMC EXT_CSD bus width %u, HS timing %u, life A 0x%02x B 0x%02x,"
+ " pre-EOL 0x%02x, firmware %02x%02x%02x%02x%02x%02x%02x%02x\n",
+ x[183], x[185], x[268], x[269], x[267], x[261], x[260], x[259], x[258], x[257],
+ x[256], x[255], x[254]);
+}
+
+static void decode_cid(const struct sp1_emmc_ident *id)
+{
+ const uint8_t *c = id->cid;
+ hexdump("cid", c, 16);
+ if (id->cid_shift == -128) {
+ LINE("EMMC CID: CRC7 matched at NO alignment -- response sampling is off\n");
+ } else {
+ LINE("EMMC CID: CRC7 ok at alignment %d%s\n", id->cid_shift,
+ id->cid_shift == 0 ? " (as expected)" : " -- NOT the expected 0");
+ }
+ /* MDT: month in the high nibble; the year nibble counts from 1997, or from 2013 on
+ * an EXT_CSD rev > 4 part -- printed raw, the rev is on the EXT_CSD line. */
+ LINE("EMMC CID: MID 0x%02x, CBX %u, OID 0x%02x, product \"%s\", rev %u.%u,"
+ " serial 0x%08x, month %u year code %u\n", c[0], c[1] & 3u, c[2],
+ text(&c[3], 6), c[9] >> 4, c[9] & 15u,
+ (unsigned)(((uint32_t)c[10] << 24) | ((uint32_t)c[11] << 16) |
+ ((uint32_t)c[12] << 8) | c[13]), c[14] >> 4, c[14] & 15u);
+}
+
+static void decode_gpt(void)
+{
+ if (!sp1_emmc_read_block(1, aux) || memcmp(aux, "EFI PART", 8) != 0) {
+ LINE("EMMC GPT: no header at block 1\n");
+ return;
+ }
+ const uint32_t entries_lba = le32(&aux[72]);
+ const uint32_t n = le32(&aux[80]);
+ const uint32_t size = le32(&aux[84]);
+ LINE("EMMC GPT: %u entries of %u bytes at block %u\n", (unsigned)n, (unsigned)size,
+ (unsigned)entries_lba);
+ if (size != 128u || !sp1_emmc_read_block(entries_lba, blk)) {
+ return;
+ }
+ uint32_t first[4] = { 0 };
+ for (uint32_t i = 0; i < 4u && i < n; i++) {
+ const uint8_t *e = &blk[i * 128u];
+ bool used = false;
+ for (int k = 0; k < 16; k++) {
+ used |= (e[k] != 0u);
+ }
+ if (!used) {
+ continue;
+ }
+ char name[37];
+ for (int k = 0; k < 36; k++) { /* UTF-16LE, ASCII only */
+ const uint8_t ch = e[56 + 2 * k];
+ name[k] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : (ch ? '?' : '\0');
+ }
+ name[36] = '\0';
+ first[i] = le32(&e[32]);
+ LINE("EMMC GPT p%u: blocks %u..%u \"%s\"\n", (unsigned)(i + 1),
+ (unsigned)first[i], (unsigned)le32(&e[40]), name);
+ }
+ for (uint32_t i = 0; i < 4u; i++) {
+ if (first[i] != 0u) {
+ char what[8] = "p?";
+ what[1] = (char)('1' + i);
+ boot_sector(what, first[i]);
+ }
+ }
+}
+
+/* Block 0: MBR, a bare FAT volume, sp1-tape-looper's index, or something else. */
+static void decode_block0(void)
+{
+ if (!sp1_emmc_read_block(0, blk)) {
+ LINE("EMMC block 0: READ FAILED\n");
+ return;
+ }
+
+ const uint32_t magic = le32(blk);
+ if ((magic >> 16) == 0x5345u) { /* 'S' 'E' ..: the looper's META_MAGIC */
+ LINE("EMMC block 0: sp1-tape-looper's song index (magic 0x%08x \"%s\")\n",
+ (unsigned)magic, text(blk, 4));
+ }
+ const bool sig = (blk[510] == 0x55u && blk[511] == 0xaau);
+ if (!sig) {
+ uint32_t z, f;
+ fill_counts(blk, &z, &f);
+ LINE("EMMC block 0: no 55aa signature, so no MBR (%u x 00, %u x ff)\n",
+ (unsigned)z, (unsigned)f);
+ hexdump("b0", blk, 64);
+ return;
+ }
+ if ((blk[0] == 0xebu || blk[0] == 0xe9u) &&
+ (memcmp(&blk[82], "FAT", 3) == 0 || memcmp(&blk[54], "FAT", 3) == 0 ||
+ memcmp(&blk[3], "EXFAT", 5) == 0)) {
+ LINE("EMMC block 0: a filesystem with no partition table\n");
+ boot_sector("vol", 0);
+ return;
+ }
+ LINE("EMMC block 0: MBR, disk signature 0x%08x\n", (unsigned)le32(&blk[440]));
+ uint32_t start[4] = { 0 };
+ bool gpt = false;
+ for (uint32_t i = 0; i < 4u; i++) {
+ const uint8_t *e = &blk[446u + 16u * i];
+ if (e[4] == 0u) {
+ continue;
+ }
+ start[i] = le32(&e[8]);
+ gpt |= (e[4] == 0xeeu);
+ LINE("EMMC MBR p%u: status 0x%02x type 0x%02x, blocks %u + %u (%u MB)\n",
+ (unsigned)(i + 1), e[0], e[4], (unsigned)start[i], (unsigned)le32(&e[12]),
+ (unsigned)(le32(&e[12]) / 2048u));
+ }
+ if (gpt) {
+ decode_gpt();
+ return;
+ }
+ for (uint32_t i = 0; i < 4u; i++) {
+ if (start[i] != 0u) {
+ char what[4] = "p?";
+ what[1] = (char)('1' + i);
+ boot_sector(what, start[i]);
+ }
+ }
+}
+
+void sp1_emmc_report_init(bool ok, const struct sp1_emmc_ident *id)
+{
+ LINE("EMMC init %s: %u CMD1s, %u ms to ready, OCR 0x%08x (%s), %u blocks\n",
+ ok ? "ok" : "FAILED", (unsigned)id->ocr_tries, (unsigned)id->ready_ms,
+ (unsigned)id->ocr, (id->ocr & 0x40000000u) ? "sector mode" : "byte mode",
+ (unsigned)sp1_emmc_sectors());
+ if (!ok) {
+ struct sp1_emmc_stats s;
+ sp1_emmc_get_stats(&s);
+ LINE("EMMC gave up (command retries %u)\n", (unsigned)s.cmd_retries);
+ return;
+ }
+ decode_cid(id);
+}
+
+void sp1_emmc_report_card(void)
+{
+ uint32_t status = 0;
+ if (sp1_emmc_status(&status)) {
+ static const char *const state[] = { "idle", "ready", "ident", "stby", "tran",
+ "data", "rcv", "prg", "dis", "btst", "slp" };
+ const uint32_t s = (status >> 9) & 15u;
+ LINE("EMMC status 0x%08x: state %s%s\n", (unsigned)status,
+ s < ARRAY_SIZE(state) ? state[s] : "?",
+ /* JEDEC error bits: 31-26, 24-19, 16, 15, 7 */
+ (status & 0xfdf98080u) ? ", ERROR BITS SET" : "");
+ } else {
+ LINE("EMMC status: no response\n");
+ }
+
+ if (sp1_emmc_read_ext_csd(aux)) {
+ decode_ext_csd(aux);
+ } else {
+ LINE("EMMC EXT_CSD: READ FAILED\n");
+ }
+ decode_block0();
+}
+
+void sp1_emmc_report_stats(void)
+{
+ struct sp1_emmc_stats s;
+ sp1_emmc_get_stats(&s);
+ LINE("EMMC errors: command retries %u, read CRC %u, write rejects %u, timeouts: "
+ "data %u busy %u spim %u; longest write busy %u us\n", (unsigned)s.cmd_retries,
+ (unsigned)s.crc_errs, (unsigned)s.wr_rejects, (unsigned)s.hunt_timeouts,
+ (unsigned)s.busy_timeouts, (unsigned)s.spim_timeouts,
+ (unsigned)s.wr_busy_max_us);
+ LINE("EMMC fast transfer: %u blocks in multi-block bursts, %u bursts finished "
+ "block by block\n", (unsigned)s.multi_blocks, (unsigned)s.multi_fallbacks);
+ if (IS_ENABLED(CONFIG_SP1_EMMC_VERIFY)) {
+ LINE("EMMC verify: %u written blocks read back wrong, %u right after a rewrite\n",
+ (unsigned)s.verify_fails, (unsigned)s.verify_fixed);
+ }
+}
diff --git a/firmware/src/sp1_emmc_report.h b/firmware/src/sp1_emmc_report.h
new file mode 100644
index 0000000..80ff9ea
--- /dev/null
+++ b/firmware/src/sp1_emmc_report.h
@@ -0,0 +1,19 @@
+/*
+ * wakes-sp1 — the eMMC report (M6, #43; CONFIG_SP1_STORAGE_TEST).
+ *
+ * Decoded console lines, every one starting "EMMC": what came back during init (CID,
+ * OCR, size), the card's state and EXT_CSD, block 0 (MBR / GPT / a bare FAT volume /
+ * sp1-tape-looper's index) with the boot sector of each partition, and the driver's
+ * error counters. Reads only. Storage thread only (sp1_store.c); paced for CDC ACM.
+ */
+#ifndef SP1_EMMC_REPORT_H
+#define SP1_EMMC_REPORT_H
+
+#include
+#include "sp1_emmc.h"
+
+void sp1_emmc_report_init(bool ok, const struct sp1_emmc_ident *id);
+void sp1_emmc_report_card(void);
+void sp1_emmc_report_stats(void);
+
+#endif /* SP1_EMMC_REPORT_H */
diff --git a/firmware/src/sp1_marbles_ui.c b/firmware/src/sp1_marbles_ui.c
index 9e19039..4338d6a 100644
--- a/firmware/src/sp1_marbles_ui.c
+++ b/firmware/src/sp1_marbles_ui.c
@@ -249,82 +249,138 @@ static void activate(enum sp1_mui_layer l)
}
}
-static void defaults_pages(void)
-{
- stored[SP1_MUI_T_SHIFT][0] = 0.5f; /* GTLT on its detent: disengaged */
- stored[SP1_MUI_T_SHIFT][1] = 0.5f; /* gate length 128/256 (Marbles) */
- stored[SP1_MUI_T_SHIFT][2] = 0.0f; /* no randomness */
- stored[SP1_MUI_T_SHIFT][3] = DEF_LENGTH;
- stored[SP1_MUI_X_SHIFT][0] = 0.0f; /* reserved (M4a) */
- stored[SP1_MUI_X_SHIFT][1] = 0.0f; /* reserved (M4a) */
- stored[SP1_MUI_X_SHIFT][2] = 0.0f; /* reserved */
+static void defaults_pages(struct sp1_mui_patch *p)
+{
+ p->v[SP1_MUI_T_SHIFT][0] = 0.5f; /* GTLT on its detent: disengaged */
+ p->v[SP1_MUI_T_SHIFT][1] = 0.5f; /* gate length 128/256 (Marbles) */
+ p->v[SP1_MUI_T_SHIFT][2] = 0.0f; /* no randomness */
+ p->v[SP1_MUI_T_SHIFT][3] = DEF_LENGTH;
+ p->v[SP1_MUI_X_SHIFT][0] = 0.0f; /* reserved (M4a) */
+ p->v[SP1_MUI_X_SHIFT][1] = 0.0f; /* reserved (M4a) */
+ p->v[SP1_MUI_X_SHIFT][2] = 0.0f; /* reserved */
/* X_SHIFT[3] is not a slot: F4 there addresses T_SHIFT[3] (LENGTH), see canon(). */
- stored[SP1_MUI_Y][0] = 0.5f; /* Marbles: 128/256 */
- stored[SP1_MUI_Y][1] = 0.5f;
- stored[SP1_MUI_Y][2] = 0.0f;
- stored[SP1_MUI_Y][3] = 6.5f / 12.0f; /* 1/8 of t2 (128/256) */
- q_ydiv = 6;
- q_length = 57;
- model = 0;
- t_range = 1;
- range = DEF_RANGE;
- diversity = 0;
- scale = 0; /* major */
+ p->v[SP1_MUI_X_SHIFT][3] = 0.0f;
+ p->v[SP1_MUI_Y][0] = 0.5f; /* Marbles: 128/256 */
+ p->v[SP1_MUI_Y][1] = 0.5f;
+ p->v[SP1_MUI_Y][2] = 0.0f;
+ p->v[SP1_MUI_Y][3] = 6.5f / 12.0f; /* 1/8 of t2 (128/256) */
+ p->model = 0;
+ p->t_range = 1;
+ p->range = DEF_RANGE;
+ p->diversity = 0;
+ p->scale = 0; /* major */
/* [F] and [G]: Marbles applies DEJA VU to both sections unless you turn one off. */
- dv_t = true;
- dv_x = true;
+ p->dv_t = 1;
+ p->dv_x = 1;
}
/* ---- boot routing vs rip routing: they are NOT the same any more (Adara, M4d) ----
* docs/DEFAULTS.md is the spec. Boot gives you something that plays the moment you press
* PLAY; a rip gives you a blank patch bay. */
-static void boot_routing(void)
+static void boot_routing(struct sp1_mui_patch *p)
{
/* ⚠️ TRIG comes from t2, the MASTER clock, which fires on every tick in every
* model -- so this is a steady stream of notes with no rhythmic randomness. That
* is deliberate (Adara, M4d): it is the most predictable "press PLAY and hear
* something" default there is, and t1 / t3 are then yours to route. It replaces
* M4b's t1 + t3, which gave the models' random rhythm straight away. */
- route.t_dest[0] = SP1_DEST_NONE;
- route.t_dest[1] = SP1_DEST_TRIG;
- route.t_dest[2] = SP1_DEST_NONE;
+ p->t_dest[0] = SP1_DEST_NONE;
+ p->t_dest[1] = SP1_DEST_TRIG;
+ p->t_dest[2] = SP1_DEST_NONE;
/* X1 -> V/Oct (no attenuverter, so Plaits' internal envelope keeps TIMBRE /
* MORPH / FM / HARMONICS); X2, X3 and Y start disconnected. */
- route.dest[0] = SP1_DEST_VOCT;
- route.dest[1] = SP1_DEST_NONE;
- route.dest[2] = SP1_DEST_NONE;
- route.dest[3] = SP1_DEST_NONE;
+ p->dest[0] = SP1_DEST_VOCT;
+ p->dest[1] = SP1_DEST_NONE;
+ p->dest[2] = SP1_DEST_NONE;
+ p->dest[3] = SP1_DEST_NONE;
}
-static void rip_routing(void)
+static void rip_routing(struct sp1_mui_patch *p)
{
- /* Every destination disconnected: "rip out the cables" now means what it says.
- * ⚠️ So after a rip on MARBLES, pressing PLAY makes no sound until something is
- * dialled back in. Intended (Adara, M4d). */
- for (int i = 0; i < 3; i++) { route.t_dest[i] = SP1_DEST_NONE; }
- for (int i = 0; i < 4; i++) { route.dest[i] = SP1_DEST_NONE; }
+ /* Two cables back in after a rip (Adara, #50): t2 -> TRIG and X2 -> V/Oct, so PLAY
+ * plays straight away; everything else disconnected. Through v0.7.2 a rip cleared
+ * every destination (M4d). Also the routing of every PRST default slot, which comes
+ * from here (sp1_prst.h).
+ * ⚠️ X2, not boot's X1. And V/Oct means the PLAITS quantizer cannot stay on (the M4b
+ * interlock): main.c's MARBLES rip turns it off, as routing V/Oct by hand does. */
+ for (int i = 0; i < 3; i++) { p->t_dest[i] = SP1_DEST_NONE; }
+ for (int i = 0; i < 4; i++) { p->dest[i] = SP1_DEST_NONE; }
+ p->t_dest[1] = SP1_DEST_TRIG;
+ p->dest[1] = SP1_DEST_VOCT;
}
/* Every BASE fader back to its default. The rip resets these too (docs/DEFAULTS.md):
* t RATE / BIAS / JITTER / DEJA VU and X SPREAD / BIAS / STEPS. */
-static void defaults_base(void)
+static void defaults_base(struct sp1_mui_patch *p)
{
- stored[SP1_MUI_T_BASE][0] = DEF_RATE;
- stored[SP1_MUI_T_BASE][1] = 0.5f;
- stored[SP1_MUI_T_BASE][2] = 0.0f;
- stored[SP1_MUI_T_BASE][3] = 0.0f; /* DEJA VU, shared with the X page */
- stored[SP1_MUI_X_BASE][0] = 0.5f;
- stored[SP1_MUI_X_BASE][1] = 0.5f;
- stored[SP1_MUI_X_BASE][2] = DEF_STEPS;
+ p->v[SP1_MUI_T_BASE][0] = DEF_RATE;
+ p->v[SP1_MUI_T_BASE][1] = 0.5f;
+ p->v[SP1_MUI_T_BASE][2] = 0.0f;
+ p->v[SP1_MUI_T_BASE][3] = 0.0f; /* DEJA VU, shared with the X page */
+ p->v[SP1_MUI_X_BASE][0] = 0.5f;
+ p->v[SP1_MUI_X_BASE][1] = 0.5f;
+ p->v[SP1_MUI_X_BASE][2] = DEF_STEPS;
+ p->v[SP1_MUI_X_BASE][3] = 0.0f; /* not a slot: see canon() */
+}
+
+static bool in_ring(const uint8_t *ring, int n, int d)
+{
+ for (int i = 0; i < n; i++) {
+ if (ring[i] == d) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool sp1_mui_dest_allowed(bool t_side, int d)
+{
+ return t_side ? in_ring(t_ring, T_RING_N, d) : in_ring(x_ring, X_RING_N, d);
+}
+
+/* Set the module's values from a patch. Out-of-range entries take the ROTC default (a
+ * sanitiser for internal callers; sp1_prst.c's field check is the one that reports). The
+ * zone selectors start at the zone their value is in, as the defaults' 6 and 57 always did. */
+static void apply(const struct sp1_mui_patch *p)
+{
+ struct sp1_mui_patch d;
+ sp1_mui_rip_patch(&d);
+ for (int l = 0; l < SP1_MUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ const float x = p->v[l][i];
+ stored[l][i] = isfinite(x) ? clamp01(x) : d.v[l][i];
+ }
+ }
+ model = (p->model >= 0 && p->model < 6) ? p->model : d.model;
+ t_range = (p->t_range >= 0 && p->t_range <= 2) ? p->t_range : d.t_range;
+ range = (p->range >= 0 && p->range < SP1_MRB_RANGE_COUNT) ? p->range : d.range;
+ diversity = (p->diversity >= 0 && p->diversity <= 2) ? p->diversity : d.diversity;
+ scale = sp1_mui_scale_included(p->scale) ? p->scale : d.scale;
+ dv_t = p->dv_t != 0;
+ dv_x = p->dv_x != 0;
+ for (int k = 0; k < 3; k++) {
+ route.t_dest[k] = (uint8_t)(sp1_mui_dest_allowed(true, p->t_dest[k])
+ ? p->t_dest[k] : d.t_dest[k]);
+ }
+ for (int k = 0; k < 4; k++) {
+ route.dest[k] = (uint8_t)(sp1_mui_dest_allowed(false, p->dest[k])
+ ? p->dest[k] : d.dest[k]);
+ }
+ q_ydiv = (int)(stored[SP1_MUI_Y][3] * 12.0f);
+ q_ydiv = q_ydiv > 11 ? 11 : q_ydiv;
+ q_length = (int)(stored[SP1_MUI_T_SHIFT][3] * (float)LOOP_STEPS);
+ q_length = q_length > LOOP_STEPS - 1 ? LOOP_STEPS - 1 : q_length;
}
/* ---- API ---------------------------------------------------------------------- */
void sp1_mui_init(void)
{
/* X_BASE[3] is not a slot: F4 there addresses T_BASE[3] (DEJA VU), see canon(). */
- defaults_base();
- defaults_pages();
- boot_routing();
+ struct sp1_mui_patch p;
+ defaults_base(&p);
+ defaults_pages(&p);
+ boot_routing(&p);
+ apply(&p);
page = SP1_MUI_PAGE_T;
settings = false;
active = SP1_MUI_T_BASE;
@@ -336,9 +392,39 @@ void sp1_mui_rip(void)
* whether SETTINGS is latched are kept (Adara, M4d). main.c re-seeds the random
* stream and re-draws the DEJA VU loop, and leaves the clock running.
* ⚠️ The faders do not move; pickup catches them up, as on PLAITS. */
- defaults_base();
- defaults_pages();
- rip_routing();
+ struct sp1_mui_patch p;
+ sp1_mui_rip_patch(&p);
+ sp1_mui_put(&p);
+}
+
+void sp1_mui_rip_patch(struct sp1_mui_patch *p)
+{
+ defaults_base(p);
+ defaults_pages(p);
+ rip_routing(p);
+}
+
+void sp1_mui_get(struct sp1_mui_patch *p)
+{
+ for (int l = 0; l < SP1_MUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ p->v[l][i] = stored[l][i];
+ }
+ }
+ p->model = model;
+ p->t_range = t_range;
+ p->range = range;
+ p->diversity = diversity;
+ p->scale = scale;
+ p->dv_t = dv_t ? 1 : 0;
+ p->dv_x = dv_x ? 1 : 0;
+ for (int k = 0; k < 3; k++) { p->t_dest[k] = route.t_dest[k]; }
+ for (int k = 0; k < 4; k++) { p->dest[k] = route.dest[k]; }
+}
+
+void sp1_mui_put(const struct sp1_mui_patch *p)
+{
+ apply(p);
activate(active);
}
diff --git a/firmware/src/sp1_marbles_ui.h b/firmware/src/sp1_marbles_ui.h
index 6748d90..10a30cc 100644
--- a/firmware/src/sp1_marbles_ui.h
+++ b/firmware/src/sp1_marbles_ui.h
@@ -155,8 +155,8 @@ bool sp1_mui_scale_step(int dir);
/* "••" + PLAY held 3 s on MARBLES: a **FULL WIPE** of the module (Adara, M4d --
* docs/DEFAULTS.md is the spec).
*
- * routing -> EVERY destination to none. ⚠️ So PLAY makes no sound afterwards until
- * something is dialled back in. That is the point of the gesture's name
+ * routing -> t2 -> TRIG, X2 -> V/Oct, everything else none (Adara, #50; through
+ * v0.7.2 every destination went to none)
* every fader-> its default, BASE included (t RATE/BIAS/JITTER, X SPREAD/BIAS/STEPS,
* the shared DEJA VU and LENGTH, the SHIFT pages and the Y page)
* buttons -> coin toss, x1 range, [J] INTELLIGENT, identical, major, [F] and [G] on
@@ -170,6 +170,28 @@ bool sp1_mui_scale_step(int dir);
* ⚠️ The faders do not move; pickup catches them up, as on PLAITS. */
void sp1_mui_rip(void);
+/* ---- the MARBLES half of a PRST slot (M6, #50) ----
+ * Every value of every layer (BPM and GTLT are fader values, so they come with them), the
+ * button settings and the routing. NOT the page on show (Wakes always comes up in PLAITS),
+ * not the clock's run/stop, not the seed (Adara: too temporary). */
+struct sp1_mui_patch {
+ float v[SP1_MUI_LAYERS][4]; /* stored values, 0..1; see canon() for the X F4s */
+ int model, t_range, range, diversity, scale;
+ int dv_t, dv_x; /* [F] and [G]: 0 / 1 */
+ int t_dest[3]; /* enum sp1_mui_dest, t ring */
+ int dest[4]; /* X1..X3, Y: enum sp1_mui_dest, X ring */
+};
+void sp1_mui_get(struct sp1_mui_patch *p);
+/* Load a patch; the page you are on is kept and pickup re-evaluated (as a rip). Sanitises
+ * rather than trusts -- anything out of its range takes the ROTC default -- but the real
+ * field check is sp1_prst.c's. */
+void sp1_mui_put(const struct sp1_mui_patch *p);
+/* What a MARBLES rip gives. sp1_mui_rip() is exactly this, then put: the ONE source of
+ * MARBLES' ROTC defaults, which PRST's field check also uses. */
+void sp1_mui_rip_patch(struct sp1_mui_patch *p);
+/* May destination `d` sit on a t output (t_side) / an X or Y output? (The two rings.) */
+bool sp1_mui_dest_allowed(bool t_side, int d);
+
/* ---- outputs ---- */
void sp1_mui_params(struct sp1_marbles_params *out);
void sp1_mui_routing(struct sp1_mui_routing *out);
diff --git a/firmware/src/sp1_plaits_ui.c b/firmware/src/sp1_plaits_ui.c
index 51ad850..8685e38 100644
--- a/firmware/src/sp1_plaits_ui.c
+++ b/firmware/src/sp1_plaits_ui.c
@@ -75,7 +75,12 @@ static bool locked[4]; /* inside CATCH_LOCK since that change
static enum sp1_pui_layer page = SP1_PUI_BASE;
static enum sp1_pui_layer active = SP1_PUI_BASE;
static bool base_seeded;
-static int slot = SP1_ENGINE_DEFAULT_SLOT; /* position in the generated table */
+/* 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
+ * 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;
static bool fnc_was;
static bool press_dirty; /* activity seen during this press */
@@ -104,6 +109,33 @@ static float clamp01(float x)
return x < 0.0f ? 0.0f : (x > 1.0f ? 1.0f : x);
}
+/* ---- engines, listed or not (#50) ---- */
+static bool offlist(int s)
+{
+ return s >= SP1_PUI_OFFLIST && s < SP1_PUI_OFFLIST + SP1_PLAITS_ENGINE_COUNT;
+}
+
+/* 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);
+}
+
+static int engine_of(int s)
+{
+ return offlist(s) ? s - SP1_PUI_OFFLIST : SP1_ENGINE_TABLE[s].plaits;
+}
+
+static uint8_t centre_of(int s)
+{
+ return SP1_PLAITS_ENGINES[engine_of(s)].centre;
+}
+
+static const char *name_of(int s)
+{
+ return SP1_PLAITS_ENGINES[engine_of(s)].name;
+}
+
/* ---- 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
@@ -118,7 +150,7 @@ static int eslot(void)
return slot;
}
int filled[SP1_ENGINE_SLOTS];
- int n = 0, here = 0;
+ 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 (i == slot) {
@@ -127,7 +159,7 @@ static int eslot(void)
filled[n++] = i;
}
}
- if (n <= 1) {
+ if (n <= 1 && !offlist(slot)) {
return slot;
}
const float step = off * (float)(n - 1);
@@ -166,7 +198,7 @@ static bool bipolar(enum sp1_pui_layer l, int i)
case SP1_PUI_SETTINGS:
return false; /* range, colour, decay, LEVEL */
default: {
- const uint8_t c = SP1_ENGINE_TABLE[eslot()].centre;
+ const uint8_t c = centre_of(eslot());
return (i == 1 && (c & C_T)) || (i == 2 && (c & C_M)) || (i == 3 && (c & C_H));
}
}
@@ -209,13 +241,14 @@ void sp1_pui_load_mods(const float shift[4], const float settings[4])
}
}
+/* SHIFT: four attenuverters, all at centre -- a gain of exactly ZERO. */
+static const float kShift[4] = { 0.5f, 0.5f, 0.5f, 0.5f };
+/* SETTINGS (M4a order): octave range 255/256 = full (plaits/settings.cc's own
+ * default), LPG colour 0, decay 128/256, LEVEL disconnected. */
+static const float kSettings[4] = { 255.0f / 256.0f, 0.0f, 0.5f, 0.0f };
+
void sp1_pui_default_mods(void)
{
- /* SHIFT: four attenuverters, all at centre -- a gain of exactly ZERO. */
- static const float kShift[4] = { 0.5f, 0.5f, 0.5f, 0.5f };
- /* SETTINGS (M4a order): octave range 255/256 = full (plaits/settings.cc's own
- * default), LPG colour 0, decay 128/256, LEVEL disconnected. */
- static const float kSettings[4] = { 255.0f / 256.0f, 0.0f, 0.5f, 0.0f };
sp1_pui_load_mods(kShift, kSettings);
/* The FREQUENCY quantizer is a SETTINGS-page value, so it resets with the page:
* off, i.e. every semitone available (M4b). */
@@ -411,7 +444,7 @@ void sp1_pui_params(struct sp1_synth_params *p)
const float *sh = stored[SP1_PUI_SHIFT];
const float *st = stored[SP1_PUI_SETTINGS];
const int es = eslot();
- const uint8_t c = SP1_ENGINE_TABLE[es].centre;
+ const uint8_t c = centre_of(es);
/* ---- MIDI is driving the pitch: the quantizer stands aside (M5a, Adara) ----
* While MIDI is active the FREQUENCY scale is bypassed -- no quantizing, no note
* latch, and mode 9 back to whole octaves. The selected scale is kept and returns at
@@ -519,7 +552,7 @@ void sp1_pui_params(struct sp1_synth_params *p)
p->lpg_colour = clamp01(st[1]);
p->decay = clamp01(st[2]);
- p->engine = SP1_ENGINE_TABLE[es].plaits;
+ p->engine = engine_of(es);
p->engine_centre = c; /* how a MIDI CC on F2-F4 reads (sp1_midi.h) */
}
@@ -551,9 +584,9 @@ enum sp1_pui_layer sp1_pui_active(void) { return active; }
enum sp1_pui_layer sp1_pui_page(void) { return page; }
bool sp1_pui_catching(int f) { return f >= 0 && f < 4 && catching[active][f]; }
bool sp1_pui_level_connected(void) { return stored[SP1_PUI_SETTINGS][3] >= LEVEL_OFF; }
-int sp1_pui_engine(void) { return SP1_ENGINE_TABLE[eslot()].plaits; }
+int sp1_pui_engine(void) { return engine_of(eslot()); }
int sp1_pui_slot(void) { return slot; }
-uint8_t sp1_pui_engine_centre(void) { return SP1_ENGINE_TABLE[eslot()].centre; }
+uint8_t sp1_pui_engine_centre(void) { return centre_of(eslot()); }
int sp1_pui_scale(void) { return scale; }
void sp1_pui_set_scale(int s)
@@ -597,16 +630,99 @@ void sp1_pui_rip(void)
* ⚠️ Neutral is a MOMENT IN TIME (Adara). Step to an engine with a different bipolar
* 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. */
- slot = SP1_ENGINE_DEFAULT_SLOT;
- const uint8_t c = SP1_ENGINE_TABLE[slot].centre;
- stored[SP1_PUI_BASE][0] = 0.5f; /* FREQUENCY -> C4 */
- stored[SP1_PUI_BASE][1] = (c & C_T) ? 0.5f : 0.0f; /* TIMBRE */
- stored[SP1_PUI_BASE][2] = (c & C_M) ? 0.5f : 0.0f; /* MORPH */
- stored[SP1_PUI_BASE][3] = (c & C_H) ? 0.5f : 0.0f; /* HARMONICS */
- sp1_pui_default_mods(); /* attenuverters 0, SETTINGS, quantizer off */
+ struct sp1_pui_patch p;
+ sp1_pui_rip_patch(SP1_ENGINE_DEFAULT_SLOT, &p);
+ 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;
+ }
+ const uint8_t c = centre_of(s);
+ p->slot = s;
+ p->v[SP1_PUI_BASE][0] = 0.5f; /* FREQUENCY -> C4 */
+ p->v[SP1_PUI_BASE][1] = (c & C_T) ? 0.5f : 0.0f; /* TIMBRE */
+ p->v[SP1_PUI_BASE][2] = (c & C_M) ? 0.5f : 0.0f; /* MORPH */
+ p->v[SP1_PUI_BASE][3] = (c & C_H) ? 0.5f : 0.0f; /* HARMONICS */
+ for (int i = 0; i < 4; i++) { /* attenuverters 0, SETTINGS */
+ p->v[SP1_PUI_SHIFT][i] = kShift[i];
+ p->v[SP1_PUI_SETTINGS][i] = kSettings[i];
+ }
+ p->scale = SP1_PUI_SCALE_OFF; /* quantizer off */
+}
+
+void sp1_pui_get(struct sp1_pui_patch *p)
+{
+ p->slot = slot;
+ for (int l = 0; l < SP1_PUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ p->v[l][i] = stored[l][i];
+ }
+ }
+ p->scale = scale;
+}
+
+void sp1_pui_put(const struct sp1_pui_patch *p)
+{
+ slot = slot_ok(p->slot) ? p->slot : SP1_ENGINE_DEFAULT_SLOT;
+ for (int l = 0; l < SP1_PUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ const float x = p->v[l][i];
+ stored[l][i] = isfinite(x) ? clamp01(x) : 0.0f;
+ }
+ }
+ sp1_pui_set_scale(p->scale); /* anything unknown -> off */
+ base_seeded = true;
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)) {
+ e = i;
+ break;
+ }
+ }
+ if (e < 0) {
+ return -1; /* not an engine of this build */
+ }
+ 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 */
+ }
+ }
+ return SP1_PUI_OFFLIST + e; /* in the build, off the list (#50) */
+}
+
+const char *sp1_pui_slot_name(int s)
+{
+ return slot_ok(s) ? name_of(s) : "";
+}
+
+bool sp1_pui_offlist(int s)
+{
+ return offlist(s);
+}
+
void sp1_pui_engine_leds(uint8_t out[4])
{
/* The engine PLAYING, not the one T2/T3 selected (Adara, M5a): with MIDI's MODEL CC
@@ -614,7 +730,7 @@ void sp1_pui_engine_leds(uint8_t out[4])
* the two are the same slot. */
sp1_pui_slot_leds(eslot(), out);
}
-const char *sp1_pui_engine_name(void) { return SP1_ENGINE_TABLE[eslot()].name; }
+const char *sp1_pui_engine_name(void) { return name_of(eslot()); }
int sp1_pui_eslot(void) { return eslot(); }
void sp1_pui_slot_leds(int s, uint8_t out[4])
@@ -623,6 +739,14 @@ void sp1_pui_slot_leds(int s, uint8_t out[4])
if (s < 0 || s >= SP1_ENGINE_SLOTS) {
s = slot;
}
+ if (s < 0 || s >= SP1_ENGINE_SLOTS) {
+ /* Off the list: no glyph of its own -- the list owns the glyphs. main.c draws
+ * the off-list animation instead (sp1_pui_offlist). Dark here. */
+ for (int i = 0; i < 4; i++) {
+ out[i] = 0u;
+ }
+ return;
+ }
for (int i = 0; i < 4; i++) {
const uint8_t k = SP1_ENGINE_TABLE[s].led[i];
out[i] = L[k < 3u ? k : 0u];
@@ -634,6 +758,18 @@ void sp1_pui_slot_leds(int s, uint8_t out[4])
* 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. */
+ int s2 = -1;
+ for (int i = 0; i < SP1_ENGINE_SLOTS; i++) {
+ if (SP1_ENGINE_TABLE[i].on && (s2 < 0 || dir < 0)) {
+ s2 = i;
+ }
+ }
+ slot = s2;
+ return slot;
+ }
int s2 = slot;
for (int n = 0; n < SP1_ENGINE_SLOTS; n++) {
s2 = (s2 + (dir < 0 ? SP1_ENGINE_SLOTS - 1 : 1)) % SP1_ENGINE_SLOTS;
diff --git a/firmware/src/sp1_plaits_ui.h b/firmware/src/sp1_plaits_ui.h
index 4a973e0..08688c7 100644
--- a/firmware/src/sp1_plaits_ui.h
+++ b/firmware/src/sp1_plaits_ui.h
@@ -71,8 +71,10 @@ void sp1_pui_init(void);
* all go through here so that when M5 makes these persist, loading a stored snapshot
* is a change to ONE call site rather than a hunt.
*
+ * (M6: a PRST slot loads through sp1_pui_put(), which sets these layers too.)
+ *
* ⚠️ The faders never seed these layers. Only BASE is seeded from the physical faders,
- * and only on the first ON after boot: an attenuverter that picked up wherever the
+ * and only on the first ON after boot (and not at all once a PRST slot is loaded): an attenuverter that picked up wherever the
* fader happened to be sitting would start the instrument modulating something the
* user did not ask for (Adara, from hardware). They start at gain 0 and stay there
* until a fader is moved WHILE the layer is showing, which pickup then catches. */
@@ -182,6 +184,42 @@ void sp1_pui_slot_leds(int slot, uint8_t out[4]);
*
* ⚠️ The faders do not move; pickup catches them up (Adara: by design). */
void sp1_pui_rip(void);
+
+/* ---- the PLAITS half of a PRST slot (M6, #50) ----
+ * Everything this module stores in a preset: the engine, the three layers' values and the
+ * 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 */
+ float v[SP1_PUI_LAYERS][4]; /* stored values, pot space 0..1 */
+ int scale; /* FREQUENCY quantizer, SP1_PUI_SCALE_OFF */
+};
+void sp1_pui_get(struct sp1_pui_patch *p);
+/* Load a patch: the faders do not move, pickup catches them up (Adara, as after a rip).
+ * Also marks BASE as seeded, so the next ON keeps these values instead of taking the
+ * faders. Sanitises rather than trusts: an empty or unknown slot -> slot 1, a value that is
+ * not a finite number -> 0, the rest clamped. The real field check is sp1_prst.c's. */
+void sp1_pui_put(const struct sp1_pui_patch *p);
+/* What a rip gives, with BASE at the neutral state of `slot`'s engine (0.5 bipolar, 0
+ * unipolar, F1 at C4). sp1_pui_rip() is exactly this for slot 1, then put. The ONE
+ * 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. */
+/* ---- engines OFF the list (#50) ----
+ * Every build contains all of Plaits' engines; config/engines.csv 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
+ * goes to the first listed engine and T2 to the last, and MIDI's MODEL CC counts from list
+ * 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. */
+int sp1_pui_slot_of(const char *name, int len);
+const char *sp1_pui_slot_name(int slot); /* "" for no engine */
+
const char *sp1_pui_engine_name(void);
/* The glyph of the engine PLAYING (sp1_pui_eslot: the selection moved by MIDI's MODEL CC) as
* LED levels -- fixed per slot, tools/gen_engines.py. What T1, T2/T3 and the module swap flash. */
diff --git a/firmware/src/sp1_power.c b/firmware/src/sp1_power.c
index b736dbd..19f5327 100644
--- a/firmware/src/sp1_power.c
+++ b/firmware/src/sp1_power.c
@@ -13,6 +13,9 @@
#include "sp1_led.h"
#include "sp1_ui_timing.h"
#include "sp1_audio.h"
+#if defined(CONFIG_SP1_STORAGE)
+#include "sp1_store.h"
+#endif
#include
#include
@@ -132,6 +135,13 @@ void sp1_quiesce_peripherals(void)
* else succeeding. Safe when audio was never started. */
sp1_audio_stop();
+#if defined(CONFIG_SP1_STORAGE)
+ /* M6 (#43): stop the storage thread's eMMC job and release the card's bus pins
+ * BEFORE its rail goes, so nothing drives an unpowered card. Never waits: a job cut
+ * short just fails its remaining steps (sp1_store.h). */
+ sp1_store_abort();
+#endif
+
/* The speaker amp, headphone codec, audio oscillator and eMMC I/O rail are
* separate chips held up by retained GPIO levels. Leaving them powered is
* what drains the battery overnight, and a clockless amp murmurs audibly.
@@ -309,6 +319,17 @@ static void gesture_reset(void)
bool sp1_power_on_hold(void)
{
uint32_t held = 0u;
+#if defined(CONFIG_SP1_DRIVE)
+ /* Drive mode (M6, #43, Adara): while the computer reads or writes the card, ON
+ * would take the card from under it, so every transfer restarts the FILL (not the
+ * dark window). ON needs SP1_PWR_ON_FILL_MS of quiet with "••" held. Only real block
+ * transfers count (sp1_store_activity), never the host's "medium?" polls, so an idle
+ * computer delays nothing. No time limit, deliberately (Adara): a limit would undo
+ * the protection, and eject or unplug always ends the transfers.
+ * ⚠️ Delays power-ON only. Power-off and the 30 s backstop are not in this path. */
+ uint32_t act_seen = sp1_store_activity();
+ uint32_t held_back = 0u;
+#endif
/* DO NOT initialise the LEDs here. The PWM devices are deferred-init, so
* during the silent window their pins are still untouched -- and that, not
@@ -367,6 +388,17 @@ bool sp1_power_on_hold(void)
return false;
}
+#if defined(CONFIG_SP1_DRIVE)
+ const uint32_t act = sp1_store_activity();
+ if (act != act_seen) {
+ act_seen = act;
+ if (held > SP1_PWR_ON_DARK_MS) {
+ held = SP1_PWR_ON_DARK_MS; /* the fill starts again */
+ held_back++;
+ }
+ }
+#endif
+
if (held >= SP1_PWR_ON_DARK_MS) {
/* Past the silent window: now it is safe to claim the pins.
* Idempotent, so this costs nothing after the first tick. */
@@ -397,6 +429,13 @@ bool sp1_power_on_hold(void)
held += SP1_TICK_MS;
}
+#if defined(CONFIG_SP1_DRIVE)
+ if (held_back > 0u) {
+ printk("PWR power-on fill restarted %u x by the computer's transfers\n",
+ held_back);
+ }
+#endif
+
/* Accepted, so the device is booting: make sure the rows are up even if the
* fill never ran (it always does, but do not depend on that). */
(void)sp1_led_init();
@@ -420,6 +459,13 @@ void sp1_power_on_gate(void)
}
}
+static void (*save_hook)(void);
+
+void sp1_power_set_save_hook(void (*fn)(void))
+{
+ save_hook = fn;
+}
+
enum sp1_power_result sp1_power_tick(uint32_t elapsed_ms, bool fnc_held)
{
/* ================================================================
@@ -571,7 +617,16 @@ enum sp1_power_result sp1_power_tick(uint32_t elapsed_ms, bool fnc_held)
* Plugged in, the destination is STANDBY, not
* SYSTEM_OFF -- and no reset is needed, because we
* are already awake. Unplugged, it is a real
- * SYSTEM_OFF. */
+ * SYSTEM_OFF.
+ *
+ * PRST (M6, #50): the save goes HERE, after the
+ * animation and before anything is powered down --
+ * and ONLY here. The 30 s backstop above never calls
+ * it (rule 5a: the forced power-off never waits for a
+ * save), and the hook is bounded (4 s, main.c). */
+ if (save_hook != NULL) {
+ save_hook();
+ }
if (sp1_usb_present()) {
sp1_quiesce_peripherals();
gesture_reset();
diff --git a/firmware/src/sp1_power.h b/firmware/src/sp1_power.h
index b6b32b8..39db2fe 100644
--- a/firmware/src/sp1_power.h
+++ b/firmware/src/sp1_power.h
@@ -69,6 +69,10 @@ bool sp1_fnc_pressed(void);
* left DISARMED until "••" is released, so a continuous press cannot roll from
* power-on straight into power-off.
*
+ * With CONFIG_SP1_DRIVE, every block the computer reads or writes restarts the fill, so
+ * ON needs SP1_PWR_ON_FILL_MS without a transfer (M6, #43): turning ON takes the card
+ * from the computer. No time limit; the hold blocks for as long as the transfers last.
+ *
* Does not power anything off; the caller decides what an early release means. */
bool sp1_power_on_hold(void);
@@ -116,6 +120,13 @@ enum sp1_power_result {
* no reset is involved, the device is simply already awake. */
enum sp1_power_result sp1_power_tick(uint32_t elapsed_ms, bool fnc_held);
+/* ---- PRST's save at shutdown (M6, #50) ----
+ * Called once when the ordinary shutdown animation COMPLETES, before the peripherals are
+ * quiesced -- on the way to STANDBY and to SYSTEM_OFF alike. Never from the 30 s backstop:
+ * the forced power-off does not wait for a save (rule 5a). The hook itself must be bounded
+ * and feed the watchdog (main.c's waits at most 4 s). NULL = none. */
+void sp1_power_set_save_hook(void (*fn)(void));
+
/* Tell the shutdown gesture that "••" was used as a modifier during this hold.
* Suppresses shutdown until "••" is released.
*
diff --git a/firmware/src/sp1_prst.c b/firmware/src/sp1_prst.c
new file mode 100644
index 0000000..58f7d34
--- /dev/null
+++ b/firmware/src/sp1_prst.c
@@ -0,0 +1,373 @@
+/* wakes-sp1 — PRST presets: the slot format and its field check. See sp1_prst.h. */
+#include "sp1_prst.h"
+
+#include
+#include
+#include
+#include
+
+/* ---- the field table, generated by tools/gen_prst.py ---- */
+struct sp1_prst_choice {
+ const char *tok;
+ int val;
+};
+struct sp1_prst_field {
+ const char *section;
+ const char *key;
+ uint8_t kind; /* SP1_PRST_K_* */
+ uint8_t check; /* SP1_PRST_C_* */
+ const struct sp1_prst_choice *ch; /* the tokens, for SP1_PRST_K_CHOICE */
+ uint8_t n_ch;
+ uint16_t off; /* into struct sp1_prst */
+};
+#include "sp1_prst_gen.h"
+
+/* Every choice list covers its whole enum: a value the firmware can hold but the file cannot
+ * name would be dropped at save and come back as the default. */
+#define N_OF(a) (sizeof(a) / sizeof((a)[0]))
+_Static_assert(N_OF(sp1_prst_ch_dest) == SP1_DEST_COUNT, "a destination has no token");
+_Static_assert(N_OF(sp1_prst_ch_scale) == SP1_MARBLES_SCALES, "a scale has no token");
+_Static_assert(N_OF(sp1_prst_ch_scale_off) == SP1_MARBLES_SCALES + 1, "quantizer tokens");
+_Static_assert(N_OF(sp1_prst_ch_output) == SP1_OUT_COUNT, "an output mode has no token");
+_Static_assert(N_OF(sp1_prst_ch_drive) == SP1_DRIVE_STEPS, "a drive step has no token");
+_Static_assert(N_OF(sp1_prst_ch_range) == SP1_MRB_RANGE_COUNT, "a [J] range has no token");
+_Static_assert(N_OF(sp1_prst_ch_t_model) == 6, "a t model has no token");
+_Static_assert(N_OF(sp1_prst_ch_burst) == 8, "burst divisions 1/1 .. 1/128");
+
+/* ---- text helpers ---- */
+struct span {
+ const char *p;
+ int n;
+};
+
+static int lower(int c)
+{
+ return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c;
+}
+
+static bool is_space(char c)
+{
+ return c == ' ' || c == '\t' || c == '\r';
+}
+
+static struct span trim(const char *p, int n)
+{
+ while (n > 0 && is_space(p[0])) {
+ p++;
+ n--;
+ }
+ while (n > 0 && is_space(p[n - 1])) {
+ n--;
+ }
+ return (struct span){ p, n };
+}
+
+/* Case-insensitive: the span equals the NUL-terminated `s`. */
+static bool eq(struct span a, const char *s)
+{
+ int k = 0;
+ for (; k < a.n; k++) {
+ if (s[k] == '\0' || lower((unsigned char)a.p[k]) != lower((unsigned char)s[k])) {
+ return false;
+ }
+ }
+ return s[k] == '\0';
+}
+
+static float *pos_at(struct sp1_prst *p, const struct sp1_prst_field *f)
+{
+ return (float *)((char *)p + f->off);
+}
+
+static int *int_at(struct sp1_prst *p, const struct sp1_prst_field *f)
+{
+ return (int *)((char *)p + f->off);
+}
+
+/* ---- defaults ---- */
+void sp1_prst_rip(struct sp1_prst *p, int slot)
+{
+ memset(p, 0, sizeof(*p));
+ sp1_pui_rip_patch(slot, &p->plaits);
+ sp1_mui_rip_patch(&p->marbles);
+ p->out_mode = SP1_PRST_DEF_OUT;
+ p->burst_div = (int)SP1_PRST_DEF_BURST;
+ p->drive = SP1_PRST_DEF_DRIVE;
+}
+
+/* ---- writing ---- */
+int sp1_prst_write(const struct sp1_prst *p, char *buf, size_t size)
+{
+ size_t at = 0;
+ const char *section = "";
+ int n = snprintf(buf, size, "; Wakes preset (PRST). A value Wakes cannot read loads "
+ "its default.\n[wakes]\nformat = %d\n", SP1_PRST_FORMAT);
+ if (n < 0 || (size_t)n >= size) {
+ return -1;
+ }
+ at = (size_t)n;
+ for (int i = 0; i < SP1_PRST_NFIELDS; i++) {
+ const struct sp1_prst_field *f = &SP1_PRST_FIELDS[i];
+ struct sp1_prst *const q = (struct sp1_prst *)p; /* read only */
+ if (strcmp(section, f->section) != 0) {
+ section = f->section;
+ n = snprintf(buf + at, size - at, "\n[%s]\n", section);
+ if (n < 0 || (size_t)n >= size - at) {
+ return -1;
+ }
+ at += (size_t)n;
+ }
+ if (f->kind == SP1_PRST_K_POS) {
+ float v = *pos_at(q, f);
+ v = isfinite(v) ? (v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v)) : 0.0f;
+ const int k = (int)(v * 10000.0f + 0.5f);
+ n = snprintf(buf + at, size - at, "%s = %d.%04d\n", f->key, k / 10000,
+ k % 10000);
+ } else if (f->kind == SP1_PRST_K_ENGINE) {
+ n = snprintf(buf + at, size - at, "%s = %s\n", f->key,
+ sp1_pui_slot_name(*int_at(q, f)));
+ } else {
+ const int v = *int_at(q, f);
+ const char *tok = NULL;
+ for (int c = 0; c < f->n_ch; c++) {
+ if (f->ch[c].val == v) {
+ tok = f->ch[c].tok;
+ break;
+ }
+ }
+ if (tok == NULL) {
+ continue; /* not representable: left out, so it loads its default */
+ }
+ n = snprintf(buf + at, size - at, "%s = %s\n", f->key, tok);
+ }
+ if (n < 0 || (size_t)n >= size - at) {
+ return -1;
+ }
+ at += (size_t)n;
+ }
+ return (int)at;
+}
+
+/* ---- reading ---- */
+
+/* A fader value: a plain decimal number in 0..1 -- digits, at most one point, nothing else.
+ * No sign, no exponent, no "nan" or "inf": anything strtof would accept beyond that is a
+ * value no Wakes ever wrote, so it is treated as corrupt rather than guessed at. */
+static bool parse_pos(struct span s, float *out)
+{
+ int i = 0, idig = 0, fdig = 0;
+ uint32_t ip = 0u, fnum = 0u, fden = 1u;
+ while (i < s.n && s.p[i] >= '0' && s.p[i] <= '9') {
+ if (idig < 3) {
+ ip = ip * 10u + (uint32_t)(s.p[i] - '0');
+ }
+ idig++;
+ i++;
+ }
+ if (i < s.n && s.p[i] == '.') {
+ i++;
+ while (i < s.n && s.p[i] >= '0' && s.p[i] <= '9') {
+ if (fdig < 8) {
+ fnum = fnum * 10u + (uint32_t)(s.p[i] - '0');
+ fden *= 10u;
+ }
+ fdig++;
+ i++;
+ }
+ }
+ if (i != s.n || idig + fdig == 0 || idig > 3) {
+ return false;
+ }
+ const float v = (float)ip + (float)fnum / (float)fden;
+ if (!(v >= 0.0f && v <= 1.0f)) {
+ return false;
+ }
+ *out = v;
+ return true;
+}
+
+static bool check_ok(uint8_t check, int v)
+{
+ switch (check) {
+ case SP1_PRST_C_SCALE: return v == SP1_PUI_SCALE_OFF || sp1_mui_scale_included(v);
+ case SP1_PRST_C_T_DEST: return sp1_mui_dest_allowed(true, v);
+ case SP1_PRST_C_X_DEST: return sp1_mui_dest_allowed(false, v);
+ default: return true;
+ }
+}
+
+static bool parse_choice(const struct sp1_prst_field *f, struct span s, int *out)
+{
+ for (int c = 0; c < f->n_ch; c++) {
+ if (eq(s, f->ch[c].tok)) {
+ if (!check_ok(f->check, f->ch[c].val)) {
+ return false;
+ }
+ *out = f->ch[c].val;
+ return true;
+ }
+ }
+ return false;
+}
+
+/* A format number: plain digits only. -1 = not one. */
+static int parse_format(struct span s)
+{
+ if (s.n < 1 || s.n > 6) {
+ return -1;
+ }
+ int v = 0;
+ for (int i = 0; i < s.n; i++) {
+ if (s.p[i] < '0' || s.p[i] > '9') {
+ return -1;
+ }
+ v = v * 10 + (s.p[i] - '0');
+ }
+ return v;
+}
+
+void sp1_prst_parse(const char *text, size_t len, struct sp1_prst *out,
+ struct sp1_prst_report *rep)
+{
+ struct span val[SP1_PRST_NFIELDS];
+ bool have[SP1_PRST_NFIELDS] = { false };
+ struct span fmt = { NULL, 0 };
+ bool have_fmt = false;
+ struct span section = { NULL, -1 }; /* -1: before any section, or a broken one */
+
+ rep->format = -1;
+ rep->format_ok = false;
+ rep->defaulted = 0;
+ rep->bad = 0;
+ rep->first_bad = NULL;
+
+ /* ---- one pass: remember the LAST value seen for every known key ---- */
+ size_t at = 0;
+ while (text != NULL && at < len) {
+ size_t end = at;
+ while (end < len && text[end] != '\n') {
+ end++;
+ }
+ const struct span line = trim(text + at, (int)(end - at));
+ at = end + 1u;
+ if (line.n == 0 || line.p[0] == ';' || line.p[0] == '#') {
+ continue;
+ }
+ if (line.p[0] == '[') {
+ section = (line.n >= 2 && line.p[line.n - 1] == ']')
+ ? trim(line.p + 1, line.n - 2) : (struct span){ NULL, -1 };
+ continue;
+ }
+ int eqat = 0;
+ while (eqat < line.n && line.p[eqat] != '=') {
+ eqat++;
+ }
+ if (eqat == line.n || section.n < 0) {
+ continue;
+ }
+ const struct span key = trim(line.p, eqat);
+ const struct span v = trim(line.p + eqat + 1, line.n - eqat - 1);
+ if (eq(section, "wakes") && eq(key, "format")) {
+ fmt = v;
+ have_fmt = true;
+ continue;
+ }
+ for (int i = 0; i < SP1_PRST_NFIELDS; i++) {
+ if (eq(section, SP1_PRST_FIELDS[i].section) &&
+ eq(key, SP1_PRST_FIELDS[i].key)) {
+ val[i] = v;
+ have[i] = true;
+ break;
+ }
+ }
+ }
+
+ /* ---- a format this firmware does not know: the whole slot is the defaults ---- */
+ rep->format = have_fmt ? parse_format(fmt) : -1;
+ if (rep->format != SP1_PRST_FORMAT) {
+ sp1_prst_rip(out, -1);
+ rep->defaulted = SP1_PRST_NFIELDS;
+ return;
+ }
+ rep->format_ok = true;
+
+ /* ---- the engine first: a bad BASE fader takes ITS neutral value ---- */
+ int slot = -1;
+ for (int i = 0; i < SP1_PRST_NFIELDS; i++) {
+ if (SP1_PRST_FIELDS[i].kind != SP1_PRST_K_ENGINE) {
+ continue;
+ }
+ if (have[i]) {
+ slot = sp1_pui_slot_of(val[i].p, val[i].n);
+ if (slot < 0) {
+ rep->bad++;
+ rep->first_bad = SP1_PRST_FIELDS[i].key;
+ }
+ }
+ if (slot < 0) {
+ rep->defaulted++;
+ }
+ }
+ sp1_prst_rip(out, slot); /* every default, the neutral BASE of that engine */
+
+ /* ---- every other field on its own ---- */
+ for (int i = 0; i < SP1_PRST_NFIELDS; i++) {
+ const struct sp1_prst_field *f = &SP1_PRST_FIELDS[i];
+ if (f->kind == SP1_PRST_K_ENGINE) {
+ continue;
+ }
+ if (!have[i]) {
+ rep->defaulted++;
+ continue;
+ }
+ bool ok;
+ if (f->kind == SP1_PRST_K_POS) {
+ float v;
+ ok = parse_pos(val[i], &v);
+ if (ok) {
+ *pos_at(out, f) = v;
+ }
+ } else {
+ int v;
+ ok = parse_choice(f, val[i], &v);
+ if (ok) {
+ *int_at(out, f) = v;
+ }
+ }
+ if (!ok) {
+ rep->defaulted++;
+ rep->bad++;
+ if (rep->first_bad == NULL) {
+ rep->first_bad = f->key;
+ }
+ }
+ }
+
+ /* ---- the V/Oct interlock (M4b): a quantizer AND a Marbles output on V/Oct ----
+ * Wakes never lets both exist (main.c turns the scale off when something is routed to
+ * V/Oct), so a file holding both was edited by hand or is corrupt. The routing is kept,
+ * as it would be on the device; the quantizer takes its default, off. */
+ if (out->plaits.scale != SP1_PUI_SCALE_OFF) {
+ for (int k = 0; k < 4; k++) {
+ if (out->marbles.dest[k] == SP1_DEST_VOCT) {
+ out->plaits.scale = SP1_PUI_SCALE_OFF;
+ rep->defaulted++;
+ rep->bad++;
+ if (rep->first_bad == NULL) {
+ rep->first_bad = "quantizer";
+ }
+ break;
+ }
+ }
+ }
+}
+
+int sp1_prst_format(void)
+{
+ return SP1_PRST_FORMAT;
+}
+
+int sp1_prst_fields(void)
+{
+ return SP1_PRST_NFIELDS;
+}
diff --git a/firmware/src/sp1_prst.h b/firmware/src/sp1_prst.h
new file mode 100644
index 0000000..e5d3e88
--- /dev/null
+++ b/firmware/src/sp1_prst.h
@@ -0,0 +1,97 @@
+/*
+ * wakes-sp1 — PRST presets: what a slot holds, and its file format (M6, #50).
+ *
+ * A slot is a `.prst` file of ini text on the eMMC (WAKES/PRST/1 .. 4, one file each; the
+ * storage side is sp1_store.h). This file is the format alone: turning the patch into text
+ * and text back into a patch. Pure C, no Zephyr, no storage -- the host suite
+ * (tools/host-tests/prsttest.c) drives it with corrupt files that would be miserable to
+ * make on the device.
+ *
+ * ---- what a slot holds (Adara, #50) ----
+ * Everything except VOL: PLAITS' engine, every fader and attenuverter, the quantizer, the
+ * output mode, the burst division and the drive; MARBLES' settings, ranges, routing and
+ * BPM. NOT the clock's run/stop, the module or page on show (Wakes always comes up in
+ * PLAITS with the clock stopped), or Marbles' seed and DEJA VU loop (too temporary).
+ *
+ * ---- the format ----
+ * Sections and keys from ONE table, tools/gen_prst.py (generated into sp1_prst_gen.h):
+ *
+ * [wakes]
+ * format = 1
+ * [plaits]
+ * engine = virtual analog
+ * timbre = 0.5000
+ * ...
+ *
+ * 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 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.
+ *
+ * ---- the field check (Adara, #50) ----
+ * "If a save file's field contains an impossible parameter -- NaN or a corrupt value -- load
+ * the ROTC default for that parameter instead to prevent crashing or bootloops." So every
+ * field is checked on its own and the rest of the file still loads:
+ * - a fader value must be a plain decimal number in 0..1 (no NaN, no infinity, no
+ * 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;
+ * - 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
+ * that was LOADED (Adara: what a rip on that engine gives).
+ * A format version this firmware does not know, or none at all, loads the WHOLE slot from
+ * defaults: a newer format's keys could mean something else here.
+ */
+#ifndef SP1_PRST_H
+#define SP1_PRST_H
+
+#include
+#include
+
+#include "sp1_plaits_ui.h"
+#include "sp1_marbles_ui.h"
+
+/* main.c's part of the PLAITS patch, at their ROTC defaults (docs/DEFAULTS.md). main.c's rip
+ * uses these too, so there is one set. */
+#define SP1_PRST_DEF_OUT SP1_OUT_MAIN
+#define SP1_PRST_DEF_BURST 5u /* 1/32: g_burst_div, 1/(1 << n) */
+#define SP1_PRST_DEF_DRIVE 0 /* off */
+
+struct sp1_prst {
+ struct sp1_pui_patch plaits;
+ int out_mode; /* enum sp1_synth_output */
+ int burst_div; /* 0..7: the FFWD burst at 1/(1 << burst_div) */
+ int drive; /* 0..SP1_DRIVE_STEPS-1 */
+ struct sp1_mui_patch marbles;
+};
+
+/* The ROTC default patch -- what ROTC on both modules gives -- with PLAITS' BASE at the
+ * neutral state of `slot`'s engine (slot 1 if that slot is empty). wakes-sp1-fresh writes
+ * this, for slot 1, into all four slots. */
+void sp1_prst_rip(struct sp1_prst *p, int slot);
+
+/* The patch as text, into buf (NUL-terminated). Returns its length, or -1 if `size` is too
+ * small. SP1_PRST_TEXT_MAX always fits. */
+#define SP1_PRST_TEXT_MAX 2048
+int sp1_prst_write(const struct sp1_prst *p, char *buf, size_t size);
+
+/* Text (need not be NUL-terminated) back into a patch, every field checked. ALWAYS leaves
+ * a complete, safe patch in *out, whatever the text was. */
+struct sp1_prst_report {
+ int format; /* the file's format, -1 if it had none */
+ bool format_ok; /* false: the whole slot is the defaults */
+ int defaulted; /* fields that took their default (missing + bad) */
+ int bad; /* ...of which present but rejected */
+ const char *first_bad; /* key of the first rejected field, or NULL */
+};
+void sp1_prst_parse(const char *text, size_t len, struct sp1_prst *out,
+ struct sp1_prst_report *rep);
+
+/* How many fields a slot file has (tools/gen_prst.py), for the log and the tests. */
+int sp1_prst_fields(void);
+/* The format this firmware writes and reads (tools/gen_prst.py). */
+int sp1_prst_format(void);
+
+#endif /* SP1_PRST_H */
diff --git a/firmware/src/sp1_standby.c b/firmware/src/sp1_standby.c
index c97a10f..5d3f107 100644
--- a/firmware/src/sp1_standby.c
+++ b/firmware/src/sp1_standby.c
@@ -5,6 +5,10 @@
#include "sp1_power.h"
#include "sp1_ui_timing.h"
#include "sp1_console.h"
+#if defined(CONFIG_SP1_DRIVE)
+#include "sp1_store.h"
+#include "sp1_usbd.h"
+#endif
#include
@@ -22,6 +26,14 @@ void sp1_standby_run(void)
sp1_charger_enable(true);
uint32_t poll_ms = SP1_STANDBY_POLL_MS; /* force a sample on entry */
uint32_t breath_ms = 0u;
+#if defined(CONFIG_SP1_DRIVE)
+ /* Drive mode (M6): the activity chase on the model row, T1 T3 T2 T4. */
+ static const uint8_t chase[4] = { 0u, 2u, 1u, 3u };
+ uint32_t act_seen = sp1_store_activity();
+ uint32_t step_ms = SP1_DRIVE_STEP_MS;
+ unsigned chase_i = 0u;
+ sp1_store_standby_enter();
+#endif
sp1_leds_all_off();
sp1_console_set_status_period(SP1_CONSOLE_PERIOD_STANDBY_MS);
@@ -113,13 +125,26 @@ void sp1_standby_run(void)
draw_bar(level, SP1_STANDBY_BAR_LEVEL);
}
- /* Status lights, dim, on the model row: T2 = plugged, T3 = charging.
- * T1/T4 stay dark so the pair reads as a symmetric indicator. */
- sp1_led_set(SP1_ROW_TRACK, 0, 0);
- sp1_led_set(SP1_ROW_TRACK, 1, SP1_STANDBY_STATUS_LEVEL);
- sp1_led_set(SP1_ROW_TRACK, 2,
- charging ? SP1_STANDBY_STATUS_LEVEL : 0u);
- sp1_led_set(SP1_ROW_TRACK, 3, 0);
+#if defined(CONFIG_SP1_DRIVE)
+ /* Drive mode: a host (not a charger) gets the card, once per visit. Then each
+ * tick that saw host transfers -- at most one step per SP1_DRIVE_STEP_MS --
+ * lights the next LED of the chase at 50 % and ramps it down. The transfer
+ * path only counts (sp1_store_activity); all of the drawing is here. */
+ sp1_store_standby_tick(sp1_usbd_host());
+ step_ms += SP1_TICK_MS;
+ const uint32_t act = sp1_store_activity();
+ if (act != act_seen && step_ms >= SP1_DRIVE_STEP_MS) {
+ act_seen = act;
+ step_ms = 0u;
+ const int led = chase[chase_i++ & 3u];
+ sp1_led_set(SP1_ROW_TRACK, led, SP1_DRIVE_LED_PEAK);
+ sp1_led_fade(SP1_ROW_TRACK, led, 0u, SP1_DRIVE_RAMP_MS);
+ }
+#endif
+
+ /* No status lights on the model row any more (Adara, M6): the play-row bar's
+ * breathing already says "charging", and the row belongs to the drive's
+ * activity. It stays dark otherwise. */
sp1_led_tick(SP1_TICK_MS);
k_msleep(SP1_TICK_MS);
diff --git a/firmware/src/sp1_store.c b/firmware/src/sp1_store.c
new file mode 100644
index 0000000..414be14
--- /dev/null
+++ b/firmware/src/sp1_store.c
@@ -0,0 +1,1178 @@
+/*
+ * wakes-sp1 — storage on the eMMC (M6, #43). See sp1_store.h.
+ *
+ * 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).
+ */
+#include "sp1_store.h"
+#include "sp1_emmc.h"
+#include "sp1_console.h"
+#if defined(CONFIG_SP1_STORAGE_TEST)
+#include "sp1_emmc_report.h"
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define DISK_NAME "EMMC" /* = CONFIG_FS_FATFS_CUSTOM_MOUNT_POINTS */
+#define MNT "/EMMC:"
+#define DIR_WAKES MNT "/WAKES"
+
+/* 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). */
+#define PART_START 8192u
+
+#define LINE(...) do { printk(__VA_ARGS__); sp1_console_pace(); } while (0)
+
+static volatile bool stop;
+
+/* ---- who owns the card (drive mode, M6) ----
+ * Two disks over one card: "EMMC" is Wakes' (FatFs, this thread) and "DRIVE" the host's
+ * (the mass-storage class, its own thread). Exactly one may move data at a time, decided by
+ * `owner` and enforced by `card_lock`, which every transfer on either disk holds -- so a
+ * change of owner, made under the lock, waits for the transfer in flight and no other. */
+enum owner { OWN_NONE = 0, OWN_WAKES, OWN_HOST };
+static atomic_t owner = ATOMIC_INIT(OWN_NONE);
+static K_MUTEX_DEFINE(card_lock);
+static atomic_t activity; /* host transfers, for STANDBY's LEDs */
+static atomic_t vol_state = ATOMIC_INIT(SP1_STORE_VOL_UNKNOWN);
+
+#if defined(CONFIG_SP1_STORAGE_TEST)
+/* Where the data region starts, from the last mount (FATFS database): the file test's
+ * mismatch report turns a cluster into an LBA with it. */
+static uint32_t r_data;
+#endif
+
+/* Jobs waiting for the thread (a bit each), so a request made while another job runs is
+ * queued rather than dropped: turning ON must always take the card back from a host. */
+#define JOB_ON BIT(0)
+#define JOB_HOST BIT(1)
+#define JOB_SAVE BIT(2)
+static atomic_t pending;
+
+/* What main's storage_gate() reads (sp1_store.h). */
+static atomic_t phase = ATOMIC_INIT(SP1_STORE_READY);
+static atomic_t fmt_result = ATOMIC_INIT(SP1_STORE_FMT_NONE);
+static atomic_t progress;
+static bool counting; /* a format is running: count its writes */
+static uint32_t fmt_written;
+static uint32_t fmt_expected = 1u;
+
+/* Every block write goes through here, so a format's progress can be counted. */
+static bool wr(uint32_t block, const uint8_t *buf)
+{
+ if (!sp1_emmc_write_block(block, buf)) {
+ return false;
+ }
+ if (counting) {
+ fmt_written++;
+ const uint32_t p = fmt_written * 255u / fmt_expected;
+ atomic_set(&progress, (atomic_val_t)(p > 254u ? 254u : p)); /* 255 = stamped */
+ }
+ return true;
+}
+
+/* ---------------------------------------------------------------- the disk */
+
+/* FatFs sees blocks [view_base, view_base + view_count). Normally the whole card; while
+ * formatting, the partition alone, so FatFs builds a volume that starts at the
+ * partition's first block (format_card). */
+static uint32_t view_base;
+static uint32_t view_count;
+
+static int d_init(struct disk_info *d)
+{
+ ARG_UNUSED(d);
+ return sp1_emmc_ready() ? 0 : -EIO; /* the job powers the card up itself */
+}
+
+static int d_status(struct disk_info *d)
+{
+ ARG_UNUSED(d);
+ return sp1_emmc_ready() ? DISK_STATUS_OK : DISK_STATUS_UNINIT;
+}
+
+static int d_read(struct disk_info *d, uint8_t *buf, uint32_t start, uint32_t n)
+{
+ ARG_UNUSED(d);
+ if (start >= view_count || n > view_count - start) {
+ return -EIO;
+ }
+ k_mutex_lock(&card_lock, K_FOREVER);
+ const bool ok = atomic_get(&owner) == OWN_WAKES &&
+ sp1_emmc_read_blocks(view_base + start, buf, n);
+ k_mutex_unlock(&card_lock);
+ return ok ? 0 : -EIO;
+}
+
+static int d_write(struct disk_info *d, const uint8_t *buf, uint32_t start, uint32_t n)
+{
+ ARG_UNUSED(d);
+ if (start >= view_count || n > view_count - start) {
+ return -EIO;
+ }
+ k_mutex_lock(&card_lock, K_FOREVER);
+ bool ok = atomic_get(&owner) == OWN_WAKES;
+ if (ok && counting) { /* a format: block by block, for the bar */
+ for (uint32_t i = 0; ok && i < n; i++) {
+ ok = wr(view_base + start + i, buf + i * SP1_EMMC_BLOCK);
+ }
+ } else if (ok) {
+ ok = sp1_emmc_write_blocks(view_base + start, buf, n);
+ }
+ k_mutex_unlock(&card_lock);
+ return ok ? 0 : -EIO;
+}
+
+static int d_ioctl(struct disk_info *d, uint8_t cmd, void *buf)
+{
+ ARG_UNUSED(d);
+ switch (cmd) {
+ case DISK_IOCTL_GET_SECTOR_COUNT:
+ *(uint32_t *)buf = view_count;
+ return 0;
+ case DISK_IOCTL_GET_SECTOR_SIZE:
+ *(uint32_t *)buf = SP1_EMMC_BLOCK;
+ return 0;
+ case DISK_IOCTL_GET_ERASE_BLOCK_SZ: /* in blocks: f_mkfs aligns the data area */
+ *(uint32_t *)buf = PART_START;
+ return 0;
+ case DISK_IOCTL_CTRL_SYNC: /* the card's write cache is off */
+ case DISK_IOCTL_CTRL_DEINIT: /* the job powers the card down itself */
+ return 0;
+ case DISK_IOCTL_CTRL_INIT:
+ return sp1_emmc_ready() ? 0 : -EIO;
+ default:
+ return -EINVAL;
+ }
+}
+
+static const struct disk_operations disk_ops = {
+ .init = d_init, .status = d_status, .read = d_read, .write = d_write,
+ .ioctl = d_ioctl,
+};
+
+static struct disk_info disk = { .name = DISK_NAME, .ops = &disk_ops };
+
+#if defined(CONFIG_SP1_DRIVE)
+/* ---------------------------------------------------------------- the host's disk */
+
+#include
+
+/* The whole card, block 0 (the MBR) included, so the host sees the partition table and
+ * mounts the FAT32 volume itself. "No medium" whenever the host does not own it -- which
+ * is how the drive looks while ON (Adara: the interface stays, the card goes). */
+#define HOST_DISK "DRIVE"
+
+static int h_init(struct disk_info *d)
+{
+ ARG_UNUSED(d);
+ return 0; /* the HOST job powers the card */
+}
+
+static int h_status(struct disk_info *d)
+{
+ ARG_UNUSED(d);
+ return (atomic_get(&owner) == OWN_HOST && sp1_emmc_ready()) ? DISK_STATUS_OK
+ : DISK_STATUS_NOMEDIA;
+}
+
+static int h_read(struct disk_info *d, uint8_t *buf, uint32_t start, uint32_t n)
+{
+ ARG_UNUSED(d);
+ k_mutex_lock(&card_lock, K_FOREVER);
+ const bool ok = atomic_get(&owner) == OWN_HOST && sp1_emmc_read_blocks(start, buf, n);
+ k_mutex_unlock(&card_lock);
+ atomic_inc(&activity);
+ return ok ? 0 : -EIO;
+}
+
+static int h_write(struct disk_info *d, const uint8_t *buf, uint32_t start, uint32_t n)
+{
+ ARG_UNUSED(d);
+ k_mutex_lock(&card_lock, K_FOREVER);
+ const bool ok = atomic_get(&owner) == OWN_HOST && sp1_emmc_write_blocks(start, buf, n);
+ k_mutex_unlock(&card_lock);
+ atomic_inc(&activity);
+ return ok ? 0 : -EIO;
+}
+
+static int h_ioctl(struct disk_info *d, uint8_t cmd, void *buf)
+{
+ ARG_UNUSED(d);
+ switch (cmd) {
+ case DISK_IOCTL_GET_SECTOR_COUNT:
+ *(uint32_t *)buf = sp1_emmc_sectors();
+ return 0;
+ case DISK_IOCTL_GET_SECTOR_SIZE:
+ *(uint32_t *)buf = SP1_EMMC_BLOCK;
+ return 0;
+ case DISK_IOCTL_GET_ERASE_BLOCK_SZ:
+ *(uint32_t *)buf = PART_START;
+ return 0;
+ case DISK_IOCTL_CTRL_SYNC: /* the card's write cache is off */
+ case DISK_IOCTL_CTRL_INIT:
+ case DISK_IOCTL_CTRL_DEINIT:
+ return 0;
+ default:
+ return -EINVAL;
+ }
+}
+
+static const struct disk_operations host_ops = {
+ .init = h_init, .status = h_status, .read = h_read, .write = h_write,
+ .ioctl = h_ioctl,
+};
+
+static struct disk_info host_disk = { .name = HOST_DISK, .ops = &host_ops };
+
+/* T10 identity: vendor 8 characters, product 16, revision 4. */
+USBD_DEFINE_MSC_LUN(sp1_drive, HOST_DISK, "Wakes", "SP-1 storage", "1.0");
+#endif /* CONFIG_SP1_DRIVE */
+
+/* ---------------------------------------------------------------- the volume */
+
+static FATFS fat;
+static struct fs_mount_t mnt = {
+ .type = FS_FATFS,
+ .fs_data = &fat,
+ .mnt_point = MNT,
+ /* ⚠️ Never format on mount. The only formatter is format_card(), fresh only. */
+ .flags = FS_MOUNT_FLAG_NO_FORMAT,
+};
+static bool mounted;
+
+static int mount_vol(void)
+{
+ if (!mounted) {
+ const int rc = fs_mount(&mnt);
+ mounted = (rc == 0);
+#if defined(CONFIG_SP1_STORAGE_TEST)
+ if (mounted) {
+ r_data = (uint32_t)fat.database;
+ }
+#endif
+ return rc;
+ }
+ return 0;
+}
+
+static void unmount_vol(void)
+{
+ if (mounted) {
+ (void)fs_unmount(&mnt);
+ mounted = false;
+ }
+}
+
+/* Used by the fresh stamp and the storage test now; by PRST (#43) next. */
+__maybe_unused static int write_file(const char *path, const void *d, size_t n)
+{
+ struct fs_file_t f;
+ fs_file_t_init(&f);
+ int rc = fs_open(&f, path, FS_O_CREATE | FS_O_WRITE);
+ if (rc != 0) {
+ return rc;
+ }
+ rc = fs_truncate(&f, 0);
+ if (rc == 0) {
+ const ssize_t w = fs_write(&f, d, n);
+ rc = (w == (ssize_t)n) ? 0 : (w < 0 ? (int)w : -EIO);
+ }
+ const int rc2 = fs_close(&f);
+ return rc != 0 ? rc : rc2;
+}
+
+__maybe_unused static int read_file(const char *path, void *d, size_t max, size_t *got)
+{
+ struct fs_file_t f;
+ fs_file_t_init(&f);
+ *got = 0;
+ int rc = fs_open(&f, path, FS_O_READ);
+ if (rc != 0) {
+ return rc;
+ }
+ const ssize_t r = fs_read(&f, d, max);
+ rc = (r < 0) ? (int)r : 0;
+ *got = (r > 0) ? (size_t)r : 0u;
+ (void)fs_close(&f);
+ return rc;
+}
+
+/* ---------------------------------------------------------------- fresh */
+
+#if defined(CONFIG_SP1_FRESH)
+
+#define STAMP DIR_WAKES "/FRESH.ID"
+
+#if defined(CONFIG_SP1_PLAITS)
+static int prst_write_defaults(void); /* the PRST section, below */
+#endif
+
+static uint8_t sec[SP1_EMMC_BLOCK]; /* block 0, the boot sectors, the MBR */
+
+/* Different for every build of the fresh image, so each one formats once. */
+static const char image_id[] = "Wakes v" APP_VERSION_STRING " fresh, built "
+ __DATE__ " " __TIME__;
+
+static void put32(uint8_t *p, uint32_t v)
+{
+ p[0] = (uint8_t)v;
+ p[1] = (uint8_t)(v >> 8);
+ p[2] = (uint8_t)(v >> 16);
+ p[3] = (uint8_t)(v >> 24);
+}
+
+/* One FAT32 partition at PART_START, the MBR written last. */
+static int format_card(void)
+{
+ const uint32_t total = sp1_emmc_sectors();
+ if (total < 4u * PART_START) {
+ return -EINVAL;
+ }
+
+ /* The progress bar's denominator: what f_mkfs writes for FAT32 (R0.16) -- the boot
+ * sector, its backup and the two FSINFO sectors, both FATs, the root cluster -- plus
+ * our block 0 twice, the two HiddSec patches, then WAKES' own cluster (mkdir zeroes
+ * all 64 blocks of it) and the stamp. Hardware 2026-10-07: 2035 writes, against
+ * 1966 before the mkdir cluster was counted (logs/sp1-20261007-173828.log). */
+ const uint32_t clusters = (total - PART_START) / 64u;
+ const uint32_t sz_fat = ((clusters + 2u) * 4u + SP1_EMMC_BLOCK - 1u) / SP1_EMMC_BLOCK;
+ fmt_expected = 4u + 2u * sz_fat + 64u + 4u + 64u + 6u;
+#if defined(CONFIG_SP1_PLAITS)
+ /* + PRST's folders and default slots (#50): five more directory clusters (PRST and
+ * 1..4, each zeroed by mkdir) and, per file (four slots and SLOT), roughly its data
+ * block, its directory entry and both FATs. An ESTIMATE until a log gives the count
+ * ("block writes against ... expected"); it only scales the progress bar. */
+ fmt_expected += 5u * 64u + 5u * 4u;
+#endif
+ fmt_written = 0u;
+ atomic_set(&progress, 0);
+ counting = true;
+
+ /* 1. Invalidate block 0 first: a format cut short then leaves NO partition table,
+ * rather than an old one pointing at a half-made volume. */
+ memset(sec, 0, sizeof(sec));
+ if (!wr(0, sec)) {
+ return -EIO;
+ }
+
+ /* 2. FAT32 into the partition, which FatFs sees as a whole disk. */
+ view_base = PART_START;
+ view_count = total - PART_START;
+ MKFS_PARM opt = {
+ .fmt = FM_FAT32 | FM_SFD, /* no table of its own: we write the MBR */
+ .n_fat = 2, /* as a computer's formatter would */
+ .align = 0, /* from the disk: PART_START (erase group) */
+ .n_root = 0, /* FAT32: root is a cluster chain */
+ .au_size = 32768, /* 32 KB clusters */
+ };
+ int rc = fs_mkfs(FS_FATFS, (uintptr_t)DISK_NAME ":", &opt, 0);
+ view_base = 0;
+ view_count = total;
+ if (rc != 0) {
+ return rc;
+ }
+
+ /* 3. BPB_HiddSec (offset 28) = the partition's start, in the boot sector and its
+ * backup (BPB_BkBootSec, offset 50). FatFs ignores it; other systems may not. */
+ if (!sp1_emmc_read_block(PART_START, sec) || memcmp(&sec[82], "FAT32", 5) != 0) {
+ return -EIO;
+ }
+ const uint32_t backup = (uint32_t)sec[50] | ((uint32_t)sec[51] << 8);
+ put32(&sec[28], PART_START);
+ if (!wr(PART_START, sec)) {
+ return -EIO;
+ }
+ if (backup != 0u) {
+ if (!sp1_emmc_read_block(PART_START + backup, sec)) {
+ return -EIO;
+ }
+ put32(&sec[28], PART_START);
+ if (!wr(PART_START + backup, sec)) {
+ return -EIO;
+ }
+ }
+
+ /* 4. The MBR: one partition, type 0x0C (FAT32, LBA). CHS fields are the
+ * "beyond CHS" marker; everything reads the LBA fields. */
+ memset(sec, 0, sizeof(sec));
+ put32(&sec[440], k_cycle_get_32() ^ total); /* disk signature */
+ uint8_t *e = &sec[446];
+ e[0] = 0x00;
+ e[1] = 0xfe; e[2] = 0xff; e[3] = 0xff;
+ e[4] = 0x0c;
+ e[5] = 0xfe; e[6] = 0xff; e[7] = 0xff;
+ put32(&e[8], PART_START);
+ put32(&e[12], total - PART_START);
+ sec[510] = 0x55;
+ sec[511] = 0xaa;
+ return wr(0, sec) ? 0 : -EIO;
+}
+
+static void fresh(void)
+{
+ static char found[sizeof(image_id) + 8];
+ size_t n = 0;
+ const int mrc = mount_vol();
+ int rc = mrc;
+ if (rc == 0) {
+ rc = read_file(STAMP, found, sizeof(found) - 1u, &n);
+ found[rc == 0 ? n : 0u] = '\0';
+ if (rc == 0 && strcmp(found, image_id) == 0) {
+ LINE("STORE fresh: formatted by this image already -- not formatting\n");
+ return;
+ }
+ }
+ if (mrc != 0) {
+ LINE("STORE fresh: no Wakes filesystem on the card -- FORMATTING\n");
+ } else if (rc != 0) {
+ LINE("STORE fresh: a filesystem with no fresh stamp -- FORMATTING\n");
+ } else {
+ LINE("STORE fresh: formatted by \"%s\" -- FORMATTING\n", found);
+ }
+ unmount_vol();
+
+ /* From here main's storage_gate() shows the progress bar and holds the UI. */
+ atomic_set(&fmt_result, SP1_STORE_FMT_FAILED); /* until it is stamped */
+ atomic_set(&phase, SP1_STORE_FORMATTING);
+ const uint32_t t0 = k_uptime_get_32();
+ rc = format_card();
+ LINE("STORE fresh: format %s (%d) in %u ms: FAT32 at block %u, %u blocks\n",
+ rc == 0 ? "done" : "FAILED", rc, (unsigned)(k_uptime_get_32() - t0),
+ (unsigned)PART_START, (unsigned)(sp1_emmc_sectors() - PART_START));
+ if (rc == 0 && !stop) {
+ rc = mount_vol();
+ if (rc == 0) {
+ rc = fs_mkdir(DIR_WAKES);
+ }
+ if (rc == 0) {
+ /* The volume label: what a computer calls the drive instead of
+ * "Removable Disk" (Adara). FAT labels are upper case; '-' is legal. */
+ const FRESULT fr = f_setlabel(DISK_NAME ":SP-1");
+ rc = (fr == FR_OK) ? 0 : -EIO;
+ }
+#if defined(CONFIG_SP1_PLAITS)
+ if (rc == 0) {
+ /* PRST (#50, Adara): the folders, and the ROTC patch in every slot. */
+ rc = prst_write_defaults();
+ }
+#endif
+ if (rc == 0) {
+ /* The stamp goes LAST: if anything before it failed, the next ON
+ * formats again. */
+ rc = write_file(STAMP, image_id, strlen(image_id));
+ }
+ LINE("STORE fresh: %s \"%s\"%s\n", rc == 0 ? "stamped" : "stamp FAILED",
+ image_id, rc == 0 ? "" : " -- will format again at the next ON");
+ }
+ counting = false;
+ LINE("STORE fresh: %u block writes against %u expected\n", (unsigned)fmt_written,
+ (unsigned)fmt_expected);
+ if (rc == 0 && !stop) {
+ atomic_set(&progress, 255);
+ atomic_set(&fmt_result, SP1_STORE_FMT_DONE);
+ }
+ unmount_vol(); /* the ON job mounts again and decides the volume state */
+}
+
+#endif /* CONFIG_SP1_FRESH */
+
+/* ---------------------------------------------------------------- the test */
+
+#if defined(CONFIG_SP1_STORAGE_TEST)
+
+#define BOOTS DIR_WAKES "/BOOTS.TXT"
+#define TESTFILE DIR_WAKES "/TEST.BIN"
+#define TEST_KB 512u
+/* 16 KB chunks: FatFs hands a whole-sector write straight to the disk, so each one is a
+ * 32-block burst -- what fast transfer is for. Test builds only. */
+#define CHUNK 16384u
+static uint8_t bulk[CHUNK];
+
+static uint8_t pattern(uint32_t i, uint32_t seed)
+{
+ return (uint8_t)(i * 131u + seed * 7u + (i >> 9));
+}
+
+static void file_test(void)
+{
+ int rc = fs_mkdir(DIR_WAKES);
+ if (rc != 0 && rc != -EEXIST) {
+ LINE("STORE test: mkdir WAKES FAILED (%d)\n", rc);
+ return;
+ }
+
+ /* A counter that survives power cycles and reflashes: read, +1, write, read back. */
+ char txt[16];
+ size_t n = 0;
+ uint32_t boots = 0;
+ if (read_file(BOOTS, txt, sizeof(txt) - 1u, &n) == 0) {
+ for (size_t i = 0; i < n && txt[i] >= '0' && txt[i] <= '9'; i++) {
+ boots = boots * 10u + (uint32_t)(txt[i] - '0');
+ }
+ }
+ boots++;
+ snprintk(txt, sizeof(txt), "%u\n", (unsigned)boots);
+ rc = write_file(BOOTS, txt, strlen(txt));
+ char back[16];
+ if (rc == 0) {
+ rc = read_file(BOOTS, back, sizeof(back) - 1u, &n);
+ }
+ const bool same = (rc == 0 && n == strlen(txt) && memcmp(back, txt, n) == 0);
+ LINE("STORE test: ON entries on this card: %u (%s)\n", (unsigned)boots,
+ same ? "written, read back" : "FAILED");
+
+ /* 512 KB of a pattern, in 16 KB chunks: write, read back, compare, delete. The
+ * pattern is generated outside the timed span so the figure is the transfer's. */
+ struct fs_file_t f;
+ fs_file_t_init(&f);
+ uint32_t wms = 0;
+ rc = fs_open(&f, TESTFILE, FS_O_CREATE | FS_O_WRITE);
+ for (uint32_t c = 0; rc == 0 && c < TEST_KB * 1024u / CHUNK && !stop; c++) {
+ for (uint32_t i = 0; i < CHUNK; i++) {
+ bulk[i] = pattern(c * CHUNK + i, boots);
+ }
+ const uint32_t t0 = k_uptime_get_32();
+ const ssize_t w = fs_write(&f, bulk, CHUNK);
+ wms += k_uptime_get_32() - t0;
+ rc = (w == (ssize_t)CHUNK) ? 0 : -EIO;
+ }
+ if (fs_close(&f) != 0 && rc == 0) {
+ rc = -EIO;
+ }
+ if (rc != 0 || stop) {
+ LINE("STORE test: write %u KB FAILED (%d)\n", (unsigned)TEST_KB, rc);
+ return;
+ }
+ uint32_t rms = 0;
+ uint32_t bad = 0;
+ uint32_t bad_blocks = 0;
+ int32_t first_bad = -1; /* block index within the file */
+ uint8_t seen[32] = { 0 }; /* what the first bad block held */
+ uint32_t sclust = 0;
+ fs_file_t_init(&f);
+ rc = fs_open(&f, TESTFILE, FS_O_READ);
+ if (rc == 0) {
+ sclust = (uint32_t)((FIL *)f.filep)->obj.sclust;
+ }
+ for (uint32_t c = 0; rc == 0 && c < TEST_KB * 1024u / CHUNK && !stop; c++) {
+ const uint32_t t0 = k_uptime_get_32();
+ const ssize_t r = fs_read(&f, bulk, CHUNK);
+ rms += k_uptime_get_32() - t0;
+ rc = (r == (ssize_t)CHUNK) ? 0 : -EIO;
+ for (uint32_t b = 0; rc == 0 && b < CHUNK / SP1_EMMC_BLOCK; b++) {
+ uint32_t diff = 0;
+ for (uint32_t i = 0; i < SP1_EMMC_BLOCK; i++) {
+ const uint32_t at = b * SP1_EMMC_BLOCK + i;
+ diff += (bulk[at] != pattern(c * CHUNK + at, boots));
+ }
+ if (diff != 0u) {
+ bad += diff;
+ bad_blocks++;
+ if (first_bad < 0) {
+ first_bad = (int32_t)(c * (CHUNK / SP1_EMMC_BLOCK) + b);
+ memcpy(seen, &bulk[b * SP1_EMMC_BLOCK], sizeof(seen));
+ }
+ }
+ }
+ }
+ (void)fs_close(&f);
+ LINE("STORE test: %u KB written in %u ms (%u KB/s), read back in %u ms (%u KB/s):"
+ " %s\n", (unsigned)TEST_KB, (unsigned)wms,
+ wms ? (unsigned)(TEST_KB * 1000u / wms) : 0u, (unsigned)rms,
+ rms ? (unsigned)(TEST_KB * 1000u / rms) : 0u,
+ rc != 0 ? "read FAILED" : (bad ? "MISMATCH" : "identical"));
+ if (bad) {
+ /* Where it went wrong and what was there instead: a directory sector reads as
+ * 8.3 names, a FAT sector as little-endian cluster numbers, another file's
+ * data as anything else. The file's clusters are 64 blocks each; if they are
+ * contiguous, block k is at LBA data + (sclust - 2) * 64 + k. */
+ LINE("STORE test: %u bytes differ in %u block(s); first bad block %d of the file, "
+ "file starts at cluster %u (LBA %u if contiguous: %u)\n", (unsigned)bad,
+ (unsigned)bad_blocks, (int)first_bad, (unsigned)sclust,
+ (unsigned)(r_data + (sclust - 2u) * 64u),
+ (unsigned)(r_data + (sclust - 2u) * 64u + (uint32_t)first_bad));
+ char hex[sizeof(seen) * 3 + 1];
+ for (size_t i = 0; i < sizeof(seen); i++) {
+ static const char hx[] = "0123456789abcdef";
+ hex[3 * i] = ' ';
+ hex[3 * i + 1] = hx[seen[i] >> 4];
+ hex[3 * i + 2] = hx[seen[i] & 15u];
+ }
+ hex[sizeof(hex) - 1] = '\0';
+ LINE("STORE test: it held:%s\n", hex);
+ }
+ rc = fs_unlink(TESTFILE);
+ LINE("STORE test: TEST.BIN %s\n", rc == 0 ? "deleted" : "delete FAILED");
+
+ struct fs_statvfs sv;
+ if (fs_statvfs(MNT, &sv) == 0) {
+ const uint64_t unit = (uint64_t)sv.f_frsize;
+ LINE("STORE test: volume %u MB, free %u MB, %u-byte clusters\n",
+ (unsigned)((sv.f_blocks * unit) >> 20), (unsigned)((sv.f_bfree * unit) >> 20),
+ (unsigned)unit);
+ }
+ struct fs_dir_t dir;
+ fs_dir_t_init(&dir);
+ if (fs_opendir(&dir, DIR_WAKES) == 0) {
+ struct fs_dirent ent;
+ while (fs_readdir(&dir, &ent) == 0 && ent.name[0] != '\0') {
+ LINE("STORE test: WAKES/%s %u B\n", ent.name, (unsigned)ent.size);
+ }
+ (void)fs_closedir(&dir);
+ }
+}
+
+#endif /* CONFIG_SP1_STORAGE_TEST */
+
+/* ---------------------------------------------------------------- PRST (#50) */
+
+#if defined(CONFIG_SP1_PLAITS)
+
+#define DIR_PRST DIR_WAKES "/PRST"
+#define SLOT_FILE DIR_PRST "/SLOT"
+/* The save's temporary file, in the slot's own folder. Not a `.prst`, so it is never
+ * loaded -- a save cut short between its write and the rename leaves it behind, and the
+ * next save of that slot replaces it. */
+#define TMP_NAME "SAVE.TMP"
+#define PATH_MAX_ (sizeof(DIR_PRST) + 16u + MAX_FILE_NAME + 1u) /* "//" */
+
+static void claim_for_wakes(void);
+
+static atomic_t prst_state = ATOMIC_INIT(SP1_STORE_PRST_WAIT);
+static atomic_t save_state = ATOMIC_INIT(SP1_STORE_SAVE_IDLE);
+static struct sp1_prst prst_slot[SP1_PRST_SLOTS];
+/* The file each slot was loaded from ("" = the folder had none): the one a save replaces. */
+static char prst_name[SP1_PRST_SLOTS][MAX_FILE_NAME + 1];
+static int prst_current;
+static char load_text[SP1_PRST_TEXT_MAX]; /* this thread's */
+static char save_text[SP1_PRST_TEXT_MAX]; /* main fills it, then queues */
+static size_t save_len;
+static int save_slot;
+
+static int lower_c(int c)
+{
+ return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c;
+}
+
+/* Alphabetical as Adara decided: case ignored, otherwise byte order. */
+static int name_cmp(const char *a, const char *b)
+{
+ for (;; a++, b++) {
+ const int x = lower_c((unsigned char)*a), y = lower_c((unsigned char)*b);
+ if (x != y || x == 0) {
+ return x - y;
+ }
+ }
+}
+
+static bool is_prst(const char *n)
+{
+ const size_t len = strlen(n);
+ return len >= 5u && name_cmp(n + len - 5u, ".prst") == 0;
+}
+
+/* One slot: the first `.prst` of its folder, read and checked field by field. 0, or the
+ * filesystem's error -- a missing folder is not one (that slot is the ROTC defaults). */
+static int load_slot(int i)
+{
+ static struct fs_dirent ent;
+ static char path[PATH_MAX_];
+ char *const best = prst_name[i];
+ best[0] = '\0';
+ snprintk(path, sizeof(path), DIR_PRST "/%d", i + 1);
+ struct fs_dir_t dir;
+ fs_dir_t_init(&dir);
+ int rc = fs_opendir(&dir, path);
+ if (rc == -ENOENT) {
+ rc = 0; /* no folder: an empty slot */
+ } else if (rc == 0) {
+ for (;;) {
+ rc = fs_readdir(&dir, &ent);
+ if (rc != 0 || ent.name[0] == '\0' || stop) {
+ break;
+ }
+ if (ent.type == FS_DIR_ENTRY_FILE && is_prst(ent.name) &&
+ (best[0] == '\0' || name_cmp(ent.name, best) < 0)) {
+ strncpy(best, ent.name, MAX_FILE_NAME);
+ best[MAX_FILE_NAME] = '\0';
+ }
+ }
+ (void)fs_closedir(&dir);
+ }
+ if (rc != 0) {
+ return rc;
+ }
+ struct sp1_prst_report r;
+ if (best[0] == '\0') {
+ sp1_prst_rip(&prst_slot[i], -1);
+ LINE("STORE PRST %d: no .prst -- the ROTC defaults\n", i + 1);
+ return 0;
+ }
+ size_t n = 0;
+ snprintk(path, sizeof(path), DIR_PRST "/%d/%.255s", i + 1, best);
+ rc = read_file(path, load_text, sizeof(load_text), &n);
+ if (rc != 0) {
+ return rc;
+ }
+ sp1_prst_parse(load_text, n, &prst_slot[i], &r);
+ if (!r.format_ok) {
+ LINE("STORE PRST %d: %s -- format %d is not %d: the ROTC defaults\n", i + 1, best,
+ r.format, sp1_prst_format());
+ } else if (r.defaulted > 0) {
+ LINE("STORE PRST %d: %s (%u B) -- %d of %d fields at their defaults, %d bad%s%s\n",
+ i + 1, best, (unsigned)n, r.defaulted, sp1_prst_fields(), r.bad,
+ r.first_bad ? ", first " : "", r.first_bad ? r.first_bad : "");
+ } else {
+ LINE("STORE PRST %d: %s (%u B)\n", i + 1, best, (unsigned)n);
+ }
+ return 0;
+}
+
+/* Inside the ON job, the volume mounted: SLOT and the four slots. */
+static void prst_load_all(void)
+{
+ char t[8];
+ size_t n = 0;
+ prst_current = 0;
+ if (read_file(SLOT_FILE, t, sizeof(t), &n) == 0) {
+ size_t k = 0;
+ while (k < n && (t[k] == ' ' || t[k] == '\t')) {
+ k++;
+ }
+ if (k < n && t[k] >= '1' && t[k] <= '0' + SP1_PRST_SLOTS) {
+ prst_current = t[k] - '1';
+ }
+ }
+ for (int i = 0; i < SP1_PRST_SLOTS; i++) {
+ const int rc = stop ? -ECANCELED : load_slot(i);
+ if (rc != 0) {
+ atomic_set(&prst_state, SP1_STORE_PRST_OFF);
+ LINE("STORE PRST off: reading slot %d failed (%d) -- defaults, no save\n",
+ i + 1, rc);
+ return;
+ }
+ }
+ atomic_set(&prst_state, SP1_STORE_PRST_READY);
+ 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
+ * again at the next ON. In this thread, so its own text buffer. */
+static int prst_write_defaults(void)
+{
+ static char path[PATH_MAX_];
+ struct sp1_prst p;
+ sp1_prst_rip(&p, -1);
+ const int n = sp1_prst_write(&p, load_text, sizeof(load_text));
+ if (n < 0) {
+ return -ENOMEM;
+ }
+ int rc = ensure_dir(DIR_PRST);
+ for (int i = 0; rc == 0 && i < SP1_PRST_SLOTS && !stop; i++) {
+ snprintk(path, sizeof(path), DIR_PRST "/%c", (char)('1' + i));
+ rc = ensure_dir(path);
+ if (rc == 0) {
+ snprintk(path, sizeof(path), DIR_PRST "/%c/%c.prst", (char)('1' + i),
+ (char)('1' + i));
+ rc = write_file(path, load_text, (size_t)n);
+ }
+ }
+ if (rc == 0 && !stop) {
+ rc = write_file(SLOT_FILE, "1\n", 2u);
+ }
+ LINE("STORE fresh: PRST slots 1-4 = the ROTC patch (%d B each), SLOT 1: %s (%d)\n",
+ n, rc == 0 ? "written" : "FAILED", rc);
+ return stop ? -ECANCELED : rc;
+}
+#endif
+
+/* The save, at shutdown. The card was powered down after the ON job, so it 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();
+ }
+ snprintk(tmp, sizeof(tmp), DIR_PRST "/%d", i + 1);
+ if (rc == 0 && !stop) {
+ rc = ensure_dir(DIR_WAKES);
+ }
+ if (rc == 0 && !stop) {
+ rc = ensure_dir(DIR_PRST);
+ }
+ if (rc == 0 && !stop) {
+ rc = ensure_dir(tmp);
+ }
+ if (prst_name[i][0] == '\0') {
+ snprintk(prst_name[i], sizeof(prst_name[i]), "%d.prst", i + 1);
+ }
+ snprintk(dst, sizeof(dst), DIR_PRST "/%d/%.255s", i + 1, prst_name[i]);
+ snprintk(tmp, sizeof(tmp), DIR_PRST "/%d/" TMP_NAME, i + 1);
+ if (rc == 0 && !stop) {
+ rc = write_file(tmp, save_text, save_len);
+ }
+ if (rc == 0 && !stop) {
+ rc = fs_rename(tmp, dst); /* replaces dst (Zephyr's FAT rename) */
+ }
+ if (rc == 0 && !stop) {
+ const char t[2] = { (char)('1' + i), '\n' };
+ rc = write_file(SLOT_FILE, t, sizeof(t));
+ }
+ 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);
+}
+
+#endif /* CONFIG_SP1_PLAITS */
+
+/* ---------------------------------------------------------------- the jobs */
+
+/* Take the card for Wakes. Under the lock, so a host transfer in flight finishes first
+ * (Adara: "after any write already in progress", bounded by the driver's own timeouts) and
+ * no new one starts: from here the host's disk reads "no medium". */
+static void claim_for_wakes(void)
+{
+ const bool was_host = atomic_get(&owner) == OWN_HOST;
+ atomic_set(&owner, OWN_NONE);
+ k_mutex_lock(&card_lock, K_FOREVER);
+ atomic_set(&owner, OWN_WAKES);
+ k_mutex_unlock(&card_lock);
+#if defined(CONFIG_SP1_DRIVE)
+ if (was_host) {
+ LINE("STORE drive: the host lets go -- the card is Wakes' again\n");
+ }
+#else
+ ARG_UNUSED(was_host);
+#endif
+}
+
+static void job_on_enter(void)
+{
+ const uint32_t t0 = k_uptime_get_32();
+ claim_for_wakes();
+ struct sp1_emmc_ident id;
+ const bool ok = sp1_emmc_init(&id); /* a fresh start whoever had the card */
+ view_base = 0;
+ view_count = sp1_emmc_sectors();
+#if defined(CONFIG_SP1_STORAGE_TEST)
+ sp1_emmc_report_init(ok, &id);
+#endif
+#if defined(CONFIG_SP1_FRESH)
+ if (ok && !stop) {
+ fresh();
+ }
+#endif
+ /* Past the fresh step, whatever happened: main's storage_gate() lets the UI go.
+ * The report and the file test below run with the UI live. */
+ atomic_set(&phase, SP1_STORE_READY);
+ if (!ok && !stop) {
+ atomic_set(&vol_state, SP1_STORE_VOL_NONE);
+ LINE("STORE PRST off: the eMMC did not start\n");
+ }
+#if defined(CONFIG_SP1_PLAITS)
+ if (!ok) {
+ atomic_set(&prst_state, SP1_STORE_PRST_OFF);
+ }
+#endif
+ if (ok && !stop) {
+#if defined(CONFIG_SP1_STORAGE_TEST)
+ if (!stop) {
+ sp1_emmc_report_card();
+ }
+#endif
+ /* Is it formatted? (Adara: if not, boot, but PRST and its combos are off;
+ * only wakes-sp1-fresh formats.) */
+ const int rc = stop ? -ECANCELED : mount_vol();
+ if (!stop) {
+ atomic_set(&vol_state, rc == 0 ? SP1_STORE_VOL_OK : SP1_STORE_VOL_NONE);
+ if (rc == 0) {
+ LINE("STORE volume ok\n");
+ } else {
+ LINE("STORE PRST off: no filesystem on the eMMC (%d) -- nothing "
+ "written; wakes-sp1-fresh creates one\n", rc);
+ }
+ }
+#if defined(CONFIG_SP1_PLAITS)
+ /* PRST (#50): all four slots into RAM, before main starts audio. */
+ if (rc == 0 && !stop) {
+ prst_load_all();
+ } else {
+ atomic_set(&prst_state, SP1_STORE_PRST_OFF);
+ }
+#endif
+#if defined(CONFIG_SP1_STORAGE_TEST)
+ if (rc == 0 && !stop) {
+ file_test();
+ }
+ sp1_emmc_report_stats();
+#endif
+ }
+ unmount_vol();
+ if (!stop) {
+ sp1_emmc_power_down();
+ }
+ atomic_set(&owner, OWN_NONE);
+ LINE("STORE %s after %u ms -- eMMC powered down\n",
+ stop ? "STOPPED by power-off" : (ok ? "done" : "eMMC not usable"),
+ (unsigned)(k_uptime_get_32() - t0));
+}
+
+#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
+ * is not offered: a computer shown a raw card offers to format it (possibly as exFAT,
+ * which Wakes cannot read), and only wakes-sp1-fresh formats (Adara). */
+static void job_host(void)
+{
+ k_mutex_lock(&card_lock, K_FOREVER);
+ struct sp1_emmc_ident id;
+ const bool ok = !stop && sp1_emmc_init(&id);
+ bool vol = false;
+ if (ok) {
+ /* Mount as Wakes for a moment: the same test the ON job uses, and it
+ * records where the volume's regions are for the diagnostics. */
+ atomic_set(&owner, OWN_WAKES);
+ view_base = 0;
+ view_count = sp1_emmc_sectors();
+ vol = (mount_vol() == 0);
+ unmount_vol();
+ atomic_set(&vol_state, vol ? SP1_STORE_VOL_OK : SP1_STORE_VOL_NONE);
+ }
+ if (vol) {
+ atomic_set(&owner, OWN_HOST);
+ } else {
+ atomic_set(&owner, OWN_NONE);
+ sp1_emmc_power_down();
+ }
+ k_mutex_unlock(&card_lock);
+ if (vol) {
+ LINE("STORE drive: the card is a USB drive (%u MB) until ON\n",
+ (unsigned)(sp1_emmc_sectors() / 2048u));
+ } else if (ok) {
+ LINE("STORE drive: no filesystem on the eMMC -- no drive (wakes-sp1-fresh "
+ "creates one)\n");
+ } else {
+ LINE("STORE drive: the eMMC did not start -- no drive this time\n");
+ }
+}
+#endif
+
+/* ---------------------------------------------------------------- the thread */
+
+static K_SEM_DEFINE(go, 0, 1);
+static K_THREAD_STACK_DEFINE(store_stack, 4096);
+static struct k_thread store_tcb;
+
+static void store_thread(void *a, void *b, void *c)
+{
+ ARG_UNUSED(a);
+ ARG_UNUSED(b);
+ ARG_UNUSED(c);
+ for (;;) {
+ k_sem_take(&go, K_FOREVER);
+ for (;;) {
+ const atomic_val_t jobs = atomic_get(&pending);
+ if (jobs & JOB_ON) { /* ON always wins: Wakes takes the card */
+ atomic_and(&pending, ~JOB_ON);
+ job_on_enter();
+#if defined(CONFIG_SP1_PLAITS)
+ } else if (jobs & JOB_SAVE) {
+ atomic_and(&pending, ~JOB_SAVE);
+ job_save();
+#endif
+ } else if (jobs & JOB_HOST) {
+ atomic_and(&pending, ~JOB_HOST);
+#if defined(CONFIG_SP1_DRIVE)
+ job_host();
+#endif
+ } else {
+ break;
+ }
+#if defined(CONFIG_SP1_STORAGE_TEST)
+ size_t unused = 0;
+ if (k_thread_stack_space_get(k_current_get(), &unused) == 0) {
+ LINE("STORE stack: %u of %u bytes never used\n",
+ (unsigned)unused,
+ (unsigned)K_THREAD_STACK_SIZEOF(store_stack));
+ }
+#endif
+ }
+ }
+}
+
+void sp1_store_init(void)
+{
+ (void)disk_access_register(&disk);
+#if defined(CONFIG_SP1_DRIVE)
+ (void)disk_access_register(&host_disk);
+#endif
+ (void)k_thread_create(&store_tcb, store_stack, K_THREAD_STACK_SIZEOF(store_stack),
+ store_thread, NULL, NULL, NULL, K_PRIO_PREEMPT(5), 0, K_NO_WAIT);
+ (void)k_thread_name_set(&store_tcb, "store");
+}
+
+void sp1_store_on_enter(void)
+{
+ stop = false;
+ 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(&prst_state, SP1_STORE_PRST_WAIT);
+ atomic_set(&save_state, SP1_STORE_SAVE_IDLE);
+#endif
+ /* Set HERE, before the job can run, so main never reads a stale READY. */
+ atomic_set(&phase, IS_ENABLED(CONFIG_SP1_FRESH) ? SP1_STORE_CHECKING : SP1_STORE_READY);
+ atomic_and(&pending, ~JOB_HOST);
+ atomic_or(&pending, JOB_ON);
+ k_sem_give(&go);
+}
+
+#if defined(CONFIG_SP1_DRIVE)
+static bool host_requested; /* this STANDBY visit */
+
+void sp1_store_standby_enter(void)
+{
+ host_requested = false;
+}
+
+void sp1_store_standby_tick(bool host)
+{
+ /* A host (not a charger) has configured the device: give it the card, once per
+ * STANDBY visit. */
+ if (host && !host_requested) {
+ host_requested = true;
+ stop = false;
+ atomic_or(&pending, JOB_HOST);
+ k_sem_give(&go);
+ }
+}
+
+uint32_t sp1_store_activity(void)
+{
+ return (uint32_t)atomic_get(&activity);
+}
+#endif
+
+enum sp1_store_volume sp1_store_volume(void)
+{
+ return (enum sp1_store_volume)atomic_get(&vol_state);
+}
+
+enum sp1_store_phase sp1_store_phase(void)
+{
+ return (enum sp1_store_phase)atomic_get(&phase);
+}
+
+enum sp1_store_format sp1_store_format_result(void)
+{
+ return (enum sp1_store_format)atomic_get(&fmt_result);
+}
+
+uint8_t sp1_store_progress(void)
+{
+ return (uint8_t)atomic_get(&progress);
+}
+
+#if defined(CONFIG_SP1_PLAITS)
+enum sp1_store_prst sp1_store_prst(void)
+{
+ return (enum sp1_store_prst)atomic_get(&prst_state);
+}
+
+int sp1_store_prst_current(void)
+{
+ return prst_current;
+}
+
+const struct sp1_prst *sp1_store_prst_slot(int slot)
+{
+ return &prst_slot[(slot >= 0 && slot < SP1_PRST_SLOTS) ? slot : 0];
+}
+
+bool sp1_store_prst_save(int slot, const struct sp1_prst *p)
+{
+ if (atomic_get(&prst_state) != SP1_STORE_PRST_READY || slot < 0 ||
+ slot >= SP1_PRST_SLOTS) {
+ return false;
+ }
+ const int n = sp1_prst_write(p, save_text, sizeof(save_text));
+ if (n < 0) {
+ return false;
+ }
+ save_len = (size_t)n;
+ save_slot = slot;
+ prst_slot[slot] = *p;
+ atomic_set(&save_state, SP1_STORE_SAVE_BUSY); /* a barrier: the text is in place */
+ atomic_or(&pending, JOB_SAVE);
+ k_sem_give(&go);
+ return true;
+}
+
+enum sp1_store_save sp1_store_save_result(void)
+{
+ return (enum sp1_store_save)atomic_get(&save_state);
+}
+#endif
+
+void sp1_store_abort(void)
+{
+ stop = true;
+ atomic_clear(&pending);
+ atomic_set(&owner, OWN_NONE);
+ sp1_emmc_abort();
+}
diff --git a/firmware/src/sp1_store.h b/firmware/src/sp1_store.h
new file mode 100644
index 0000000..376aecf
--- /dev/null
+++ b/firmware/src/sp1_store.h
@@ -0,0 +1,155 @@
+/*
+ * wakes-sp1 — storage on the eMMC (M6, #43; CONFIG_SP1_STORAGE): a FAT32 volume and the
+ * thread that owns it. PRST's presets will live here; today it runs the fresh format
+ * and the storage test.
+ *
+ * ---- the card ----
+ * One MBR partition, FAT32, starting at block 8192 (4 MB: the card's erase group, so the
+ * volume and its data area sit on erase boundaries), 32 KB clusters, two FATs, volume
+ * label "SP-1" (Adara: what the computer calls the drive) -- the layout an SD card
+ * formatter makes, so a computer sees an ordinary drive. Mounted at "/EMMC:". Long file
+ * names (Adara: presets are ".prst", ini inside): /EMMC:/WAKES/...
+ *
+ * ---- formatting: ONLY wakes-sp1-fresh (Adara, 2026-10-07) ----
+ * "Flashing wakes-sp1-fresh formats the eMMC. Flashing a normal wakes-sp1 bin does not
+ * touch the eMMC." Enforced at build level: without CONFIG_SP1_FRESH the image contains
+ * no formatter at all (CONFIG_FILE_SYSTEM_MKFS off, so FatFs is built without f_mkfs),
+ * mounting never formats (FS_MOUNT_FLAG_NO_FORMAT, and CONFIG_FS_FATFS_MOUNT_MKFS off),
+ * and tools/ci/check_image.py fails a normal image that links f_mkfs.
+ * The fresh image formats on its first entry to ON and writes its own build ID to
+ * /EMMC:/WAKES/FRESH.ID; while that file matches, it never formats again. ⚠️ So flashing
+ * the SAME fresh file twice formats once: the second flash is indistinguishable from a
+ * reboot (the image cannot see its own flashing without writing the nRF's flash).
+ *
+ * ---- threading ----
+ * Everything runs in one thread at K_PRIO_PREEMPT(5): below audio (0) and below main
+ * and the USB threads (1), so it only ever uses CPU they leave idle -- no cost to the
+ * audio block. It does NOT feed the watchdog (sp1_emmc.h). A format takes several
+ * seconds, during which main waits in storage_gate() -- still feeding the watchdog and
+ * still running sp1_power_tick(), so the 30 s backstop is untouched (rule 5a).
+ */
+#ifndef SP1_STORE_H
+#define SP1_STORE_H
+
+#include
+
+/* Once at boot, before any other call: registers the disk and starts the thread. */
+void sp1_store_init(void);
+
+/* ---- the fresh format holds ON entry (Adara, 2026-10-07) ----
+ * "Formatting the eMMC should hold up the rest of the UI while the device is being turned
+ * on. We can still turn the SP-1 off during the process in case it hangs, using the 30s
+ * SHFT hold backstop." main.c's storage_gate() waits on these between queuing the job and
+ * starting audio, drawing the progress bar from sp1_store_progress(). Fresh builds only:
+ * a normal image never formats, so it never waits. */
+enum sp1_store_phase {
+ SP1_STORE_READY = 0, /* no job, or the job is past its fresh step */
+ SP1_STORE_CHECKING, /* job queued: powering the card, reading FRESH.ID */
+ SP1_STORE_FORMATTING, /* formatting */
+};
+enum sp1_store_format {
+ SP1_STORE_FMT_NONE = 0, /* no format this ON entry */
+ SP1_STORE_FMT_DONE, /* formatted and stamped */
+ SP1_STORE_FMT_FAILED, /* tried and failed (or stopped): formats again next ON */
+};
+enum sp1_store_phase sp1_store_phase(void);
+enum sp1_store_format sp1_store_format_result(void);
+/* 0-255 through a format: the format's block writes so far against the count FatFs will
+ * make for this card (exact for FAT32: both FATs, the root cluster, the boot sectors). */
+uint8_t sp1_store_progress(void);
+
+/* ---- is there a filesystem to use? (Adara, 2026-10-07) ----
+ * "On boot, check if the partition is formatted. If it's not formatted, don't format unless
+ * it's Fresh. In this state, boot, but disable the PRST feature and key combos related to
+ * it. As we add the PRST feature and related combos, we should build them with a check of
+ * whether the partition is formatted or not."
+ * So EVERY PRST feature and key combo asks sp1_store_volume() and does nothing unless it
+ * says OK. "Formatted" = a FAT volume FatFs can mount (wakes-sp1-fresh's, or a FAT32 a
+ * computer made); WAKES/ is created when first needed. Set by the ON job a fraction of a
+ * second after ON, and by the drive job in STANDBY. UNKNOWN means "not looked yet" --
+ * treat it as NO, never as yes. Without a volume the drive is not offered either: a
+ * computer shown a raw card offers to format it, possibly as exFAT, which Wakes cannot
+ * read. */
+enum sp1_store_volume {
+ SP1_STORE_VOL_UNKNOWN = 0,
+ SP1_STORE_VOL_OK,
+ SP1_STORE_VOL_NONE, /* no card, or no FAT volume on it: PRST is off */
+};
+enum sp1_store_volume sp1_store_volume(void);
+
+/* Every entry to ON (main thread): queue the ON job -- take the card from a host (drive
+ * mode), the fresh check and format (CONFIG_SP1_FRESH), the report and file test
+ * (CONFIG_SP1_STORAGE_TEST). Returns at once. Never dropped: if another job is running it
+ * runs next, ahead of anything else queued. */
+void sp1_store_on_enter(void);
+
+#if defined(CONFIG_SP1_DRIVE)
+#include
+
+/* ---- drive mode (M6, Adara 2026-10-07) ----
+ * In STANDBY with a host attached the card is a USB drive (automatic, no gesture); turning
+ * ON takes it back after the transfer in flight. The mass-storage interface is always in
+ * the descriptor: while the host does not own the card it reads "no medium", so going
+ * STANDBY <-> ON never re-enumerates. ⚠️ A host that EJECTS the drive does not get it back
+ * until the next USB reset (a replug): Zephyr's class keeps "ejected" until then, the way
+ * a card reader keeps a removed card out.
+ * sp1_standby_run() calls these: enter once per visit, tick every control tick with
+ * sp1_usbd_host(). sp1_store_activity() counts the host's transfers, for the LEDs. */
+void sp1_store_standby_enter(void);
+void sp1_store_standby_tick(bool host);
+uint32_t sp1_store_activity(void);
+#endif
+
+#if defined(CONFIG_SP1_PLAITS)
+#include
+#include "sp1_prst.h"
+
+/* ---- PRST: the four slots (M6, #50) ----
+ * WAKES/PRST/1 .. 4 on the volume, one `.prst` per folder, any name: the FOLDER decides the
+ * slot (Adara). More than one file in a folder -> the first in alphabetical order (case
+ * ignored, byte order), never the others. WAKES/PRST/SLOT holds the last-loaded slot's
+ * number (missing or unreadable -> slot 1).
+ *
+ * LOAD: the ON job reads all four into RAM right after the volume check, so a slot change
+ * never touches the card while playing. A folder with no `.prst` (or no folder) is that
+ * slot at the ROTC defaults, PRST staying on. A card that fails -- it does not start, no
+ * filesystem, a read error -- turns PRST off for the session. main.c waits for the answer
+ * before audio starts, at most SP1_PRST_LOAD_MS (10 s, Adara), and treats a late answer
+ * as off.
+ *
+ * SAVE: only at a normal shutdown (sp1_power_set_save_hook), into the current slot. The
+ * text goes to a temporary file in the slot's folder (not ending in `.prst`, so never
+ * loaded), which then replaces the last-loaded file -- or becomes `N.prst` in an empty
+ * folder. Other files in the folder are never touched. Then SLOT. */
+#define SP1_PRST_SLOTS 4
+#define SP1_PRST_LOAD_MS 10000u
+#define SP1_PRST_SAVE_MS 4000u
+
+enum sp1_store_prst {
+ SP1_STORE_PRST_WAIT = 0, /* the ON job has not read the slots yet */
+ SP1_STORE_PRST_READY, /* all four in RAM: sp1_store_prst_slot() */
+ SP1_STORE_PRST_OFF, /* no card, no filesystem, or a read failed */
+};
+enum sp1_store_prst sp1_store_prst(void);
+/* After READY only. 0..3. */
+int sp1_store_prst_current(void);
+const struct sp1_prst *sp1_store_prst_slot(int slot);
+
+/* Main thread, at shutdown: write `p` into `slot` and make it the current one. Queues the
+ * job and returns; false if it could not be queued (PRST is not READY). Poll the result. */
+bool sp1_store_prst_save(int slot, const struct sp1_prst *p);
+enum sp1_store_save {
+ SP1_STORE_SAVE_IDLE = 0,
+ SP1_STORE_SAVE_BUSY,
+ SP1_STORE_SAVE_OK,
+ SP1_STORE_SAVE_FAILED,
+};
+enum sp1_store_save sp1_store_save_result(void);
+#endif
+
+/* 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. */
+void sp1_store_abort(void);
+
+#endif /* SP1_STORE_H */
diff --git a/firmware/src/sp1_ui_timing.h b/firmware/src/sp1_ui_timing.h
index c3fe4bd..8887a40 100644
--- a/firmware/src/sp1_ui_timing.h
+++ b/firmware/src/sp1_ui_timing.h
@@ -109,10 +109,17 @@
/* ---- STANDBY (off, plugged in) ----
* The play row is a charge bar filling from the "••" end toward PLAY. It breathes
- * while charging and sits solid when complete. Status lights live on the model
- * row at T2/T3, dim so they read as indicators rather than as UI. */
-#define SP1_STANDBY_STATUS_LEVEL 38u /* ~15 % of 255 -- T2/T3 status */
+ * while charging and sits solid when complete -- the only charging indicator now: the
+ * T2/T3 plugged/charging lights are gone (Adara, M6), to free the model row for the
+ * drive's activity below. */
#define SP1_STANDBY_BAR_LEVEL 77u /* ~30 % of 255 -- the charge bar */
+/* Drive mode's activity (Adara, M6 #43): on host reads and writes the model row steps
+ * T1, T3, T2, T4 (2 and 3 swapped on purpose), each LED a fast downward ramp from 50 %.
+ * One step at most every SP1_DRIVE_STEP_MS, so a transfer reads as a chase rather than
+ * all four glowing at once. Tune on hardware. */
+#define SP1_DRIVE_LED_PEAK 128u /* 50 % */
+#define SP1_DRIVE_STEP_MS 50u
+#define SP1_DRIVE_RAMP_MS 150u
#define SP1_STANDBY_BREATH_MS 2200u /* one full breath cycle */
#define SP1_STANDBY_BREATH_DEPTH 60u /* peak-to-trough at FULL brightness;
* scaled down with the bar level so a
@@ -173,15 +180,34 @@
/* ---- engine flash (Adara, M3b): instant, brief, fades back into the page ----
* Patterns: SLOT_GLYPHS in tools/gen_engines.py, one per slot. */
-/* "••" + PLAY held: rip out the cables (Adara, M4) -- the module on show back to its
- * defaults. The track row flickers twice, fades to black, stays black, and -- only if
- * the hold lasts SP1_RIP_HOLD_MS -- the reset happens and the page fades back in.
- * Letting go earlier cancels. */
-#define SP1_RIP_HOLD_MS 3000u /* to complete */
-#define SP1_RIP_FLICKER_MS 70u /* each on / off of the two flickers */
-#define SP1_RIP_BLACK_MS 500u /* black at the end of the hold */
-#define SP1_RIP_FADEBACK_MS 500u /* after the reset: black -> the page */
-#define SP1_RIP_CANCEL_FADE_MS 150u /* let go early: back to the page */
+/* ---- "••" + PLAY: PRST and ROTC on one combination (Adara, #50) ----
+ * PLAY pressed with "••" held shows the current PRST slot's glyph at once (one LED per
+ * slot, T1..T4): that LED ramps 100 % -> 0 every SP1_PRST_RAMP_MS, SP1_PRST_GLYPH_MS in
+ * all (16 ramps at 10 Hz), then the page fades back in. PLAY pressed again while it shows
+ * = the next slot. PLAY kept held from the first press = ROTC ("rip out the cables"),
+ * still SP1_RIP_HOLD_MS in total:
+ * glyph SP1_PRST_GLYPH_MS -> all four black SP1_ROTC_BLACK_MS -> fade up to full over
+ * SP1_ROTC_RISE_MS -> the Unpatch animation (SP1_UNPATCH_ANIM_MS) -> the wipe.
+ * Letting go once the ROTC animation has begun (past the glyph) fades back to the SHIFT
+ * screen and wipes nothing. Through v0.7.2 the rip was two flickers, a fade and black. */
+#define SP1_PRST_GLYPH_MS 1600u /* the slot glyph: 16 ramps */
+#define SP1_PRST_RAMP_MS 100u /* one ramp, 100 % -> 0 (10 Hz) */
+#define SP1_PRST_FADEBACK_MS 250u /* the glyph's end: back to the page */
+#define SP1_ROTC_BLACK_MS 250u /* after the glyph: all four dark */
+#define SP1_ROTC_RISE_MS 400u /* then 0 -> 100 %, all four */
+#define SP1_RIP_HOLD_MS 3000u /* to complete */
+#define SP1_RIP_FADEBACK_MS 500u /* after the reset: black -> the page */
+#define SP1_RIP_CANCEL_FADE_MS 150u /* let go early: back to the SHIFT screen */
+/* ---- the fresh format at ON entry (Adara, M6 #43) ----
+ * The UI waits while wakes-sp1-fresh formats the eMMC. The track row is a progress bar
+ * through the format (sp1_led_bar, full brightness); when it completes the row flickers
+ * twice, 0 -> 100 %, and fades quickly into the page. A format that fails leaves the bar
+ * and fades into the page with no flicker -- the flicker means "done". Only the 30 s
+ * backstop powers off meanwhile (storage_gate() in main.c). */
+#define SP1_FMT_FLICKER_MS 70u /* each off / on of the two flickers (as the rip) */
+#define SP1_FMT_DONE_FADE_MS 250u /* then full -> the page */
+#define SP1_FMT_FAIL_FADE_MS 250u /* failed: the bar -> the page */
+
/* ---- UNPATCH: "••" held + T1-T4 held (Adara, M4e) ----
* Clears the routing belonging to that button -- on PLAITS the Marbles outputs aimed at
* that parameter, on MARBLES that output's destination. The only destructive gesture
@@ -222,6 +248,10 @@
#define SP1_UNPATCH_SWEEP_MS 240u /* 100 % -> dark, middle outwards */
#define SP1_UNPATCH_BLINK_LEVEL 204u /* 80 % of 255 (Adara) */
+/* ROTC's phases must add up to its 3 s (Adara: "still 3 s in total"). */
+#define SP1_ROTC_UNPATCH_AT (SP1_PRST_GLYPH_MS + SP1_ROTC_BLACK_MS + SP1_ROTC_RISE_MS)
+/* (checked in main.c) */
+
/* ---- the MIDI prompt (M5a, Adara; M5 plan B9) ----
* MIDI plugged in -> the Unpatch animation REVERSED (the cable going in); unplugged -> the
* Unpatch animation as it is. Same SP1_UNPATCH_ANIM_MS, same fade back to the page.
@@ -236,6 +266,13 @@
* 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) ----
+ * 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
+ * rate (Adara); 64 ms = exactly 8 control ticks, so every ramp has the same steps. */
+#define SP1_OFFLIST_RAMP_MS 64u /* one ramp, 70 % -> 0 (15.6 Hz) */
+#define SP1_OFFLIST_LEVEL 179u /* 70 % of 255 */
/* M3c: glyphs are drawn by hand (SLOT_GLYPHS) -- each LED off, half or full. */
#define SP1_ENGINE_LED_FULL 255u
/* The "◐" level: 33 % perceptual (Adara, M3e -- 50 % was too close to full to tell
diff --git a/firmware/src/sp1_usbd.c b/firmware/src/sp1_usbd.c
index f6266cb..7a55305 100644
--- a/firmware/src/sp1_usbd.c
+++ b/firmware/src/sp1_usbd.c
@@ -107,12 +107,14 @@ static void usb_thread_find(const struct k_thread *t, void *user_data)
found[0] = (k_tid_t)t;
} else if (strcmp(name, "usbd") == 0) {
found[1] = (k_tid_t)t;
+ } else if (strcmp(name, "usbd_msc") == 0) {
+ found[2] = (k_tid_t)t;
}
}
static int usb_threads_below_audio(void)
{
- k_tid_t found[2] = { NULL, NULL };
+ k_tid_t found[3] = { NULL, NULL, NULL };
int n = 0;
k_thread_foreach_unlocked(usb_thread_find, found);
@@ -122,6 +124,15 @@ static int usb_threads_below_audio(void)
n++;
}
}
+ /* M6 drive mode: the mass-storage class runs every SCSI command -- and with it every
+ * eMMC transfer -- in its own thread, which Zephyr starts at the system work queue's
+ * COOPERATIVE priority. Left there, a host polling the drive while ON would run inside
+ * audio blocks. One step below main: in STANDBY it gets everything main leaves; in ON
+ * it only answers "no medium". Not counted in `n`, which the boot log reads as "the
+ * two core USB threads moved". */
+ if (found[2] != NULL) {
+ k_thread_priority_set(found[2], K_PRIO_PREEMPT(CONFIG_MAIN_THREAD_PRIORITY + 1));
+ }
return n;
}
#endif
@@ -156,8 +167,21 @@ int sp1_usbd_init(void)
if (err == 0) {
/* Every compiled-in class: CDC ACM (devicetree), feldd's MIDI class
* (USBD_DEFINE_CLASS in usb_midi1.c) and USB audio out (wakes_uac, sp1_uac.c),
- * in that order -- linker order is by name (sp1_uac.c says why it matters). */
- err = usbd_register_all_classes(&sp1_usbd, USBD_SPEED_FS, 1, NULL);
+ * in that order -- linker order is by name (sp1_uac.c says why it matters).
+ * Mass storage is held back from that list and added LAST (M6): by name it would
+ * land between CDC and MIDI and renumber every interface after it. */
+ static const char *const later[] = { "msc_0", NULL };
+ err = usbd_register_all_classes(&sp1_usbd, USBD_SPEED_FS, 1, later);
+ }
+#if defined(CONFIG_SP1_DRIVE)
+ if (err == 0) {
+ err = usbd_register_class(&sp1_usbd, "msc_0", USBD_SPEED_FS, 1);
+ }
+#endif
+ if (err == 0) {
+ /* The function set's version (Kconfig SP1_USB_BCD_DEVICE): changes when the
+ * functions do, so the PID never has to. */
+ err = usbd_device_set_bcd_device(&sp1_usbd, CONFIG_SP1_USB_BCD_DEVICE);
}
if (err != 0) {
return err;
diff --git a/tools/ci/check_image.py b/tools/ci/check_image.py
index 7460990..5956559 100644
--- a/tools/ci/check_image.py
+++ b/tools/ci/check_image.py
@@ -268,6 +268,31 @@ def check_uac_copies(zd):
", ".join(calls) or "word copies")
+def check_storage(zd, cfg):
+ """Only wakes-sp1-fresh may format the eMMC (#43, Adara 2026-10-07).
+
+ "Flashing wakes-sp1-fresh formats the eMMC. Flashing a normal wakes-sp1 bin does not
+ touch the eMMC." So a normal image must not even CONTAIN a formatter (FatFs' f_mkfs is
+ only compiled with CONFIG_FILE_SYSTEM_MKFS), and no image may format on a failed
+ mount -- Zephyr's default, which would wipe a card holding another firmware's data.
+ Nothing to check while storage is not linked.
+ """
+ if cfg.get("CONFIG_SP1_STORAGE") != "y":
+ return
+ check(cfg.get("CONFIG_FS_FATFS_MOUNT_MKFS") != "y",
+ "storage: a failed mount never formats (FS_FATFS_MOUNT_MKFS off)",
+ f"got {cfg.get('CONFIG_FS_FATFS_MOUNT_MKFS')}")
+ with open(zd / f"{NAME}.elf", "rb") as fh:
+ mkfs = bool(ELFFile(fh).get_section_by_name(".symtab").get_symbol_by_name("f_mkfs"))
+ if cfg.get("CONFIG_SP1_FRESH") == "y":
+ check(mkfs, "storage: FRESH image links the formatter", "f_mkfs present")
+ print(" [NOTE] FRESH IMAGE: formats the eMMC on its first entry to ON. "
+ "Ship it as wakes-sp1-fresh, never as wakes-sp1.")
+ else:
+ check(not mkfs, "storage: normal image contains no formatter",
+ "f_mkfs LINKED" if mkfs else "no f_mkfs")
+
+
def check_source(repo):
# A header constant, not a build flag, so nothing else would catch a leftover 1:
# the device would boot into the calibration wizard.
@@ -294,6 +319,7 @@ def main():
check_layouts(zd)
check_fast_clear(zd)
check_uac_copies(zd)
+ check_storage(zd, cfg)
check_source(a.repo)
failed = results.count(False)
diff --git a/tools/gen_engines.py b/tools/gen_engines.py
index 6f8f28f..c0a4e9e 100644
--- a/tools/gen_engines.py
+++ b/tools/gen_engines.py
@@ -198,6 +198,19 @@ def generate(csv_path, out_path):
out.append("\t{ %2d, %d, 0x%x, { %d, %d, %d, %d }, %s }, /* slot %2d */"
% ((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.
+ by_idx = sorted(facts().values(), key=lambda e: e["plaits"])
+ out += ["};", "",
+ "#define SP1_PLAITS_ENGINE_COUNT %d" % len(by_idx), "",
+ "/* By Plaits index: name and centre detents (as above), listed or not. */",
+ "static const struct {",
+ "\tuint8_t centre;",
+ "\tconst char *name;",
+ "} 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 */", ""]
text = "\n".join(out)
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
diff --git a/tools/gen_prst.py b/tools/gen_prst.py
new file mode 100644
index 0000000..f6cf69e
--- /dev/null
+++ b/tools/gen_prst.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""wakes-sp1 -- generate the PRST preset format's field table (M6, #50).
+
+ gen_prst.py build step (CMake runs this)
+ gen_prst.py --fingerprint print the current field list's fingerprint
+
+A PRST slot is a `.prst` file of ini text (src/sp1_prst.h). This file is the ONE list of what
+goes in it: every key, its section, what kind of value it holds, and where in
+`struct sp1_prst` it lands. sp1_prst.c writes and reads files from the generated table; it
+holds no list of its own.
+
+---- the format version (Adara, #50) ----
+"Every slot carries a format version. Firmware that doesn't recognise a slot's version starts
+that slot from defaults. The build fails if the format changes without a version bump."
+
+So the field list has a FINGERPRINT (a hash of every key, kind, check and choice token), and
+FORMATS below records the fingerprint of each released version. The build fails if the
+current list's fingerprint is not the newest entry. To change the format on purpose: add
+the next version with the fingerprint the error prints -- and the release that ships it
+must say so and ask users to install wakes-sp1-fresh.
+
+⚠️ Never edit an existing FORMATS entry: a version names one exact format forever.
+
+Standard library only.
+"""
+import hashlib
+import os
+import sys
+
+# ---- the format versions: {version: fingerprint}. Append only. ------------------------------
+FORMATS = {
+ 1: '83265ab33880809b',
+}
+
+# ---- choices: (token written in the file, C expression of the value) ----------------------
+# Tokens are lowercase and space-free so a preset stays easy to edit by hand; reading ignores
+# case. The VALUE is a C expression -- an enum name where one exists -- so the table cannot
+# drift from the firmware's enum order.
+DESTS = [
+ ('none', 'SP1_DEST_NONE'), ('fm', 'SP1_DEST_FM'), ('timbre', 'SP1_DEST_TIMBRE'),
+ ('morph', 'SP1_DEST_MORPH'), ('harmonics', 'SP1_DEST_HARM'), ('voct', 'SP1_DEST_VOCT'),
+ ('level', 'SP1_DEST_LEVEL'), ('trig', 'SP1_DEST_TRIG'),
+]
+SCALES = [
+ ('major', '0'), ('minor', '1'), ('pentatonic', '2'), ('pelog', '3'), ('bhairav', '4'),
+ ('shri', '5'), ('free', '6'),
+]
+CHOICES = {
+ 'dest': DESTS,
+ 'scale': SCALES,
+ 'scale_off': [('off', 'SP1_PUI_SCALE_OFF')] + SCALES,
+ 'output': [('out', 'SP1_OUT_MAIN'), ('aux', 'SP1_OUT_AUX'), ('out+aux', 'SP1_OUT_SUM'),
+ ('outxaux', 'SP1_OUT_RING')],
+ 'burst': [('1/%d' % (1 << i), str(i)) for i in range(8)], # g_burst_div 0..7
+ 'drive': [('off', '0'), ('+3db', '1'), ('+8db', '2'), ('+15db', '3'), ('+24db', '4')],
+ 't_model': [('bernoulli', '0'), ('clusters', '1'), ('drums', '2'),
+ ('independent_bernoulli', '3'), ('divider', '4'), ('three_states', '5')],
+ 't_range': [('x0.25', '0'), ('x1', '1'), ('x4', '2')],
+ 'range': [('0-2v', 'SP1_MRB_RANGE_NARROW'), ('0-5v', 'SP1_MRB_RANGE_POSITIVE'),
+ ('+-5v', 'SP1_MRB_RANGE_FULL'), ('intelligent', 'SP1_MRB_RANGE_INTELLIGENT')],
+ 'diversity': [('identical', '0'), ('bump', '1'), ('tilt', '2')],
+ 'onoff': [('off', '0'), ('on', '1')],
+}
+
+# ---- 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
+# 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.
+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 = [
+ ('plaits', 'engine', 'engine', '', 'plaits.slot'),
+ ('plaits', 'frequency', 'pos', '', 'plaits.v[%s][0]' % B),
+ ('plaits', 'timbre', 'pos', '', 'plaits.v[%s][1]' % B),
+ ('plaits', 'morph', 'pos', '', 'plaits.v[%s][2]' % B),
+ ('plaits', 'harmonics', 'pos', '', 'plaits.v[%s][3]' % B),
+ ('plaits', 'fm_attenuverter', 'pos', '', 'plaits.v[%s][0]' % SH),
+ ('plaits', 'timbre_attenuverter', 'pos', '', 'plaits.v[%s][1]' % SH),
+ ('plaits', 'morph_attenuverter', 'pos', '', 'plaits.v[%s][2]' % SH),
+ ('plaits', 'harmonics_attenuverter', 'pos', '', 'plaits.v[%s][3]' % SH),
+ ('plaits', 'octave_range', 'pos', '', 'plaits.v[%s][0]' % ST),
+ ('plaits', 'lpg_colour', 'pos', '', 'plaits.v[%s][1]' % ST),
+ ('plaits', 'lpg_decay', 'pos', '', 'plaits.v[%s][2]' % ST),
+ ('plaits', 'level', 'pos', '', 'plaits.v[%s][3]' % ST),
+ ('plaits', 'quantizer', 'scale_off', 'scale', 'plaits.scale'),
+ ('plaits', 'output', 'output', '', 'out_mode'),
+ ('plaits', 'burst', 'burst', '', 'burst_div'),
+ ('plaits', 'drive', 'drive', '', 'drive'),
+ ('marbles', 'rate', 'pos', '', 'marbles.v[%s][0]' % T),
+ ('marbles', 't_bias', 'pos', '', 'marbles.v[%s][1]' % T),
+ ('marbles', 'jitter', 'pos', '', 'marbles.v[%s][2]' % T),
+ ('marbles', 'deja_vu', 'pos', '', 'marbles.v[%s][3]' % T),
+ ('marbles', 'gtlt', 'pos', '', 'marbles.v[%s][0]' % TS),
+ ('marbles', 'gate_length', 'pos', '', 'marbles.v[%s][1]' % TS),
+ ('marbles', 'gate_length_random', 'pos', '', 'marbles.v[%s][2]' % TS),
+ ('marbles', 'length', 'pos', '', 'marbles.v[%s][3]' % TS),
+ ('marbles', 'spread', 'pos', '', 'marbles.v[%s][0]' % XB),
+ ('marbles', 'x_bias', 'pos', '', 'marbles.v[%s][1]' % XB),
+ ('marbles', 'steps', 'pos', '', 'marbles.v[%s][2]' % XB),
+ ('marbles', 'y_spread', 'pos', '', 'marbles.v[%s][0]' % Y),
+ ('marbles', 'y_bias', 'pos', '', 'marbles.v[%s][1]' % Y),
+ ('marbles', 'y_steps', 'pos', '', 'marbles.v[%s][2]' % Y),
+ ('marbles', 'y_divider', 'pos', '', 'marbles.v[%s][3]' % Y),
+ ('marbles', 't_model', 't_model', '', 'marbles.model'),
+ ('marbles', 't_range', 't_range', '', 'marbles.t_range'),
+ ('marbles', 'range', 'range', '', 'marbles.range'),
+ ('marbles', 'diversity', 'diversity', '', 'marbles.diversity'),
+ ('marbles', 'scale', 'scale', 'scale', 'marbles.scale'),
+ ('marbles', 'deja_vu_t', 'onoff', '', 'marbles.dv_t'),
+ ('marbles', 'deja_vu_x', 'onoff', '', 'marbles.dv_x'),
+ ('marbles', 't1', 'dest', 't_dest', 'marbles.t_dest[0]'),
+ ('marbles', 't2', 'dest', 't_dest', 'marbles.t_dest[1]'),
+ ('marbles', 't3', 'dest', 't_dest', 'marbles.t_dest[2]'),
+ ('marbles', 'x1', 'dest', 'x_dest', 'marbles.dest[0]'),
+ ('marbles', 'x2', 'dest', 'x_dest', 'marbles.dest[1]'),
+ ('marbles', 'x3', 'dest', 'x_dest', 'marbles.dest[2]'),
+ ('marbles', 'y', 'dest', 'x_dest', 'marbles.dest[3]'),
+]
+CHECKS = ['', 'scale', 't_dest', 'x_dest']
+
+
+def fail(msg):
+ sys.stderr.write('gen_prst.py: %s\n' % msg)
+ sys.exit(1)
+
+
+def validate():
+ seen = set()
+ for sec, key, kind, check, path in FIELDS:
+ if (sec, key) in seen:
+ fail('%s.%s listed twice' % (sec, key))
+ seen.add((sec, key))
+ if kind not in ('engine', 'pos') and kind not in CHOICES:
+ fail('%s.%s: unknown kind %r' % (sec, key, kind))
+ if check not in CHECKS:
+ fail('%s.%s: unknown check %r' % (sec, key, check))
+ if not key.isidentifier() or key != key.lower():
+ fail('%s.%s: keys are lowercase identifiers' % (sec, key))
+ for name, toks in CHOICES.items():
+ t = [a for a, _ in toks]
+ if len(set(t)) != len(t):
+ fail('choice %s has a token twice' % name)
+ for a in t:
+ if a != a.lower() or any(c.isspace() for c in a) or not a:
+ fail('choice %s: token %r must be lowercase, without spaces' % (name, a))
+
+
+def fingerprint():
+ # Everything that decides what a file means. NOT the struct paths: they are where a
+ # value lands in RAM, which can change without changing a single file.
+ parts = []
+ for sec, key, kind, check, _ in FIELDS:
+ parts.append('%s.%s:%s:%s' % (sec, key, kind, check))
+ for name in sorted(CHOICES):
+ parts.append('%s=%s' % (name, ','.join('%s>%s' % tv for tv in CHOICES[name])))
+ return hashlib.sha256('\n'.join(parts).encode('utf-8')).hexdigest()[:16]
+
+
+def check_version():
+ fp = fingerprint()
+ newest = max(FORMATS)
+ if FORMATS[newest] != fp:
+ if fp in FORMATS.values():
+ fail('the field list matches an OLDER format; restore it or add a new version')
+ fail('the PRST format changed without a version bump.\n'
+ ' Fingerprint now: %s (format %d is %s).\n'
+ ' If the change is intended, add %d: %r, to FORMATS in tools/gen_prst.py --\n'
+ ' and the release that ships it must say so and ask users to install\n'
+ ' wakes-sp1-fresh (#50).' % (fp, newest, FORMATS[newest], newest + 1, fp))
+ return newest, fp
+
+
+def c_str(s):
+ return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
+
+
+def generate(out):
+ version, fp = check_version()
+ L = []
+ L.append('/* GENERATED by tools/gen_prst.py -- the PRST field table (#50).')
+ L.append(' * Do not edit: edit FIELDS / CHOICES there. Included by sp1_prst.c only. */')
+ L.append('#ifndef SP1_PRST_GEN_H')
+ L.append('#define SP1_PRST_GEN_H')
+ L.append('')
+ L.append('#define SP1_PRST_FORMAT %d' % version)
+ L.append('#define SP1_PRST_FINGERPRINT "%s"' % fp)
+ L.append('#define SP1_PRST_NFIELDS %d' % len(FIELDS))
+ L.append('')
+ L.append('enum { SP1_PRST_K_ENGINE = 0, SP1_PRST_K_POS, SP1_PRST_K_CHOICE };')
+ L.append('enum { %s };' % ', '.join('SP1_PRST_C_%s = %d' % ((c or 'none').upper(), i)
+ for i, c in enumerate(CHECKS)))
+ L.append('')
+ for name in sorted(CHOICES):
+ L.append('static const struct sp1_prst_choice sp1_prst_ch_%s[] = {' % name)
+ for tok, val in CHOICES[name]:
+ L.append('\t{ %s, %s },' % (c_str(tok), val))
+ L.append('};')
+ L.append('')
+ L.append('static const struct sp1_prst_field SP1_PRST_FIELDS[SP1_PRST_NFIELDS] = {')
+ for sec, key, kind, check, path in FIELDS:
+ if kind in ('engine', 'pos'):
+ k, ch, n = 'SP1_PRST_K_' + kind.upper(), 'NULL', '0'
+ else:
+ k = 'SP1_PRST_K_CHOICE'
+ ch = 'sp1_prst_ch_' + kind
+ n = 'sizeof(%s) / sizeof(%s[0])' % (ch, ch)
+ L.append('\t{ %s, %s, %s, SP1_PRST_C_%s, %s, %s, offsetof(struct sp1_prst, %s) },'
+ % (c_str(sec), c_str(key), k, (check or 'none').upper(), ch, n, path))
+ L.append('};')
+ L.append('')
+ L.append('#endif /* SP1_PRST_GEN_H */')
+ text = '\n'.join(L) + '\n'
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
+ old = None
+ if os.path.exists(out):
+ with open(out, encoding='utf-8') as f:
+ old = f.read()
+ if old != text: # leave the timestamp alone when nothing changed
+ with open(out, 'w', encoding='utf-8', newline='\n') as f:
+ f.write(text)
+ print('PRST format %d (%s), %d fields -> %s' % (version, fp, len(FIELDS), out))
+
+
+def main(argv):
+ validate()
+ if len(argv) == 2 and argv[1] == '--fingerprint':
+ print(fingerprint())
+ return
+ if len(argv) != 2:
+ fail('usage: gen_prst.py | --fingerprint')
+ generate(argv[1])
+
+
+if __name__ == '__main__':
+ main(sys.argv)
diff --git a/tools/host-tests/README.md b/tools/host-tests/README.md
index dfcdf3b..02f66f2 100644
--- a/tools/host-tests/README.md
+++ b/tools/host-tests/README.md
@@ -13,15 +13,16 @@ proved on a laptop, and because there is exactly one SP-1 (`docs/SAFETY.md`).
| `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 |
| `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
+ uactest.c prsttest.c
cd /tmp/wakes-sp1-host && ./routetest && ./uitest && ./miditest && ./miditest_alt \
&& ./miditest_pickup_shared && ./miditest_pickup_takeover && ./miditest_clock \
- && ./test_usb_rt_parse && ./uactest
+ && ./test_usb_rt_parse && ./uactest && ./prsttest
```
Builds go to `$TMPDIR/wakes-sp1-host` (override with `SP1_HOST_BUILD_DIR`); nothing is written
diff --git a/tools/host-tests/hostbuild.sh b/tools/host-tests/hostbuild.sh
index 55e46f1..3b360dc 100644
--- a/tools/host-tests/hostbuild.sh
+++ b/tools/host-tests/hostbuild.sh
@@ -24,6 +24,8 @@ 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
+# 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
# 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
@@ -97,6 +99,7 @@ g++ $CXXFLAGS $INC -c $SRC/sp1_marbles.cc -o $OBJ/sp1_marbles.o
g++ $CXXFLAGS $INC -c $SRC/sp1_midi.cc -o $OBJ/sp1_midi.o
gcc $CFLAGS $INC -c $SRC/sp1_plaits_ui.c -o $OBJ/pui.o
gcc $CFLAGS $INC -c $SRC/sp1_marbles_ui.c -o $OBJ/mui.o
+gcc $CFLAGS $INC -c $SRC/sp1_prst.c -o $OBJ/prst.o
# Binaries land in the build dir, never in the repo.
for t in "$@"; do
@@ -149,7 +152,7 @@ for t in "$@"; do
out=${out}_takeover ;;
*.cc) g++ $CXXFLAGS $INC "$t" $OBJ/sp1_synth.o $OBJ/sp1_marbles.o $OBJ/sp1_midi.o \
$OBJ/pui.o $OBJ/mui.o "$LIB" -lm -o "$out" ;;
- *.c) gcc $CFLAGS $INC "$t" $OBJ/pui.o $OBJ/mui.o $OBJ/sp1_midi.o -lm -o "$out" ;;
+ *.c) gcc $CFLAGS $INC "$t" $OBJ/pui.o $OBJ/mui.o $OBJ/prst.o $OBJ/sp1_midi.o -lm -o "$out" ;;
esac
echo "$out"
done
diff --git a/tools/host-tests/miditest.cc b/tools/host-tests/miditest.cc
index 879ed2f..50132bd 100644
--- a/tools/host-tests/miditest.cc
+++ b/tools/host-tests/miditest.cc
@@ -568,6 +568,40 @@ int main() {
"MODEL may change at most every 50 ms: 8 ms after the last change it must hold");
sp1_midi_main_tick(48);
CHECK(sp1_pui_engine() == sel, "MODEL 0 -> the selection, once 50 ms have passed");
+ {
+ // #50: an engine OFF the list (loaded from a PRST slot) -- MODEL counts from list
+ // position 1, and MODEL 0 plays the off-list engine again.
+ int off = -1;
+ for (int e = 0; e < SP1_PLAITS_ENGINE_COUNT && off < 0; ++e) {
+ bool listed = false;
+ for (int i = 0; i < SP1_ENGINE_SLOTS; ++i)
+ listed = listed || (SP1_ENGINE_TABLE[i].on && SP1_ENGINE_TABLE[i].plaits == e);
+ if (!listed) off = e;
+ }
+ if (off >= 0) {
+ struct sp1_pui_patch pp;
+ sp1_pui_get(&pp);
+ const int keep = pp.slot;
+ pp.slot = SP1_PUI_OFFLIST + off;
+ sp1_pui_put(&pp);
+ CHECK(sp1_pui_engine() == off, "off-list engine %d not playing (got %d)", off,
+ sp1_pui_engine());
+ sp1_midi_main_tick(56);
+ cc(105, 127);
+ render_rms(1);
+ sp1_midi_main_tick(8);
+ CHECK(sp1_pui_engine() == SP1_ENGINE_TABLE[lastf].plaits,
+ "off-list + MODEL 127 -> the last filled slot, got engine %d", sp1_pui_engine());
+ sp1_midi_main_tick(56);
+ cc(105, 0);
+ render_rms(1);
+ sp1_midi_main_tick(56);
+ CHECK(sp1_pui_engine() == off, "off-list + MODEL 0 -> the off-list engine, got %d",
+ sp1_pui_engine());
+ pp.slot = keep;
+ sp1_pui_put(&pp);
+ }
+ }
sp1_pui_params(&sp);
CHECK(sp.level_patched == 0, "LEVEL fader at 0 is disconnected");
cc(26, 127); // LEVEL CC pushes the fader up
diff --git a/tools/host-tests/prsttest.c b/tools/host-tests/prsttest.c
new file mode 100644
index 0000000..0f6ee60
--- /dev/null
+++ b/tools/host-tests/prsttest.c
@@ -0,0 +1,569 @@
+/* wakes-sp1 M6 (#50): host checks of the PRST slot format and its field check.
+ * Links the real sp1_prst.c + both UI files; the audio-thread parts are stubbed as in uitest. */
+#include
+#include
+#include
+#include
+
+#include "sp1_prst.h"
+#include "sp1_engines_gen.h" /* which engines config/engines.csv lists */
+
+/* ---- stubs for the parts that live in the audio thread (as uitest.c) ---- */
+uint8_t sp1_marbles_last_gates(void) { return 0u; }
+float sp1_marbles_last_volts(int k) { (void)k; return 0.0f; }
+float sp1_marbles_bpm(float rate, int r) { (void)r; return 120.0f * powf(2.0f, rate / 12.0f); }
+const char *sp1_marbles_model_name(int m) { (void)m; return "?"; }
+void sp1_marbles_plaits_scale(int s) { (void)s; }
+float sp1_marbles_plaits_quantize(float st) { return st; }
+int sp1_marbles_plaits_degrees(float *st, int max) { (void)st; (void)max; return 0; }
+const char *sp1_marbles_scale_name(int s) { (void)s; return "?"; }
+
+static int fails;
+#define CHECK(cond, ...) do { if (!(cond)) { printf(" FAIL: "); \
+ printf(__VA_ARGS__); printf("\n"); fails++; } } while (0)
+
+static const uint16_t raw_mid[4] = { 1850, 1850, 1850, 1850 };
+static char text[SP1_PRST_TEXT_MAX];
+
+/* Marbles slots a file does not carry: X BASE F4 and X SHIFT F4 are the t page's (canon()),
+ * X SHIFT F1-F3 are reserved. They come back as their defaults whatever they were. */
+static bool carried_m(int l, int i)
+{
+ return !((l == SP1_MUI_X_BASE && i == 3) || l == SP1_MUI_X_SHIFT);
+}
+
+/* Field-by-field difference, positions within half the file's last digit. Returns the
+ * number of differences and prints the first few. */
+static int diff(const struct sp1_prst *a, const struct sp1_prst *b, const char *what)
+{
+ int n = 0;
+#define D(cond, ...) do { if (cond) { if (n < 4) { printf(" %s: ", what); \
+ printf(__VA_ARGS__); printf("\n"); } n++; } } while (0)
+ D(a->plaits.slot != b->plaits.slot, "engine slot %d vs %d", a->plaits.slot, b->plaits.slot);
+ for (int l = 0; l < SP1_PUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ D(fabsf(a->plaits.v[l][i] - b->plaits.v[l][i]) > 0.00005f,
+ "plaits v[%d][%d] %.5f vs %.5f", l, i, a->plaits.v[l][i], b->plaits.v[l][i]);
+ }
+ }
+ D(a->plaits.scale != b->plaits.scale, "quantizer %d vs %d", a->plaits.scale, b->plaits.scale);
+ D(a->out_mode != b->out_mode, "output %d vs %d", a->out_mode, b->out_mode);
+ D(a->burst_div != b->burst_div, "burst %d vs %d", a->burst_div, b->burst_div);
+ D(a->drive != b->drive, "drive %d vs %d", a->drive, b->drive);
+ for (int l = 0; l < SP1_MUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ if (carried_m(l, i)) {
+ D(fabsf(a->marbles.v[l][i] - b->marbles.v[l][i]) > 0.00005f,
+ "marbles v[%d][%d] %.5f vs %.5f", l, i, a->marbles.v[l][i],
+ b->marbles.v[l][i]);
+ }
+ }
+ }
+ const struct sp1_mui_patch *x = &a->marbles, *y = &b->marbles;
+ D(x->model != y->model, "t model %d vs %d", x->model, y->model);
+ D(x->t_range != y->t_range, "t range %d vs %d", x->t_range, y->t_range);
+ D(x->range != y->range, "[J] %d vs %d", x->range, y->range);
+ D(x->diversity != y->diversity, "diversity %d vs %d", x->diversity, y->diversity);
+ D(x->scale != y->scale, "scale %d vs %d", x->scale, y->scale);
+ D(x->dv_t != y->dv_t || x->dv_x != y->dv_x, "deja vu toggles");
+ for (int k = 0; k < 3; k++) {
+ D(x->t_dest[k] != y->t_dest[k], "t%d %d vs %d", k + 1, x->t_dest[k], y->t_dest[k]);
+ }
+ for (int k = 0; k < 4; k++) {
+ D(x->dest[k] != y->dest[k], "x%d %d vs %d", k + 1, x->dest[k], y->dest[k]);
+ }
+#undef D
+ return n;
+}
+
+/* A patch nothing like the defaults: every field off its default value. */
+static void unusual(struct sp1_prst *p)
+{
+ sp1_prst_rip(p, -1);
+ p->plaits.slot = 6; /* chords */
+ for (int l = 0; l < SP1_PUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ p->plaits.v[l][i] = 0.1234f + 0.05f * (float)(l * 4 + i);
+ }
+ }
+ p->plaits.v[SP1_PUI_BASE][0] = 1.0f; /* both ends survive */
+ p->plaits.v[SP1_PUI_BASE][1] = 0.0f;
+ p->plaits.scale = 3; /* pelog */
+ p->out_mode = SP1_OUT_RING;
+ p->burst_div = 7;
+ p->drive = 4;
+ for (int l = 0; l < SP1_MUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ if (carried_m(l, i)) {
+ p->marbles.v[l][i] = 0.9876f - 0.04f * (float)(l * 4 + i);
+ }
+ }
+ }
+ p->marbles.model = 5;
+ p->marbles.t_range = 2;
+ p->marbles.range = SP1_MRB_RANGE_FULL;
+ p->marbles.diversity = 2;
+ p->marbles.scale = 5;
+ p->marbles.dv_t = 0;
+ p->marbles.dv_x = 1;
+ p->marbles.t_dest[0] = SP1_DEST_HARM;
+ p->marbles.t_dest[1] = SP1_DEST_LEVEL;
+ p->marbles.t_dest[2] = SP1_DEST_TRIG;
+ p->marbles.dest[0] = SP1_DEST_FM;
+ p->marbles.dest[1] = SP1_DEST_TIMBRE;
+ p->marbles.dest[2] = SP1_DEST_MORPH;
+ p->marbles.dest[3] = SP1_DEST_LEVEL; /* not V/Oct: the quantizer is on (M4b) */
+}
+
+/* Everything a parse returns must be safe to hand to the UIs: every value finite and in
+ * its range, every choice one the firmware can hold. */
+static bool safe(const struct sp1_prst *p)
+{
+ for (int l = 0; l < SP1_PUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ const float v = p->plaits.v[l][i];
+ if (!(v >= 0.0f && v <= 1.0f)) { return false; }
+ }
+ }
+ for (int l = 0; l < SP1_MUI_LAYERS; l++) {
+ for (int i = 0; i < 4; i++) {
+ const float v = p->marbles.v[l][i];
+ if (!(v >= 0.0f && v <= 1.0f)) { return false; }
+ }
+ }
+ if (strcmp(sp1_pui_slot_name(p->plaits.slot), "") == 0) { return false; }
+ if (p->plaits.scale != SP1_PUI_SCALE_OFF && !sp1_mui_scale_included(p->plaits.scale)) {
+ return false;
+ }
+ if (p->out_mode < 0 || p->out_mode >= SP1_OUT_COUNT) { return false; }
+ if (p->burst_div < 0 || p->burst_div > 7) { return false; }
+ if (p->drive < 0 || p->drive >= SP1_DRIVE_STEPS) { return false; }
+ const struct sp1_mui_patch *m = &p->marbles;
+ if (m->model < 0 || m->model > 5 || m->t_range < 0 || m->t_range > 2) { return false; }
+ if (m->range < 0 || m->range >= SP1_MRB_RANGE_COUNT) { return false; }
+ if (m->diversity < 0 || m->diversity > 2 || !sp1_mui_scale_included(m->scale)) {
+ return false;
+ }
+ if ((m->dv_t != 0 && m->dv_t != 1) || (m->dv_x != 0 && m->dv_x != 1)) { return false; }
+ for (int k = 0; k < 3; k++) {
+ if (!sp1_mui_dest_allowed(true, m->t_dest[k])) { return false; }
+ }
+ for (int k = 0; k < 4; k++) {
+ if (!sp1_mui_dest_allowed(false, m->dest[k])) { return false; }
+ /* the V/Oct interlock (M4b): never a quantizer AND a V/Oct route */
+ if (m->dest[k] == SP1_DEST_VOCT && p->plaits.scale != SP1_PUI_SCALE_OFF) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* `base` with the line for `key` replaced by "key = value" (value NULL: the line removed). */
+static int with(const char *base, const char *key, const char *value, char *out, size_t size)
+{
+ size_t at = 0;
+ const char *p = base;
+ const size_t kl = strlen(key);
+ while (*p) {
+ const char *e = strchr(p, '\n');
+ const size_t n = e ? (size_t)(e - p + 1) : strlen(p);
+ if (strncmp(p, key, kl) == 0 && p[kl] == ' ' && p[kl + 1] == '=') {
+ if (value) {
+ at += (size_t)snprintf(out + at, size - at, "%s = %s\n", key, value);
+ }
+ } else {
+ memcpy(out + at, p, n);
+ at += n;
+ }
+ p += n;
+ }
+ out[at] = '\0';
+ return (int)at;
+}
+
+int main(void)
+{
+ struct sp1_prst a, b, d;
+ struct sp1_prst_report rep;
+
+ /* ---------- 1. the defaults: one source, and the rip still gives them ---------- */
+ printf("1. ROTC defaults\n");
+ sp1_pui_init();
+ sp1_mui_init();
+ sp1_pui_enter(raw_mid);
+ sp1_mui_enter(raw_mid, false);
+ sp1_pui_rip();
+ sp1_mui_rip();
+ sp1_prst_rip(&d, -1);
+ a = d;
+ sp1_pui_get(&a.plaits);
+ 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,
+ "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,
+ "virtual analog's neutral BASE is wrong");
+ /* #50: t2 -> TRIG and X2 -> V/Oct, every other cable out */
+ CHECK(d.marbles.t_dest[0] == SP1_DEST_NONE && d.marbles.t_dest[1] == SP1_DEST_TRIG &&
+ d.marbles.t_dest[2] == SP1_DEST_NONE && d.marbles.dest[0] == SP1_DEST_NONE &&
+ d.marbles.dest[1] == SP1_DEST_VOCT && d.marbles.dest[2] == SP1_DEST_NONE &&
+ d.marbles.dest[3] == SP1_DEST_NONE, "the ROTC routing is not t2 TRIG + X2 V/Oct");
+ CHECK(d.out_mode == SP1_OUT_MAIN && d.burst_div == 5 && d.drive == 0,
+ "main's defaults wrong");
+ /* boot is NOT the rip: t2 -> TRIG and X1 -> V/Oct (M4d) */
+ sp1_mui_init();
+ sp1_mui_get(&b.marbles);
+ CHECK(b.marbles.t_dest[1] == SP1_DEST_TRIG && b.marbles.dest[0] == SP1_DEST_VOCT,
+ "boot routing lost");
+ /* a different engine's neutral: chords has no bipolar parameter */
+ 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 */
+ CHECK(b.plaits.slot == 0, "an empty slot was accepted");
+
+ /* ---------- 2. write -> read gives the patch back ---------- */
+ printf("2. round trip\n");
+ int n = sp1_prst_write(&d, text, sizeof(text));
+ CHECK(n > 0, "the defaults do not fit");
+ printf(" the default patch, %d bytes:\n", n);
+ for (const char *p = text; *p;) {
+ const char *e = strchr(p, '\n');
+ printf(" | %.*s\n", (int)(e ? e - p : (long)strlen(p)), p);
+ p = e ? e + 1 : p + strlen(p);
+ }
+ sp1_prst_parse(text, (size_t)n, &a, &rep);
+ CHECK(rep.format_ok && rep.defaulted == 0 && rep.bad == 0,
+ "defaults: format_ok %d defaulted %d bad %d", rep.format_ok, rep.defaulted, rep.bad);
+ CHECK(diff(&a, &d, "defaults") == 0, "the defaults do not survive a round trip");
+
+ unusual(&b);
+ n = sp1_prst_write(&b, text, sizeof(text));
+ sp1_prst_parse(text, (size_t)n, &a, &rep);
+ CHECK(rep.format_ok && rep.defaulted == 0, "unusual: defaulted %d (first bad %s)",
+ rep.defaulted, rep.first_bad ? rep.first_bad : "-");
+ CHECK(diff(&a, &b, "unusual") == 0, "an unusual patch does not survive a round trip");
+ /* ...and through the UIs: put, get, write, read */
+ sp1_pui_put(&b.plaits);
+ sp1_mui_put(&b.marbles);
+ a = b;
+ sp1_pui_get(&a.plaits);
+ sp1_mui_get(&a.marbles);
+ CHECK(diff(&a, &b, "through the UIs") == 0, "put/get changed the patch");
+ CHECK(sp1_pui_slot() == 6 && sp1_pui_scale() == 3 && sp1_mui_model() == 5 &&
+ sp1_mui_range() == SP1_MRB_RANGE_FULL, "the UIs did not take the patch");
+ /* the largest patch the format can produce fits, with room to spare */
+ CHECK(n < SP1_PRST_TEXT_MAX / 2, "a patch is %d bytes, close to the buffer", n);
+
+ /* ---------- 3. the field check: one bad field, the rest still loads ---------- */
+ printf("3. field check\n");
+ unusual(&b);
+ const int good_n = sp1_prst_write(&b, text, sizeof(text));
+ (void)good_n;
+ static const struct { const char *key, *value; } bad[] = {
+ { "timbre", "nan" }, { "timbre", "NaN" }, { "timbre", "inf" },
+ { "timbre", "-0.1000" }, { "timbre", "1.0001" }, { "timbre", "1e-1" },
+ { "timbre", "0.5abc" }, { "timbre", "" }, { "timbre", "." },
+ { "timbre", "0x1" }, { "timbre", "0.5 0.6" }, { "timbre", "\x01\xff" },
+ { "rate", "99999999999999999999" }, { "rate", "+0.5" },
+ { "output", "speaker" }, { "drive", "+30db" }, { "burst", "1/3" },
+ { "quantizer", "free" }, /* the free scale slot is not included */
+ { "scale", "off" }, /* Marbles' scale has no "off" */
+ { "scale", "free" },
+ { "t1", "voct" }, /* V/Oct is not on the t ring */
+ { "x1", "trig" }, /* TRIG is not on the X ring */
+ { "y", "banana" }, { "t_range", "x2" }, { "range", "0-10v" },
+ { "deja_vu_t", "yes" }, { "t_model", "7" },
+ };
+ char buf[SP1_PRST_TEXT_MAX + 64];
+ for (size_t k = 0; k < sizeof(bad) / sizeof(bad[0]); k++) {
+ const int m = with(text, bad[k].key, bad[k].value, buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(rep.format_ok && rep.bad == 1 && rep.defaulted == 1 && rep.first_bad &&
+ strcmp(rep.first_bad, bad[k].key) == 0,
+ "%s = '%s': bad %d defaulted %d first %s", bad[k].key, bad[k].value,
+ rep.bad, rep.defaulted, rep.first_bad ? rep.first_bad : "-");
+ CHECK(safe(&a), "%s = '%s' left an unsafe patch", bad[k].key, bad[k].value);
+ /* exactly one field moved, and to its default */
+ struct sp1_prst want = b;
+ struct sp1_prst defs;
+ sp1_prst_rip(&defs, b.plaits.slot);
+ /* copy the default into `want` by re-parsing a file without that key */
+ const int m2 = with(text, bad[k].key, NULL, buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m2, &want, &rep);
+ CHECK(rep.defaulted == 1 && rep.bad == 0, "%s: removing it did not default it",
+ bad[k].key);
+ CHECK(diff(&a, &want, bad[k].key) == 0, "%s = '%s' is not 'that field's default'",
+ bad[k].key, bad[k].value);
+ (void)defs;
+ }
+ /* the default IS the ROTC one: a bad TIMBRE on chords is chords' neutral (0, unipolar);
+ * on virtual analog it is 0.5 (bipolar) -- Adara: neutral for the LOADED engine */
+ int m = with(text, "timbre", "nan", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(a.plaits.slot == 6 && a.plaits.v[SP1_PUI_BASE][1] == 0.0f,
+ "chords: bad TIMBRE -> %.3f, not 0", a.plaits.v[SP1_PUI_BASE][1]);
+ char buf2[SP1_PRST_TEXT_MAX + 64];
+ with(text, "engine", "Virtual Analog", buf2, sizeof(buf2)); /* case ignored */
+ m = with(buf2, "timbre", "nan", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(a.plaits.slot == 0 && a.plaits.v[SP1_PUI_BASE][1] == 0.5f && rep.bad == 1,
+ "virtual analog: bad TIMBRE -> %.3f, not 0.5", a.plaits.v[SP1_PUI_BASE][1]);
+ CHECK(fabsf(a.plaits.v[SP1_PUI_BASE][2] - b.plaits.v[SP1_PUI_BASE][2]) < 0.0001f,
+ "a GOOD BASE field was replaced");
+ /* an unknown engine -> slot 1 (Adara); its good faders still load */
+ m = with(text, "engine", "west coast complex", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(a.plaits.slot == 0 && rep.bad == 1 && rep.first_bad &&
+ strcmp(rep.first_bad, "engine") == 0, "an unknown engine is not slot 1");
+ CHECK(fabsf(a.plaits.v[SP1_PUI_BASE][2] - b.plaits.v[SP1_PUI_BASE][2]) < 0.0001f &&
+ a.marbles.model == 5, "an unknown engine took the rest of the file with it");
+ /* the V/Oct interlock: the quantizer goes, the route stays */
+ m = with(text, "x2", "voct", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(a.marbles.dest[1] == SP1_DEST_VOCT && a.plaits.scale == SP1_PUI_SCALE_OFF &&
+ rep.bad == 1 && rep.first_bad && strcmp(rep.first_bad, "quantizer") == 0,
+ "quantizer + V/Oct: scale %d, x2 %d, bad %d", a.plaits.scale, a.marbles.dest[1],
+ rep.bad);
+ /* every value missing: all defaults, nothing called bad */
+ sp1_prst_parse("[wakes]\nformat = 1\n", 19, &a, &rep);
+ CHECK(rep.format_ok && rep.defaulted == sp1_prst_fields() && rep.bad == 0,
+ "an empty slot: defaulted %d bad %d", rep.defaulted, rep.bad);
+ CHECK(diff(&a, &d, "empty") == 0, "an empty slot is not the ROTC default");
+
+ /* ---------- 4. the format version ---------- */
+ printf("4. format version\n");
+ static const char *const fmts[] = {
+ NULL, "2", "0", "1x", "", "01x", " ", "999999999", "-1",
+ };
+ for (size_t k = 0; k < sizeof(fmts) / sizeof(fmts[0]); k++) {
+ m = with(text, "format", fmts[k], buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(!rep.format_ok && rep.defaulted == sp1_prst_fields(),
+ "format '%s' was accepted", fmts[k] ? fmts[k] : "(none)");
+ CHECK(diff(&a, &d, "format") == 0, "format '%s': not the whole default slot",
+ fmts[k] ? fmts[k] : "(none)");
+ }
+ /* `format` must be in [wakes]: the same line elsewhere is not a version */
+ m = with(text, "format", NULL, buf, sizeof(buf));
+ strcat(buf, "[plaits]\nformat = 1\n");
+ sp1_prst_parse(buf, strlen(buf), &a, &rep);
+ CHECK(!rep.format_ok, "a format line outside [wakes] counted");
+ /* "01" is a decimal 1: accepted */
+ m = with(text, "format", "01", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(rep.format_ok && rep.defaulted == 0, "format 01 rejected");
+
+ /* ---------- 5. the text as people edit it ---------- */
+ printf("5. hand-edited text\n");
+ {
+ /* CRLF, tabs, comments, blank lines, case, unknown keys and sections, keys before
+ * any section, a duplicate (the last wins), no newline at the end */
+ const char *t =
+ "; my preset\r\n"
+ "stray = 1\r\n"
+ "\r\n"
+ "[ WAKES ]\r\n"
+ "\tFormat\t=\t1\r\n"
+ "[Plaits]\r\n"
+ "# a comment\r\n"
+ "Engine = CHORDS\r\n"
+ "timbre = 0.25\r\n"
+ "timbre=0.75\r\n"
+ "wobble = 0.3\r\n"
+ "[future]\r\n"
+ "timbre = 0.1\r\n"
+ "[marbles]\r\n"
+ "t1 = Level\r\n"
+ "rate = 1";
+ sp1_prst_parse(t, strlen(t), &a, &rep);
+ CHECK(rep.format_ok && rep.bad == 0, "hand-edited: format_ok %d bad %d",
+ rep.format_ok, rep.bad);
+ CHECK(a.plaits.slot == 6, "Engine = CHORDS not read");
+ CHECK(fabsf(a.plaits.v[SP1_PUI_BASE][1] - 0.75f) < 1e-6f,
+ "duplicate: timbre %.3f, not the last (0.75)", a.plaits.v[SP1_PUI_BASE][1]);
+ CHECK(a.marbles.t_dest[0] == SP1_DEST_LEVEL, "t1 = Level not read");
+ CHECK(a.marbles.v[SP1_MUI_T_BASE][0] == 1.0f, "a last line without a newline lost");
+ /* a section header that never closes: what follows belongs to no section */
+ const char *u = "[wakes]\nformat = 1\n[plaits\ntimbre = 0.75\n";
+ sp1_prst_parse(u, strlen(u), &a, &rep);
+ CHECK(rep.format_ok && a.plaits.v[SP1_PUI_BASE][1] == 0.5f,
+ "a key under a broken section header was used");
+ /* NUL bytes inside the text are just bad characters */
+ char z[64] = "[wakes]\nformat = 1\n[plaits]\ntimbre = 0.2\0\n";
+ sp1_prst_parse(z, 41, &a, &rep);
+ CHECK(rep.bad == 1, "a NUL inside a value was accepted");
+ /* NULL / zero length */
+ sp1_prst_parse(NULL, 0, &a, &rep);
+ CHECK(!rep.format_ok && safe(&a), "NULL text");
+ }
+
+ /* ---------- 6. the writer never overruns ---------- */
+ printf("6. writer bounds\n");
+ unusual(&b);
+ n = sp1_prst_write(&b, text, sizeof(text));
+ for (int size = 0; size <= n; size++) {
+ char small[SP1_PRST_TEXT_MAX + 8];
+ memset(small, 0x5a, sizeof(small));
+ const int r = sp1_prst_write(&b, small, (size_t)size);
+ CHECK(r == -1, "size %d (needs %d): returned %d", size, n + 1, r);
+ for (int k = size; k < (int)sizeof(small); k++) {
+ if (small[k] != 0x5a) {
+ CHECK(0, "size %d: wrote byte %d", size, k);
+ break;
+ }
+ }
+ }
+ CHECK(sp1_prst_write(&b, text, (size_t)n + 1u) == n, "exact size refused");
+ /* garbage in a patch never reaches the file: NaN writes as 0, unknown choices are left
+ * out (and so load their default) */
+ b.plaits.v[SP1_PUI_BASE][1] = NAN;
+ b.marbles.dest[3] = 99;
+ n = sp1_prst_write(&b, text, sizeof(text));
+ sp1_prst_parse(text, (size_t)n, &a, &rep);
+ CHECK(rep.bad == 0 && rep.defaulted == 1 && a.plaits.v[SP1_PUI_BASE][1] == 0.0f &&
+ a.marbles.dest[3] == SP1_DEST_NONE, "garbage in a patch was written");
+
+ /* ---------- 7. the UIs' own sanitising (put) ---------- */
+ printf("7. put sanitises\n");
+ sp1_prst_rip(&b, -1);
+ b.plaits.slot = 23; /* empty */
+ b.plaits.v[SP1_PUI_SHIFT][0] = NAN;
+ b.plaits.v[SP1_PUI_SHIFT][1] = 7.0f;
+ b.plaits.scale = 42;
+ b.marbles.v[SP1_MUI_Y][0] = INFINITY;
+ b.marbles.model = -3;
+ b.marbles.scale = 6; /* not included */
+ b.marbles.t_dest[0] = SP1_DEST_VOCT;
+ b.marbles.dest[0] = SP1_DEST_TRIG;
+ sp1_pui_put(&b.plaits);
+ sp1_mui_put(&b.marbles);
+ sp1_pui_get(&a.plaits);
+ sp1_mui_get(&a.marbles);
+ a.out_mode = b.out_mode; a.burst_div = b.burst_div; a.drive = b.drive;
+ CHECK(safe(&a), "put kept something unsafe");
+ CHECK(a.plaits.slot == 0 && a.plaits.v[SP1_PUI_SHIFT][0] == 0.0f &&
+ a.plaits.v[SP1_PUI_SHIFT][1] == 1.0f && a.plaits.scale == SP1_PUI_SCALE_OFF,
+ "plaits put");
+ CHECK(a.marbles.model == d.marbles.model && a.marbles.scale == d.marbles.scale &&
+ a.marbles.t_dest[0] == d.marbles.t_dest[0] && a.marbles.dest[0] == d.marbles.dest[0]
+ && a.marbles.v[SP1_MUI_Y][0] == d.marbles.v[SP1_MUI_Y][0], "marbles put");
+ /* the parameters the synth gets from a sanitised patch are finite */
+ {
+ struct sp1_synth_params sp;
+ struct sp1_marbles_params mp;
+ sp1_pui_params(&sp);
+ sp1_mui_params(&mp);
+ CHECK(isfinite(sp.note) && isfinite(sp.timbre) && isfinite(sp.fm_mod) &&
+ isfinite(mp.rate) && isfinite(mp.y_spread), "non-finite synth params");
+ }
+
+ /* ---------- 8. nothing a card can hold crashes it or gets through unchecked ---------- */
+ printf("8. corrupt files\n");
+ unusual(&b);
+ n = sp1_prst_write(&b, text, sizeof(text));
+ int unsafe = 0, runs = 0;
+ /* every truncation of a good file */
+ for (int len = 0; len <= n; len++) {
+ sp1_prst_parse(text, (size_t)len, &a, &rep);
+ unsafe += !safe(&a);
+ runs++;
+ }
+ /* random byte damage, and pure noise */
+ srand(50);
+ for (int k = 0; k < 20000; k++) {
+ memcpy(buf, text, (size_t)n);
+ const int hits = 1 + rand() % 8;
+ for (int h = 0; h < hits; h++) {
+ buf[rand() % n] = (char)(rand() & 0xff);
+ }
+ sp1_prst_parse(buf, (size_t)n, &a, &rep);
+ unsafe += !safe(&a);
+ runs++;
+ }
+ for (int k = 0; k < 2000; k++) {
+ const int len = rand() % (int)sizeof(buf);
+ for (int i = 0; i < len; i++) {
+ buf[i] = (char)(rand() & 0xff);
+ }
+ sp1_prst_parse(buf, (size_t)len, &a, &rep);
+ unsafe += !safe(&a);
+ runs++;
+ }
+ CHECK(unsafe == 0, "%d of %d corrupt files gave an unsafe patch", unsafe, runs);
+ printf(" %d corrupt files, all safe\n", runs);
+
+ /* ---------- 9. an engine OFF the list (#50) ---------- */
+ printf("9. engines off engines.csv\n");
+ {
+ int off = -1, first = -1, last = -1;
+ for (int i = 0; i < SP1_ENGINE_SLOTS; i++) {
+ if (SP1_ENGINE_TABLE[i].on) {
+ first = first < 0 ? i : first;
+ last = i;
+ }
+ }
+ for (int e = 0; e < SP1_PLAITS_ENGINE_COUNT && off < 0; e++) {
+ bool listed = false;
+ for (int i = 0; i < SP1_ENGINE_SLOTS; i++) {
+ listed = listed ||
+ (SP1_ENGINE_TABLE[i].on && SP1_ENGINE_TABLE[i].plaits == e);
+ }
+ if (!listed) {
+ off = e;
+ }
+ }
+ CHECK(off >= 0, "every engine is listed: nothing to test");
+ if (off >= 0) {
+ const char *nm = SP1_PLAITS_ENGINES[off].name;
+ printf(" %s (plaits %d) is not on the list\n", nm, off);
+ /* the file: by name (case ignored), resolved off the list, its own neutral */
+ unusual(&b);
+ n = sp1_prst_write(&b, text, sizeof(text));
+ char up[64];
+ snprintf(up, sizeof(up), "%s", nm);
+ for (char *c = up; *c; c++) {
+ *c = (char)((*c >= 'a' && *c <= 'z') ? *c - 32 : *c);
+ }
+ with(text, "engine", up, buf2, sizeof(buf2));
+ m = with(buf2, "morph", "nan", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ const uint8_t c = SP1_PLAITS_ENGINES[off].centre;
+ CHECK(a.plaits.slot == SP1_PUI_OFFLIST + off && rep.bad == 1,
+ "engine = %s -> slot %d, bad %d", up, a.plaits.slot, rep.bad);
+ CHECK(a.plaits.v[SP1_PUI_BASE][2] == ((c & 0x4u) ? 0.5f : 0.0f),
+ "bad MORPH is not %s's neutral: %.2f", nm, a.plaits.v[SP1_PUI_BASE][2]);
+ CHECK(safe(&a), "an off-list engine gave an unsafe patch");
+ /* and back out: written by its name */
+ n = sp1_prst_write(&a, text, sizeof(text));
+ 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");
+ /* the UI plays it, with its own detents and no glyph */
+ sp1_pui_put(&a.plaits);
+ struct sp1_synth_params sp;
+ sp1_pui_params(&sp);
+ uint8_t lv[4] = { 1, 1, 1, 1 };
+ sp1_pui_engine_leds(lv);
+ CHECK(sp1_pui_engine() == off && sp.engine == off &&
+ sp1_pui_engine_centre() == c && strcmp(sp1_pui_engine_name(), nm) == 0,
+ "the UI does not play %s", nm);
+ CHECK(sp1_pui_offlist(sp1_pui_slot()) && !lv[0] && !lv[1] && !lv[2] && !lv[3],
+ "an off-list engine drew a glyph");
+ /* T3 -> the first listed engine, T2 -> the last (Adara) */
+ CHECK(sp1_pui_engine_step(+1) == first, "T3 from off the list: not the first");
+ sp1_pui_put(&a.plaits);
+ CHECK(sp1_pui_engine_step(-1) == last, "T2 from off the list: not the last");
+ CHECK(sp1_pui_engine_step(+1) != last, "stepping on from the last is stuck");
+ }
+ /* still: a name no engine of this build has -> list position 1 */
+ m = with(text, "engine", "6-op FM D", buf, sizeof(buf));
+ sp1_prst_parse(buf, (size_t)m, &a, &rep);
+ CHECK(a.plaits.slot == 0 && rep.bad == 1, "an unknown engine is not slot 1");
+ }
+
+ printf(fails ? "\nprsttest: %d FAILED\n" : "\nprsttest: all passed\n", fails);
+ return fails ? 1 : 0;
+}
diff --git a/tools/host-tests/uitest.c b/tools/host-tests/uitest.c
index c81d050..e9e4308 100644
--- a/tools/host-tests/uitest.c
+++ b/tools/host-tests/uitest.c
@@ -478,11 +478,14 @@ int main(void)
sp1_mui_rip();
sp1_mui_routing(&r);
sp1_mui_params(&b);
+ /* #50 (Adara): t2 -> TRIG and X2 -> V/Oct come back; nothing else */
for (int i = 0; i < 3; i++) {
- CHECK(r.t_dest[i] == SP1_DEST_NONE, "rip left t%d routed", i + 1);
+ CHECK(r.t_dest[i] == (i == 1 ? SP1_DEST_TRIG : SP1_DEST_NONE),
+ "rip: t%d -> %u", i + 1, r.t_dest[i]);
}
for (int i = 0; i < 4; i++) {
- CHECK(r.dest[i] == SP1_DEST_NONE, "rip left X/Y %d routed", i + 1);
+ CHECK(r.dest[i] == (i == 1 ? SP1_DEST_VOCT : SP1_DEST_NONE),
+ "rip: X/Y %d -> %u", i + 1, r.dest[i]);
}
CHECK(sp1_mui_model() == 0, "rip did not return the model to coin toss");
CHECK(sp1_mui_scale() == 0, "rip did not return the scale to major");
@@ -492,7 +495,7 @@ int main(void)
CHECK(fabsf(b.x_bias - 0.5f) < 1e-3f, "rip did not reset X BIAS");
CHECK(fabsf(b.t_bias - 0.5f) < 1e-3f, "rip did not reset t BIAS");
CHECK(b.t_jitter == 0.0f, "rip did not reset JITTER");
- printf(" marbles rip: every output disconnected, %d BPM, model 1, major\n",
+ printf(" marbles rip: t2 -> TRIG, X2 -> V/Oct, the rest out, %d BPM, model 1, major\n",
(int)sp1_mui_bpm());
/* and the page you were standing on is kept */
CHECK(sp1_mui_page() == SP1_MUI_PAGE_X, "rip moved me off the X page");
diff --git a/west.yml b/west.yml
index ba7576c..15009b7 100644
--- a/west.yml
+++ b/west.yml
@@ -9,6 +9,10 @@
# three reached a real build. Do not widen it to `import: true` (~2 GB more and
# a full re-update) and do not drop `cmsis_6` -- the Kconfig fix in
# zephyr-patches/ depends on modules/cmsis_6 being present.
+#
+# `fatfs` (M6, #43; added with Adara's approval, 2026-10-07): ChaN's FatFs as Zephyr
+# packages it, for the FAT filesystem PRST keeps on the eMMC. Revision is whatever the
+# pinned Zephyr's own west.yml names. Every module added here is Adara's call.
manifest:
remotes:
- name: zephyrproject-rtos
@@ -22,6 +26,7 @@ manifest:
name-allowlist:
- cmsis
- cmsis_6
+ - fatfs
- hal_nordic
self: