SLOOP 2.3: USB audio, MIDI IN jack, MIDI clock, REC modes, lights, backup, CHOP of any length, knob and USB MIDI fixes

This commit is contained in:
isod89 committed 2026-10-05 22:32:43 -04:00
1 parent f2b44c219b
commit d691ba7b2d
45 files changed
+4021 -550

No files matched your search

+2 -1
View File
@@ -59,7 +59,8 @@ Build options (environment, `0` or `1`; defaults in `firmware/src/felucca.c`):
| `FELUCCA_FLASH` | 1 | settings, presets and projects in flash |
| `FELUCCA_OTA` | 1 | update entry (needs `FELUCCA_FLASH`) |
| `FELUCCA_CDC` | 1 | USB serial console |
| `FELUCCA_UART` | 0 | TRS MIDI IN (not tested on hardware) |
| `FELUCCA_UAC` | 1 | USB audio input: the master output, 44.1 kHz stereo (after Felucca 1.0) |
| `FELUCCA_UART` | 1 | TRS MIDI IN (the 3.5 mm jack) |
## Samples
+39 -5
View File
@@ -1,6 +1,6 @@
<p align="center"><img src="assets/logo/sloop-logo.png" alt="SLOOP" width="360"></p>
# SLOOP 2.0 — démarrage rapide
# SLOOP 2.3 — démarrage rapide
**SLOOP** transforme le M-VAVE FM-1 en groovebox à jouer en live, pour tous les styles : trois synthés et une batterie de 16 sons sur les touches blanches, 9 moteurs de synthèse, 68 sons rangés par famille (basses, claviers, orgues, nappes, leads, plucks, stabs), 37 kits de batterie (808, 909, trap, phonk, house, techno, UK garage, jungle, amapiano, synthwave, chiptune, ambient…), tes propres samples, ghost notes et ratchets, note repeat, accords sur une touche, 16 effets punch-in, et un écran à la teenage engineering qui montre toujours ce que tes mains peuvent faire. Aucun motif d'usine : tout ce que tu entends, tu le joues.
@@ -66,7 +66,7 @@ Chaque bouton de fonction a deux vies. **Tapé** (appuyé puis relâché sans ri
| **PRESETS** | le son de la piste, ou le kit de batterie |
| **SELECT** | tempo (toujours, même dans un calque) |
| **OCT− / OCT+** | synthés : octave (les deux : retour à 0) · batterie, maintenus : ghost / fort |
| **HOME** | l'écran TRACKS · maintenu : menu (couleur, coupe-bas, zoom, calibration, à propos) · tapé pendant qu'un calque est maintenu : le verrouille |
| **HOME** | l'écran TRACKS · maintenu : menu (couleur, coupe-bas, zoom, lumières, touches, notes, audio USB, calibration, à propos) · tapé pendant qu'un calque est maintenu : le verrouille |
## La batterie : 16 sons sur les touches blanches
@@ -85,7 +85,15 @@ Une touche noire joue le son de la touche blanche à sa gauche (deux doigts sur
| --- | --- | --- |
| **En lecture** | enregistre la piste **tout de suite** | REC à nouveau arrête l'enregistrement, la boucle continue |
| **À l'arrêt, projet avec des notes** | arme (*rec ready*) | **ta première note démarre la boucle et devient le pas 1** |
| **À l'arrêt, projet vide** | arme (*play freely*) | une **prise libre** : la boucle suit ton jeu |
| **À l'arrêt, projet vide** | arme (*play freely*) | une **prise libre** : la boucle suit ton jeu (ou, en mode *tempo*, comme avec des notes) |
**L'écran REC règle la façon d'enregistrer** (armé, avant la première note) :
- **KNOB 1 — mode** (projet vide seulement) : **free** = prise libre, le tempo suit ton jeu · **tempo** = enregistre au tempo réglé (SELECT).
- **KNOB 2 — length** : la boucle de la piste, **1, 2 ou 4 mesures**.
- **KNOB 3 — start** : **note** = ta première note démarre la boucle · **count** = appuie sur **PLAY** : une mesure de clics (4, 3, 2, 1 à l'écran), puis la boucle démarre et enregistre.
Le mode et le départ restent comme tu les as laissés (réglages de la FM-1). Avec des notes déjà dans le projet, pas de mode : on enregistre toujours au tempo réglé. Pendant le décompte, REC l'annule et PLAY revient à *rec ready*.
**Prise libre :** joue librement ; l'écran montre les secondes et la boucle que ça donnerait (*2 bars · 92 bpm*). **REC sur le « 1 » qui suit ta dernière mesure** : SLOOP choisit 1, 2 ou 4 mesures au tempo le plus proche, cale tes notes et lance la boucle. **PLAY** abandonne la prise.
@@ -142,12 +150,38 @@ L'écran **SONG** (SAVE tapé sur TRACKS, ou SAVE + touche 16) montre la chaîne
Chrome ou Edge, FM-1 en USB, **Connect**. Il suit l'appareil en direct.
- **Sequencer** sur la piste batterie : une grille 16 sons × pas, avec le **kit**. Choisis un **niveau** (GHOST, SOFT, NORM, HARD) et un **roll** (x1–x4), puis clique : une frappe ; reclique (même niveau et roll) : effacée ; Maj+clic : un niveau plus fort.
- **Settings → MASTER** : DUST, DUCK, FILT, ROLL. **Tracks** : les quatre tranches (volume, pan, mute ; SOLO et REC affichés). **Samples** : tes sons USR1–USR3 et le découpage CHOP.
- **Settings → MASTER** : DUST, DUCK, FILT, ROLL. **Tracks** : les quatre tranches (volume, pan, mute ; SOLO et REC affichés). **Samples** : tes sons USR1–USR3 et le découpage CHOP (même un enregistrement de plus de 7 s : coche les chops à garder, raccourcis-les, ou **Fit to slot**).
## Clavier MIDI
- **Prise MIDI IN** (jack 3,5 mm TRS du FM-1) : un clavier ou des pads avec une sortie MIDI, via un adaptateur TRS ↔ DIN MIDI. Si rien ne joue, essaie l'autre type d'adaptateur (type A / type B).
- **USB** : depuis un ordinateur ou un téléphone (DAW, appli de routage MIDI) ou un boîtier « USB MIDI host ». Un clavier USB branché directement sur le FM-1 ne peut pas marcher : ce sont deux appareils USB, il faut un hôte.
- **Canaux :** 1, 2, 3 = pistes synth 1, 2, 3 · 10 = la batterie · 4 à 16 = **la piste sélectionnée** (règle ton clavier sur le canal 4 et il suit ALGORITHM).
- **Horloge MIDI :** GLO → SYSTEM → **SYNC** = **USB** ou **TRS**. SLOOP suit le tempo, START, CONTINUE et STOP du maître, sans jamais dériver. Sans horloge pendant une demi-seconde, PLAY rejoue au tempo du FM-1. SYNC est un réglage de la FM-1 : il reste quand tu charges un projet.
- Le MIDI Bluetooth n'est pas pris en charge (la radio reste éteinte).
## Lumières (jouer dans le noir)
Maintiens **HOME** pour le menu : **LIGHTS**, **KEYS** et **NOTES** y sont ensemble. PRESETS déplace, **KNOB 1** règle, OCT+ fait défiler, OCT− ferme. C'est sauvegardé avec les réglages de la FM-1, pas avec un projet : charger un projet ou NEW PROJECT n'y change rien.
- **LIGHTS** — OFF, LOW, MID, HIGH : tous les boutons s'éclairent à ce niveau, on lit les étiquettes dans le noir (illisibles sur un FM-1 noir quand ils sont éteints). Ce qui est actif (la page, PLAY, REC, l'octave) reste en pleine lumière et clignote comme avant.
- **KEYS** — OFF, C KEYS, WHITE KEYS : les touches Do, ou toutes les touches blanches, s'éclairent aussi.
- **NOTES** — ON : sur une piste synth, les notes qui sonnent allument leur touche, jouées au clavier ou par le séquenceur (par @renebohne). Ça marche sur toutes les pages et dans tous les calques : là où les touches jouent ou effacent des notes (EDIT, ARP, SAVE, SCL), les notes sont allumées ; là où les touches sont des tuiles (effets FX, pas SEQ, mute / solo GLO), les notes brillent faiblement et les tuiles gardent leur pleine lumière.
L'éclairage faible est une impulsion très courte à chaque balayage du panneau : pas de scintillement.
## Enregistrer la FM-1 sur l'ordinateur (audio USB)
Branchée en USB, la FM-1 est aussi une **entrée audio** nommée **Felucca** (44,1 kHz, stéréo, sans pilote). Dans ta DAW ou dans Audacity, choisis cette entrée et enregistre : tu as la sortie master, exactement ce qu'on entend au casque (avec DUST, DUCK et FILT). **Le niveau : menu HOME → USB AUDIO.** **MASTER** (par défaut) : l'enregistrement suit le bouton MASTER, comme le casque. **FULL** : niveau fixe, comme MASTER à fond, protégé de la saturation par le limiteur, quel que soit le bouton ; MASTER ne règle alors que le casque (le bon choix pour une carte son sans réglage de niveau). Le MIDI, l'éditeur et l'installateur marchent toujours sur le même câble. La première fois, l'ordinateur reconfigure l'appareil (MIDI + audio) ; le port MIDI garde son nom. Cette entrée vient de Felucca 1.0.
## Sauvegarde complète
Dans l'éditeur, onglet **Projects** → **Backup** : **Save a backup** enregistre tout le contenu de la FM-1 dans un seul fichier (le morceau en cours, les projets 1 à 4, les presets utilisateur, les samples USR1 à USR3, les réglages). **Restore from a file** remet tout comme dans le fichier (ce qui est sur la FM-1 est remplacé). Arrête la lecture (PLAY) avant de restaurer.
## Secours
- **Secours USB :** maintiens **OCT−** seul à l'allumage (*SLOOP USB RESCUE*), puis réinstalle.
- **Installation interrompue :** le FM-1 reste en mode mise à jour ; relance INSTALL et il termine. Un paquet abîmé est refusé et le FM-1 attend un paquet correct.
- **Retour au firmware officiel :** M-UPGRADE de M-VAVE et le firmware FM-1 de m-vave.com.
- **Retour au firmware officiel :** sur la page d'installation, ouvre **Return to the official firmware (V15)** : fais d'abord une sauvegarde avec l'éditeur, télécharge FM-1 V15 sur m-vave.com, choisis son fichier FM-1.fwsc (seul ce fichier exact est accepté) et installe-le. M-UPGRADE de M-VAVE marche aussi (ferme les autres applis qui utilisent le MIDI).
SLOOP est libre (GPL-3.0), basé sur Felucca de Leo Kuroshita (Hügelton Instruments). M-VAVE et FM-1 sont des marques de leurs propriétaires ; SLOOP n'y est pas affilié.
+318 -42
View File
@@ -1,79 +1,355 @@
<p align="center"><img src="assets/logo/sloop-logo.png" alt="SLOOP" width="420"></p>
<p align="center"><img src="assets/logo/sloop-logo.png" alt="SLOOP" width="420"></p>
<p align="center"><b>A live groovebox firmware for the M-VAVE FM-1 — for any style.</b><br>
Free and open source (GPL-3.0), based on <a href="https://github.com/hugelton/Felucca">Felucca</a>.</p>
Free and open source (GPL-3.0), based on <a href="https://github.com/hugelton/Felucca">Felucca</a> by Leo Kuroshita / Hügelton Instruments.</p>
<p align="center">
<a href="https://isod89.github.io/sloop-fm1/"><b>Install from the browser</b></a> ·
<a href="SLOOP.md">Manual</a> ·
<a href="DEMARRAGE-RAPIDE-FR.md">Guide en français</a> ·
<a href="https://isod89.github.io/sloop-fm1/webapp/editor/">Web editor</a> ·
<a href="../../releases">Releases</a> ·
<a href="../../issues">Report a bug</a>
</p>
---
SLOOP turns the FM-1 into a four-track groovebox you play live: three synths and a drum machine with 16 sounds on the white keys, nine synthesis engines, your own samples, a song mode you play with your hands. House, techno, hip-hop, drum & bass, synthwave, lo-fi, ambient, chiptune — it does not pick a style for you. No factory patterns, nothing to load: everything you hear, you play.
SLOOP turns the FM-1 into a four-track groovebox you play live: **three synths and a drum machine** with 16 sounds on the white keys, nine synthesis engines, 68 sounds, 37 drum kits, your own samples, a song mode you play with your hands — and now **USB audio**, a **MIDI keyboard on the jack**, **MIDI clock**, **lights for playing in the dark** and a **full backup**. House, techno, hip-hop, trap, drum & bass, amapiano, synthwave, lo-fi, ambient, chiptune — it does not pick a style for you. No factory patterns, nothing to load: everything you hear, you play.
> **Status:** 2.3. Still a beta: install at your own risk, and please [report](../../issues) what you find. Your projects, presets, samples and settings are kept when you update, and you can go back at any time (see [Going back](#going-back)).
## Contents
1. [What's new in 2.3](#whats-new-in-23)
2. [Screenshots](#screenshots)
3. [Features](#features)
4. [Install](#install)
5. [Your first beat in 60 seconds](#your-first-beat-in-60-seconds)
6. [The controls](#the-controls)
7. [The menu: settings of the FM-1](#the-menu-settings-of-the-fm-1)
8. [MIDI and USB audio](#midi-and-usb-audio)
9. [The web editor](#the-web-editor)
10. [Compatibility](#compatibility)
11. [Troubleshooting](#troubleshooting)
12. [Specifications](#specifications)
13. [Documentation](#documentation)
14. [Building and tests](#building-and-tests)
15. [Contributing](#contributing)
16. [Credits and thanks](#credits-and-thanks)
17. [Licence](#licence)
---
## What's new in 2.3
| | |
| --- | --- |
| **USB audio** | On USB the FM-1 is also an audio input (*Felucca*, 44.1 kHz stereo, no driver): record it in your DAW or Audacity over the same cable. Its level follows the MASTER knob, or stays at a fixed full level (HOME menu → **USB AUDIO**). From Felucca 1.0. |
| **MIDI keyboard on the jack** | The 3.5 mm TRS MIDI IN works: a keyboard or a pad controller through a TRS-to-DIN adapter. Channels 1–3 the synths, 10 the drums, 4–16 the selected track. No note left hanging. |
| **MIDI clock in** | GLO → SYSTEM → **SYNC** = USB or TRS: SLOOP follows a DAW or a drum machine — tempo, START, CONTINUE, STOP — pulse by pulse, with no drift. |
| **Record your way** | The REC screen has three dials: **mode** (*free*: the tempo follows your playing, or *tempo*: the tempo you set), **length** (1, 2 or 4 bars), **start** (your first note, or a one-bar **count-in** after PLAY). |
| **Lights for playing in the dark** | HOME menu: **LIGHTS** (every button glows, LOW / MID / HIGH), **KEYS** (the C keys or every white key), **NOTES** (the notes playing light their keys, by @renebohne). |
| **Backup and restore** | The web editor saves everything on the FM-1 in one file — the music in progress, projects, user presets, samples, settings — and puts it all back. |
| **CHOP, any length** | A recording longer than a sample slot (about 7 s) works: keep the chops you want, shorten them, or **Fit to slot**. |
| **Back to the official firmware** | From the installer page, with a backup first: select M-VAVE's FM-1 V15 file and install it. |
| **Steadier** | Knobs that answer every click; no dropped notes over USB MIDI; one voice fades on overload, never the bass or the lead; keys a millisecond faster; no stuck note after a VOICE change; stricter checks of what is read back from flash. |
The full list, and what came in 2.0, 2.1 and 2.2: [SLOOP.md](SLOOP.md#new-in-23). Release notes: [Releases](../../releases).
## Screenshots
<p align="center"><img src="assets/screens/sloop-2.3-screens.png" alt="SLOOP 2.3 screens on the FM-1" width="760"></p>
<p align="center"><sub>The FM-1's screen in 2.3: the tracks, the REC screen and its count-in, the menu (lights and USB audio), MIDI clock, about.</sub></p>
<p align="center"><img src="assets/screens/screens.png" alt="SLOOP screens on the FM-1" width="760"></p>
<p align="center"><sub>The FM-1's screen: start-up, the four tracks (recording), the drum grid and the acoustic kit, the sounds by kind, the layers (punch-in FX, steps, key and chords, mix, erase), a free take, the FX sends.</sub></p>
<p align="center"><sub>Start-up, the four tracks (recording), the drum grid and the acoustic kit, the sounds by kind, the layers (punch-in FX, steps, key and chords, mix, erase), a free take, the FX sends.</sub></p>
<p align="center"><img src="assets/screens/editor-drums.png" alt="SLOOP web editor: the drum track" width="760"></p>
<p align="center"><sub>The web editor: the drum track as a 16-lane grid, with levels and ratchets.</sub></p>
## New in 2.2
<p align="center"><img src="assets/screens/editor-chop.png" alt="SLOOP web editor: CHOP" width="760"></p>
- **A new drum engine** built like the classic machines (tuned body and pitch drop, click, noise through a resonant filter, drive; softer hits are darker). 32 synthesised kits rebuilt on it — new: PHONK, AMAPIANO, UK GARAGE, deep house — and a sampled **acoustic kit** (CC0 studio recordings). Every kit is level-matched.
- **68 sounds, browsed by kind** (basses, keys, organs, pads, leads, plucks and bells, stabs), all level-matched. 14 new, among them 808 SLIDE, ACID 303, SUPERSAW, M1 PIANO, AFRO KEYS, KALIMBA, DUB CHORD, HOUSE ORGN — and **GRAND PNO**, a real Steinway grand (CC0).
- **Lock a layer:** hold a layer button and tap HOME — it stays open with both hands free (FX on the keys with one hand, FILTER / DUST / DUCK with the other). Any other button lets it go.
- **Stereo chorus and a new stereo reverb** (a feedback delay network: dense, no metallic ring).
- **More reliable:** saves retried until they succeed, the song end gives your loop back, swing never plays a step twice, no click on retriggered voices, the installer refuses a damaged package, no more flicker on the button lights.
Everything in [SLOOP.md](SLOOP.md#new-in-22).
<p align="center"><sub>CHOP: a 20 s recording cut into 16 chops, 8 kept, fitted to the slot.</sub></p>
## Features
- **Hold a button, touch a key.** Every function button is a layer: hold it and the 16 white keys and the four knobs change job, and the screen shows how. Tap it and its pages open.
- **FX**: 16 punch-in effects (loops, stutter, reverse, tape stop, filters, crush…)
- **EDIT**: erase a sound or a note as the loop plays; shift, double or halve the pattern; undo / redo
- **ARP**: note repeat (1/8 to 1/64), locked to the grid
- **SEQ**: step entry, with a level and a ratchet per step
- **SCL**: the key of the song, and one-key chords (triad, 7th, 9th, sus4, power)
- **GLO**: mute, solo, tap tempo, track levels
- **SAVE**: play sections A–D live, record the song as you play
- Keys 1, 5, 9 and 13 glow dimly as landmarks: the rows of the 4 × 4 grid on the screen
- Hold a layer button and tap HOME to lock the layer open: both hands free
- **Drums:** 16 sounds on the white keys, ghost and hard hits (hold OCT− / OCT+), ratchets x1–x4, 37 kits (a sampled acoustic kit in 5 treatments, 32 synthesised: 808, 909, 606, house, deep house, techno, minimal, electro, trap, drill, phonk, UK garage, jungle, dubstep, reggaeton, amapiano, afrobeat, latin, disco, synthwave, chiptune, industrial, hyperpop, ambient, jazz brushes…), all level-matched.
- **Synths:** 9 engines — analog, 4-op FM, phase distortion, three-oscillator, tonewheel organ, formant voice, granular, lo-fi chip, sampler — with envelopes, LFO, arpeggiator, glide, drive, slicer and sends to a stereo chorus, a tempo delay and a stereo reverb. 68 presets to start from, browsed by kind and level-matched (sliding 808s, acid, reese and FM basses, a Steinway grand, Rhodes, house and afro keys, organs, supersaw, plucks and bells, stabs and dub chords, pads, talkbox, scratches) and 32 slots for your own.
- **Recording with no click:** a free take sets the loop length and the tempo from your playing; REC records at once while playing; notes land where you heard them (latency-compensated).
- **Groove:** MPC-style swing (50–75 %), a sample-accurate clock (no drift at any tempo), polymeters.
- **Master:** DUST (old sampler + vinyl), DUCK (the kick pumps the synths), a DJ filter.
- **Memory:** undo / redo, autosave of the working project, 4 projects, 32 user presets.
- **Songs, live:** hold SAVE and press a key — sections A–D start on the next bar, always in time; SONG REC writes the order you play into the song, PLAY in song mode plays it back.
- **Your own samples:** three user slots; the web editor chops a recording into 16 pieces (tap along while it plays) and uploads them.
- **Web editor:** every parameter, the drum track as a 16-lane grid, the mixer, a preset library, sample upload. Live sync with the device.
### Play it live: hold a button, touch a key
Every function button is a **layer**: hold it and the 16 white keys and the four knobs change job, and the screen shows how. Tap it and its pages open. Hold a layer button and tap HOME to **lock** it open, both hands free.
| Hold | The white keys | KNOB 1 · 2 · 3 · 4 |
| --- | --- | --- |
| **FX** — punch | 16 punch-in effects on the whole mix: loops 1/4–1/32, stutter, reverse, tape stop, half speed, filter sweeps, phone, bit crush, alias, gate, echo, tape wobble | FILTER · DUST · DUCK |
| **EDIT** — erase | erase a sound or a note as the loop plays (stopped: from the whole pattern) | SHIFT · LENGTH ×2 / ½ · TRANSPOSE |
| **ARP** — roll | note repeat on the grid, recorded as ratchets | RATE (1/8 … 1/64) |
| **SEQ** — steps | the 16 steps of the page, with a level and a ratchet per step | SOUND / NOTE · DIV · SWING · LENGTH |
| **SCL** — key | the key of the song | CHORD · SCALE · KEYS · TRANSPOSE |
| **GLO** — mix | 1–4 mute, 5–8 solo, 16 tap tempo | the levels of tracks 1–4 |
| **SAVE** — song | 1–4 play sections A–D, 5–8 save the loop into them, 13 loop / song, 14 record the song, 16 the chain | — |
Keys 1, 5, 9 and 13 glow dimly while a layer is held: the first key of each row of the 4 × 4 grid on the screen. **EDIT + OCT− / OCT+** is undo / redo.
### Drums
- **16 sounds on the white keys**, kick to cowbell; a black key doubles the white key on its left (fast rolls with two fingers).
- **Ghost and hard hits:** hold OCT− / OCT+ while you play. Every hit keeps its level (GHOST, SOFT, NORM, HARD) and a **ratchet** (x1–x4).
- **37 kits**, all level-matched: a sampled acoustic kit in 5 treatments (CC0 studio recordings) and 32 synthesised kits — 808, 909, 606, 80s, vintage, trap, drill, boom bap, lo-fi, phonk, house, deep house, techno, minimal, electro, disco, UK garage, jungle, dubstep, reggaeton, amapiano, afrobeat, latin, tribal, synthwave, chiptune, arcade, glitch, industrial, hyperpop, ambient, jazz brushes. Each synthesised sound is built like on the classic machines; softer hits are darker as well as quieter.
- **Grid and kit pages** on the FM-1 (EDIT or SEQ on the drum track), and a 16-lane grid in the web editor.
### Synths and sounds
- **Nine engines:** analog, 4-op FM, phase distortion, three-oscillator, tonewheel organ, formant voice, granular, lo-fi chip, sampler.
- **68 sounds, browsed by kind** — basses (sliding 808s, acid 303, reese, FM), keys (Rhodes, a real Steinway grand, house and afro keys), organs, pads, leads (supersaw, talkbox), plucks and bells, stabs and dub chords — every one level-matched. **32 slots** for your own presets.
- Envelopes (with a pitch punch for 808s), LFO, arpeggiator, glide and voice modes (POLY, MONO, LEGATO, UNISON), per-track drive and slicer, sends to a **stereo chorus**, a **tempo delay** and a **stereo reverb**.
- **Key and chords (SCL):** the key of the song for all synths, 16 scales, one-key chords (triad, 7th, 9th, sus4, power), keys snapped to the scale or the scale on the white keys.
### Recording and the sequencer
- **Records as you play, no click needed:** while it plays, REC records at once and every pass is added on top (overdub). Notes land where you heard them: the ~12 ms of the keys are taken back.
- **The REC screen (2.3):** **mode** *free* — no tempo, no grid: play, press REC on the "1" after your last bar, and the loop's length sets the tempo — or *tempo* — record at the tempo you set; **length** 1, 2 or 4 bars; **start** on your first note, or after a one-bar **count-in**.
- **Hold REC ~2 s** to clear a track; **undo / redo** brings it back.
- **64 steps per track**, each track with its own length and division (polymeters stay in phase); chords up to 4 notes a step, ties, slide; **MPC swing** 50–75 %; one sample-accurate clock for everything: no drift at any tempo.
- The PLAY light flashes on every beat (a visual metronome); an audible click is in GLO → GLOBAL → CLICK and is never recorded.
### Songs
Save up to four sections **A–D** (SAVE + keys 5–8), play them live on the next bar (SAVE + keys 1–4), and **record the song as you play it** (SAVE + key 14). In song mode PLAY plays the whole chain. The SONG screen edits it by hand.
### Effects and master
- **16 punch-in effects** (FX + a key), locked to the tempo.
- **Master:** **DUST** (an old sampler and a record: bits, rate, crackle), **DUCK** (the kick pumps the synths), **FILT** (a DJ filter: low-pass ← off → high-pass), and an output limiter.
### Your own samples
- **Three slots** (USR1–USR3) of about 7.4 s each, played by a synth track; up to 16 WAV files per slot, each on its own key.
- **CHOP** in the web editor: open or drop a recording (WAV, MP3, AIFF…) of **any length**, tap along while it plays (each tap snaps to its hit), or find the hits, a tempo grid, equal parts; keep the chops you want, shorten them or **Fit to slot**; send them to a slot, one per key, or download them as WAV files.
### MIDI
- **USB MIDI** in and out, class compliant.
- **TRS MIDI IN** (the 3.5 mm jack, 2.3) for a keyboard or a pad controller.
- **MIDI clock in** (USB or TRS): tempo, START, CONTINUE, STOP.
- Details: [MIDI and USB audio](#midi-and-usb-audio).
### USB audio (2.3)
The FM-1 is also a **USB audio input**: record its master output on a computer, no driver, over the same cable as MIDI and the editor. Details: [USB audio](#usb-audio-record-the-fm-1-on-a-computer).
### Lights for playing in the dark (2.3)
Every button can glow so its label is readable on a black FM-1; the C keys or every white key can glow too; the notes playing can light their keys. Details: [The menu](#the-menu-settings-of-the-fm-1).
### Memory and safety
- **Autosave:** stop and leave it 2.5 s, your work is kept; at power-on SLOOP comes back exactly as you left it.
- **4 projects**, **32 user presets**, **undo / redo**.
- **Full backup and restore** from the web editor (2.3).
- **Safe updates:** the installer checks the package (SHA-256) before writing it, the update loader checks it again (CRC) before starting it; an interrupted install finishes when you press Install again; **USB rescue** (OCT− at power-on).
## Install
**From the browser:** open **[the SLOOP installer](https://isod89.github.io/sloop-fm1/)** in **Chrome or Edge**, connect the FM-1 by USB (a data cable, no hub), press **INSTALL** and wait for *Done*. Nothing to download or compile. The [web editor](https://isod89.github.io/sloop-fm1/webapp/editor/) works the same way.
### From the browser (recommended)
Other ways: the `.fwsc` of each [release](../../releases) with `python tools/fm1_install.py sloop-2.2.fwsc` (needs `pip install mido python-rtmidi`), or build it yourself and run `INSTALL-SLOOP.bat` (Windows).
1. Open **[the SLOOP installer](https://isod89.github.io/sloop-fm1/)** in **Chrome or Edge** on a computer.
2. Connect the FM-1 by USB — a **data** cable, directly (no hub).
3. Press **INSTALL**, allow MIDI access, and wait for *Done*. The FM-1 restarts on the SLOOP logo.
Going back: M-VAVE's own updater (M-UPGRADE) and the official FM-1 firmware. If an install is cut off, the FM-1 stays in update mode: press Install again and it finishes.
Nothing to download or compile. Your projects, user presets, samples and settings are kept. After an install, **unplug and plug the FM-1 back in** once so the computer finds its USB audio input.
> Custom firmware is installed at your own risk. If an FM-1 no longer starts, recovery needs [FM-1-transporter](https://github.com/kurogedelic/FM-1-transporter).
### Other ways
- **Python:** the `.fwsc` of a [release](../../releases) with `python tools/fm1_install.py sloop-2.3.fwsc` (needs `pip install mido python-rtmidi`).
- **Build it yourself:** see [Building and tests](#building-and-tests); on Windows, `INSTALL-SLOOP.bat` builds SLOOP and opens the installer locally.
### Going back
- **To an earlier SLOOP:** install the `.fwsc` of its [release](../../releases) (for example [2.2](../../releases/tag/v2.2)). It keeps your work and simply ignores the 2.3 settings.
- **To the official firmware:** on the installer page, open **Return to the official firmware (V15)**. Save a backup with the editor first, download FM-1 V15 from m-vave.com and select its `FM-1.fwsc` — only that exact file is accepted. M-VAVE's updater, M-UPGRADE, works too. To come back, install SLOOP again and restore your backup.
### Rescue
- **The FM-1 no longer starts SLOOP:** hold **OCT−** alone while switching it on (*SLOOP USB RESCUE*), then install again.
- **An install was cut off:** the FM-1 stays in update mode; press INSTALL again and it finishes.
- If an FM-1 no longer starts at all, recovery needs [FM-1-transporter](https://github.com/kurogedelic/FM-1-transporter).
> Custom firmware is installed at your own risk. No warranty.
## Your first beat in 60 seconds
1. **ALGORITHM** to track **4** (orange, drums). The white keys are 16 drum sounds; **PRESETS** picks a kit (try *808* or *BOOMBAP*).
2. Press **REC** and play a beat freely, at your own tempo. Hold **OCT−** while you hit for ghost notes, **OCT+** for hard ones.
3. **Press REC on the "1" after your last bar.** The loop closes, its length sets the tempo, the hits snap to the grid and it plays at once. (Prefer a set tempo, or a count-in? Turn KNOB 1 and KNOB 3 on the REC screen before you start.)
4. **REC** again while it plays: you record on top. Hold **ARP** and hold the hat key for a hat roll.
5. **ALGORITHM** to track **1**, **REC**, play a bass line. Hold **SCL** and press the key of your song; on track 2, hold SCL and turn **KNOB 1** to *7TH*: every white key now plays a chord.
6. Hold **FX** and press a white key for a punch-in effect; still holding FX, turn **KNOB 2** for DUST, **KNOB 3** for DUCK.
7. A mistake? Hold **EDIT** and press **OCT−**: undo.
## The controls
| Control | What it does |
| --- | --- |
| **MASTER** | volume (and the USB audio level, if USB AUDIO is on MASTER) |
| **SELECT** | tempo, on every page, even inside a layer |
| **ALGORITHM** | the selected track: 1 · 2 · 3 (synths) · 4 (drums) |
| **PRESETS** | the selected track's sound, or the drum kit |
| **KNOB 1–4** | what the four dials at the bottom of the screen show, each in its colour |
| **OCT− / OCT+** | octave (both: back to 0) · on the drum track, held: ghost / hard hits |
| **FX · SCL · ENV · LFO · EDIT · GLO** (top row) | tap: their pages · hold FX, SCL, EDIT, GLO: a layer. **SCL** is the second button of the top row, between FX and ENV |
| **HOME** | the TRACKS screen · hold: the menu · tapped while a layer is held: lock it |
| **SAVE** | on TRACKS: the SONG screen · elsewhere: the SAVE pages · hold: the song layer |
| **ARP · SEQ** | tap: their pages · hold: note repeat · steps |
| **PLAY** | start / stop all four tracks; its light flashes on every beat |
| **REC** | playing: record now / stop · stopped: arm (the REC screen) · hold: clear the track |
| **EDIT + OCT− / OCT+** | undo / redo |
Colours: **blue** track 1 and KNOB 1, **green** 2, **yellow** 3, **orange** 4 (drums). White is what you touch; red is recording.
## The menu: settings of the FM-1
Hold **HOME**. **PRESETS** moves, **KNOB 1** sets, **OCT+** steps round, **OCT−** closes. These are settings of the FM-1, not of a project: loading a project or NEW PROJECT does not change them, and the backup keeps them.
| Item | Choices | What it does |
| --- | --- | --- |
| **COLOR** | 5 palettes | the screen's colours |
| **LOWCUT** | OFF / ON | a low cut for the small built-in speaker |
| **ZOOM** | OFF / ON | a large readout of the value you turn |
| **LIGHTS** | OFF / LOW / MID / HIGH | every button glows at that level; what is active stays at full light |
| **KEYS** | OFF / C KEYS / WHITE KEYS | the C keys, or every white key, glow too |
| **NOTES** | OFF / ON | the notes playing on a synth track light their keys, on every page and in every layer |
| **USB AUDIO** | MASTER / FULL | the level of the USB audio input: follows the MASTER knob, or a fixed full level |
| **HARDWARE CALIBRATION** | | the panel table, if a key or a knob answers wrongly |
| **ABOUT** | | the version (*SLOOP 2.3*) and its build date, the credits |
Two more settings of the FM-1 live elsewhere: **SYNC** (GLO → SYSTEM: INT, USB or TRS) and the REC screen's **mode** and **start**.
## MIDI and USB audio
### MIDI in
SLOOP takes MIDI from two places at once:
- **The MIDI IN jack** (3.5 mm TRS): a keyboard or a pad controller with a MIDI output, through a **TRS-to-DIN MIDI adapter**. If nothing plays, try the other adapter type (A / B).
- **USB**, from a computer or a phone (a DAW, a MIDI routing app) or a USB MIDI host box.
| MIDI channel | Plays |
| --- | --- |
| 1, 2, 3 | synth tracks 1, 2, 3 |
| 10 | the drum track (the nearest of its 16 sounds; GLO → DRUMS → CH changes the channel) |
| 4–16 | the selected track: set your keyboard to channel 4 and it follows ALGORITHM |
A USB keyboard plugged **straight into the FM-1** cannot work: both are USB devices, and a USB link needs a host (a computer, a phone, or a USB MIDI host box). Bluetooth MIDI is not supported: SLOOP, like Felucca, never switches the radio on.
### MIDI clock in
GLO → SYSTEM → **SYNC** = **USB** or **TRS** (INT: SLOOP's own tempo). START plays from the top, CONTINUE carries on, STOP stops; the tempo follows the master and the steps follow its 24 pulses a beat, so SLOOP never drifts. When the clock stops for half a second, PLAY on the FM-1 plays at its own tempo again.
### USB audio: record the FM-1 on a computer
On USB the FM-1 is also an **audio input named "Felucca"**: 44.1 kHz, 16-bit stereo, class compliant — no driver on Windows, macOS or Linux. Choose it in your DAW or in Audacity and record: you get the master output, exactly what the headphones play (after DUST, DUCK and FILT). MIDI, the web editor and the installer keep working on the same cable.
- **The level:** HOME menu → **USB AUDIO**. **MASTER** (default): the recording follows the MASTER knob, as the headphones do — keep MASTER well up while you record. **FULL**: a fixed level, as with MASTER all the way up, kept from clipping by the limiter; MASTER then only sets the headphones (the right choice for an interface with no level control).
- **The first time** (and after an install), the computer sets the FM-1 up again as a MIDI + audio device: unplug and plug it back in if the input does not show. The MIDI port keeps its name.
- The audio input comes from Felucca 1.0.
## The web editor
Open it from the [installer page](https://isod89.github.io/sloop-fm1/) (or the [editor link](https://isod89.github.io/sloop-fm1/webapp/editor/)) in Chrome or Edge, with the FM-1 on USB, and press **Connect**. It follows the device live: turn a knob on the FM-1 and the editor moves.
- **Sound** — every parameter of the selected track, the engines and the presets.
- **Sequencer** — the steps; on the drum track a grid of 16 sounds × the steps, with levels and ratchets, and the kit.
- **Tracks** — the four channel strips.
- **Library** — your user presets and preset files.
- **Samples** — the three user slots, files and **CHOP**.
- **Projects** — the four projects, and **Backup**: *Save a backup* writes everything on the FM-1 to one file; *Restore from a file* puts it all back (stop playback first).
- **Settings** — global, master (DUST, DUCK, FILT, ROLL), drums.
<p align="center"><img src="assets/screens/editor-backup.png" alt="SLOOP web editor: projects and backup" width="560"></p>
The protocol is documented in [web/EDITOR_PROTOCOL.md](web/EDITOR_PROTOCOL.md).
## Compatibility
| | |
| --- | --- |
| Device | M-VAVE FM-1 (the official firmware can be put back at any time) |
| Installer and editor | **Chrome or Edge** on Windows, macOS or Linux (they use Web MIDI with SysEx) |
| Cable | a USB **data** cable, plugged directly (no hub) |
| USB audio | any computer that takes a class-compliant USB audio input (no driver) |
| MIDI IN jack | 3.5 mm TRS, through a TRS-to-DIN MIDI adapter (type A or B) |
| Not supported | Bluetooth MIDI; a USB keyboard plugged straight into the FM-1 |
## Troubleshooting
**The installer or the editor does not find the FM-1.** Use Chrome or Edge, a data cable, no hub, and allow MIDI access. Close every other app or tab that uses MIDI (a DAW, M-UPGRADE, another editor tab), then reload the page.
**An install stopped half-way.** The FM-1 waits in update mode: press INSTALL again. If SLOOP no longer starts, hold **OCT−** alone while switching on (*SLOOP USB RESCUE*) and install again.
**The black keys make no sound on a synth track.** That track plays chords or the scale on the white keys: hold **SCL** (between FX and ENV) and set **KNOB 1 CHORD** to OFF and **KNOB 3 KEYS** to OFF. The drum track always uses the black keys.
**Nothing plays from the MIDI IN jack.** Try the other adapter type (A / B); check the keyboard's channel (1–3 synths, 10 drums, 4–16 the selected track).
**The USB audio input does not show.** Unplug the FM-1 and plug it back in (after an install the computer must find it again). In Audacity: Transport → Rescan Audio Devices. On Windows: Sound settings → Recording → show disabled devices.
**The USB recording is too quiet, or follows the volume knob.** Set HOME menu → **USB AUDIO** to **FULL**, or turn MASTER up.
**Recorded notes move to the grid.** SLOOP quantises what you record to the steps of the track (its **DIV**: 1/4 … 1/32, triplets). For finer timing, set DIV to 1/32; for groove, use SWING.
**Notes fade out on a dense part.** The processor is at its limit: SLOOP fades one voice at a time (never the bass or the lead) rather than glitching. Fewer held notes or a lighter engine help.
**The lights or SYNC went back to OFF / INT.** You went back to an earlier SLOOP, which does not keep them; set them again in 2.3.
Something else? [Open an issue](../../issues): what you did, what you expected, what happened, and the version shown in HOME menu → ABOUT.
## Specifications
| | |
| --- | --- |
| Tracks | 3 synth parts (8 voices shared) + drums (16 sounds, 6 voices) |
| Sounds | 68 presets on 9 engines (browsed by kind, level-matched), 8 sampled sets (CC0), 3 slots for your own samples, 32 user presets |
| Drum kits | 37 (5 sampled, 32 synthesised, 16 sounds each), level-matched |
| Sequencer | 64 steps per track, own length and division each; chords with a level and ratchet per note; drums with a level and ratchet per sound; ties, slide; MPC swing 50–75 %; one sample-accurate clock (no drift) |
| Recording | live, quantised as heard (latency-compensated), overdub; free take (the tempo follows you) or the tempo set; start on the first note or a one-bar count-in; 1, 2 or 4 bars |
| Performance | layers: punch-in FX, erase, note repeat, step entry, key / chords, mute / solo / tap tempo, song sections |
| Effects | 16 punch-in effects; master DUST, DUCK, DJ filter, limiter; per track drive, slicer, sends to a stereo chorus, a tempo delay and a stereo reverb |
| Memory | autosave, undo / redo, 4 projects, 32 user presets, song of 4 sections × 16 steps × 1–64 bars, full backup / restore (editor) |
| Audio | 44.1 kHz, fixed-point DSP; USB audio input (the master output, 16-bit stereo, class compliant) |
| MIDI | USB class-compliant in / out; TRS MIDI IN (3.5 mm); MIDI clock in (USB or TRS) |
| Lights | button backlight (3 levels), C keys / white keys, played notes |
| Update | over USB from the browser (SHA-256 and CRC checked), USB rescue, return to the official V15 |
## Documentation
- [SLOOP.md](SLOOP.md) — the manual
- [SLOOP.md](SLOOP.md) — the full manual (every page, layer, sound and kit)
- [DEMARRAGE-RAPIDE-FR.md](DEMARRAGE-RAPIDE-FR.md) — guide de démarrage en français
- [BUILDING.md](BUILDING.md) — building and testing
- [BUILDING.md](BUILDING.md) — building, build options and tests
- [web/EDITOR_PROTOCOL.md](web/EDITOR_PROTOCOL.md) — the editor's SysEx protocol
- [LICENSING.md](LICENSING.md) — the licences of the code and the assets
## Building
## Building and tests
See [BUILDING.md](BUILDING.md). In short: the JieLi toolchain and three files of the AC79 SDK, then `./build.sh` (Linux / macOS) or `INSTALL-SLOOP.bat` (Windows with WSL). `tests/run_tests.sh` runs the host test suite (audio renders, sequencer timing, UI, storage, update loader, web pages).
See [BUILDING.md](BUILDING.md). In short: the JieLi toolchain and three files of the AC79 SDK, then `./build.sh` (Linux / macOS) or `INSTALL-SLOOP.bat` (Windows with WSL), which builds the firmware and serves the installer and the editor on `http://localhost:8766`.
## Credits
`tests/run_tests.sh` runs the host test suite with no hardware: audio renders against golden hashes, CPU budgets, the sequencer's timing (no drift, swing, ratchets, rolls, the REC modes and the count-in, MIDI clock), the UI pages and layers, the knobs, flash storage, the update loader, MIDI and USB audio, and the web pages (editor, backup, CHOP, installer).
SLOOP is a fork of **[Felucca](https://github.com/hugelton/Felucca)** by Leo Kuroshita (@kurogedelic), Hügelton Instruments: the engines, the sequencer, the editor and the installer come from there. Font: Terminus (SIL OFL 1.1). Samples: Versilian Studios VSCO-2 CE and VCSL, Sonic Pi (all CC0). PHASE engine after CrispyZebra; VOICE after klattsch. Icons: Fukiai.
## Contributing
- **Bugs and ideas:** [open an issue](../../issues) — what you did, what you expected, what happened, and the version in HOME menu → ABOUT.
- **Pull requests** are welcome. Keep the style of the code around your change, add a host test when you can, and make sure `tests/run_tests.sh` passes. Contributions are credited in the release notes and the manual.
- By contributing you agree that your code is released under GPL-3.0, like the rest of SLOOP.
## Credits and thanks
- **[Felucca](https://github.com/hugelton/Felucca)** by **Leo Kuroshita** (@kurogedelic) / **Hügelton Instruments** — the engines, the sequencer, the editor, the installer, and in 2.3 the USB audio input, the MIDI clock, the knob reading and many fixes (Felucca 1.0 / 1.0.1). Thank you.
- **@renebohne** — the played-note key lights (pull request #11).
- **ChanceTheMaker** and **keremimo** — the TRS MIDI input fix (Felucca Salt) and contributions to the MIDI clock.
- **Everyone who installed SLOOP, made music with it, commented, reported a bug or asked for a feature** — most of 2.3 comes from your messages.
- Samples: Versilian Studios VSCO-2 CE and VCSL, Sonic Pi (all CC0). Font: Terminus (SIL OFL 1.1). Icons: Fukiai (MIT, Hügelton Instruments). PHASE engine after CrispyZebra (GPL); VOICE after klattsch (MIT).
- Interface ideas after teenage engineering's pocket operators and EP-133, Elektron's step entry and Akai's MPC (swing, note repeat, erase).
## Licence
Code: GPL-3.0-only (see [LICENSE](LICENSE) and [LICENSING.md](LICENSING.md) for the assets). No warranty. M-VAVE and FM-1 are trademarks of their owners; SLOOP is not affiliated with M-VAVE. Drum kit names describe styles, not products.
Code: GPL-3.0-only (see [LICENSE](LICENSE), and [LICENSING.md](LICENSING.md) for the assets). No warranty. M-VAVE and FM-1 are trademarks of their owners; SLOOP is not affiliated with M-VAVE, teenage engineering, Elektron or Akai. Drum kit names describe styles, not products.
+82 -14
View File
@@ -1,12 +1,25 @@
<p align="center"><img src="assets/logo/sloop-logo.png" alt="SLOOP" width="480"></p>
# SLOOP 2.2
# SLOOP 2.3
**A live groovebox firmware for the M-VAVE FM-1 — for any style.** Four tracks — three synths and a drum machine with 16 sounds on the white keys — nine synthesis engines, 68 sounds, 37 drum kits (808, 909, trap, phonk, house, techno, UK garage, jungle, amapiano, reggaeton, synthwave, chiptune, ambient, jazz…), your own samples, ghost notes and ratchets, note repeat, one-key chords, 16 punch-in effects, a vinyl / sidechain / DJ-filter master, and a teenage-engineering-style screen that always shows what your hands can do next. No factory patterns, nothing to load: everything you hear, you play.
SLOOP is free and open source (GPL-3.0), based on [Felucca](https://github.com/hugelton/Felucca) by Leo Kuroshita / Hügelton Instruments.
> **Status:** 2.2, running on the FM-1. Still a beta: install at your own risk, and please report what you find (GitHub issues).
> **Status:** 2.3, running on the FM-1. Still a beta: install at your own risk, and please report what you find (GitHub issues).
### New in 2.3
- **A MIDI keyboard on the MIDI IN jack.** The FM-1's 3.5 mm TRS MIDI input works: channels 1–3 play the synth tracks, 10 the drums, 4–16 the selected track. The input reads its buffer by content, so no note is left hanging (fix from Felucca [Salt], by ChanceTheMaker and keremimo). See [MIDI keyboards](#midi-keyboards).
- **MIDI clock in.** GLO → SYSTEM → **SYNC**: USB or TRS, a setting of the FM-1 that stays when you load a project. SLOOP follows the master's tempo, START, CONTINUE and STOP, pulse by pulse, so it never drifts (after Felucca 1.0, from contributions by ChanceTheMaker and keremimo). See [MIDI keyboards](#midi-keyboards).
- **USB audio: record the FM-1 on a computer.** On USB the FM-1 is also an audio input (*Felucca*, 44.1 kHz stereo, no driver): record its master output in your DAW or Audacity, MIDI and the editor still working on the same cable (after Felucca 1.0). HOME menu → **USB AUDIO**: the level follows the MASTER knob, or **FULL**, a fixed full level. See [USB audio](#usb-audio-record-on-a-computer).
- **Choose how REC records.** On the REC screen: KNOB 1 **mode** — *free* (the free take: the tempo follows you) or *tempo* (record at the tempo you set) — KNOB 2 the **length** (1, 2 or 4 bars), KNOB 3 the **start** — your first note, or a one-bar **count-in** after PLAY. See [Recording](#recording).
- **Lights for playing in the dark.** Hold HOME → **LIGHTS**: every button glows (LOW, MID, HIGH), so the labels are readable on a black FM-1; the active ones stay at full light. **KEYS**: the C keys, or every white key, glow too. **NOTES**: the notes playing light their keys, on every page and in every layer (by @renebohne). The glow is a short pulse on every scan, as in Felucca 1.0.1: no flicker, and the dim marks read as dim. See [Lights](#lights).
- **Backup and restore.** The editor saves everything on the FM-1 in one file — the music you are working on, the projects, the user presets, the samples, the settings — and puts it all back. See [The web editor](#the-web-editor).
- **CHOP: recordings of any length.** A recording longer than a slot (about 7 s) is no longer a dead end: tick the chops you keep, untick the rest, shorten any chop (its length slider, or drag the handle at the bottom of the wave), or press **Fit to slot** to shorten the longest ones just enough. Only the kept chops go to the slot or the WAVs, on consecutive keys. See [The web editor](#the-web-editor).
- **Back to the official firmware from the installer page**, a backup first: select M-VAVE's FM-1 V15 file and install it (as in Felucca 1.0).
- **Steadier.** The knobs answer every click: no more dead moments, double clicks or jumps. A note-off sent from a computer is never dropped any more when a lot of MIDI arrives at once (a hanging note), and a malformed MIDI message is ignored. When the processor is overloaded, SLOOP fades out one voice at a time, after two late halves in a row and never the bass or the lead, instead of cutting the oldest note. Keys play about a millisecond sooner. A key let go just after a change of VOICE (POLY, MONO…) no longer leaves its note stuck. The settings, projects and presets are checked more strictly when they are read back from flash. (All after Felucca 1.0.)
- The installer page shows the right numbers (68 sounds, 37 kits).
### New in 2.2
@@ -54,8 +67,11 @@ SLOOP is free and open source (GPL-3.0), based on [Felucca](https://github.com/h
15. [Song mode](#song-mode)
16. [The web editor](#the-web-editor)
17. [Sound design pages](#sound-design-pages)
18. [Specifications](#specifications)
19. [Rescue, going back, credits](#rescue-going-back-credits)
18. [MIDI keyboards](#midi-keyboards)
19. [USB audio: record on a computer](#usb-audio-record-on-a-computer)
20. [Lights](#lights)
21. [Specifications](#specifications)
22. [Rescue, going back, credits](#rescue-going-back-credits)
---
@@ -119,7 +135,7 @@ Other controls:
| **PRESETS** | the selected track's sound, or the drum kit |
| **SELECT** | tempo (always, even inside a layer) |
| **OCT− / OCT+** | synth tracks: octave (both: back to 0) · drum track, held: ghost / hard hits |
| **HOME** | the TRACKS screen · hold: menu (colour, low cut, zoom, calibration, about) · tapped while a layer is held: lock it open |
| **HOME** | the TRACKS screen · hold: menu (colour, low cut, zoom, lights, keys, notes, USB audio, calibration, about) · tapped while a layer is held: lock it open |
| **ENV / LFO** | their pages |
## The drum track
@@ -143,7 +159,17 @@ SLOOP records live and layers every pass on top of the last (overdub). Notes go
| --- | --- | --- |
| **Playing** | records the selected track **at once** | REC again stops recording, the loop plays on |
| **Stopped, project with notes** | arms (*rec ready*, the REC light blinks) | **your first note starts the loop and is step 1**; PLAY starts it too |
| **Stopped, empty project** | arms (*rec ready* · *play freely*) | a **free take**: see below |
| **Stopped, empty project** | arms (*rec ready* · *play freely*) | a **free take** (see below), or MODE *tempo*: as with notes |
**The REC screen sets how it records** (armed, before the first note), with the knobs:
| Knob | Dial | Choices |
| --- | --- | --- |
| KNOB 1 | **mode** (empty project only) | **free**: a free take, the tempo follows you · **tempo**: record at the tempo set (SELECT) |
| KNOB 2 | **length** | the loop of the selected track: **1, 2 or 4 bars** |
| KNOB 3 | **start** | **note**: your first note starts the loop · **count**: press **PLAY**, one bar of clicks (4, 3, 2, 1 on the screen), then the loop starts recording; notes played before only sound |
MODE and START are settings of the FM-1: they stay as you left them. In a project with notes there is no MODE: it always records at the tempo set (a free take would change the tempo of what is already there). During the count-in, REC cancels it and PLAY goes back to *rec ready*.
**Free take — the loop follows you.** On an empty project there is no tempo yet, so you set it by playing:
@@ -235,7 +261,7 @@ Hold **FX**, then hold a white key — the 16 white keys from the lowest F to th
- **TRACKS** (HOME) — the performance view: tempo, swing, transport, bar.beat; each track with its sound, its steps, the playhead, mute / solo / rec badges and its level. Dials: *swing · level · steps · pan* (KNOB 2 on a muted track unmutes it).
- **Layers** — while a layer button is held: 16 tiles (the white keys) and the knobs' dials, in the layer's colour.
- **DRUMS** (EDIT or SEQ tapped on TRACKS with the drum track) — **grid**: the 16 sounds × 16 steps, levels as shades, ratchets as notches; dials *sound · step · hit · level*. **kit**: 16 pads that flash on every hit; dials *kit · level · reverb · pan*. EDIT / SEQ tapped switches grid ↔ kit.
- **REC READY / FREE TAKE** — while REC is armed, and during a free take: the seconds and the loop it makes.
- **REC READY / FREE TAKE** — while REC is armed: the tracks, then **mode**, **length** and **start** on KNOB 1–3 (4-3-2-1 during a count-in); during a free take: the seconds and the loop it makes.
- **Holds** — the ring of REC (clear) while held.
- **SONG** — the section chain.
- **Sound pages** (ENV, LFO, FX, SCL, EDIT, ARP, SEQ, GLO, SAVE) — the full synth, colour-coded.
@@ -290,7 +316,7 @@ The kit is saved with projects and song sections. MIDI notes in on the drum chan
Three slots of about 7.4 s each hold your own sounds, played by a synth track: engine **SAMPLE**, **SET** = USR1 / USR2 / USR3. Load them from the web editor, tab **Samples**:
- **Files:** up to 16 WAV per slot (any rate, mono or stereo). The note each one plays at its own speed is in its name (`KEYS_C4.wav`, C4 = 60).
- **CHOP:** open or drop a recording (WAV, MP3, AIFF…) and cut it into up to 16 chops, one per key — live with **TAP** (or the space bar) while it plays (*snap to the hit* puts each tap on its attack), **Find hits**, **Grid** or **Equal parts**; then **Send to USR1/2/3**, or **Download WAVs**.
- **CHOP:** open or drop a recording (WAV, MP3, AIFF…) and cut it into up to 16 chops, one per key — live with **TAP** (or the space bar) while it plays (*snap to the hit* puts each tap on its attack), **Find hits**, **Grid** or **Equal parts**; then keep the chops you want (the box on each chop, **Keep all**, **Keep none**, or **K**), set a chop's length (the slider under the chops, or drag the handle at the bottom of the wave; **Up to the next marker** undoes it) or press **Fit to slot** when they are too long together — a recording of any length works, the slot takes about 7.4 s of chops — then **Send to USR1/2/3**, or **Download WAVs** (the kept chops only, each with its own number).
## Song mode
@@ -311,13 +337,55 @@ Open it from the installer page, or with **`OPEN-EDITOR.bat`** (`http://localhos
- **Sequencer** — the pattern settings and the steps. On the **drum track**: a grid of the 16 sounds × the steps, with the **kit**. Choose a **level** (GHOST, SOFT, NORM, HARD) and a **roll** (x1–x4), then click: a hit; click it again (same level and roll): cleared; Shift+click: one level louder.
- **Tracks** — the four channel strips (level, pan, mute; SOLO and REC shown as on the device).
- **Library**, **Samples** (with CHOP), **Projects**, **Settings** (GLOBAL, **MASTER**: DUST, DUCK, FILT, ROLL; DRUMS).
- **Backup** (Projects tab): **Save a backup** writes everything on the FM-1 to one file (SLOOP-backup-DATE.json): the music you are working on, the projects 1–4 (the song sections A–D), the 32 user presets, the samples USR1–3 and the settings (colours, calibration, the song order, the lights, SYNC). **Restore from a file** puts it all back — what is on the FM-1 is replaced. A damaged file is refused before anything is written, every object is checked as a load checks it, and each one is written as a save writes it (a cut-off restore never leaves half an object). Stop the song (PLAY) before restoring.
The protocol is documented in [web/EDITOR_PROTOCOL.md](web/EDITOR_PROTOCOL.md) (v5).
The protocol is documented in [web/EDITOR_PROTOCOL.md](web/EDITOR_PROTOCOL.md) (v6).
## Sound design pages
The full Felucca engine is underneath: nine synthesis engines (analog, 4-op FM, phase distortion, lo-fi chip, sampler, formant voice, three-oscillator, tonewheel organ, granular), envelopes (with a pitch punch for the 808s), LFO, arpeggiator, scales and chords, glide and voice modes, per-track drive and slicer, chorus / delay / reverb sends (a stereo chorus, a tempo delay, a stereo reverb built as a feedback delay network: dense, no metallic ring), 32 user presets, 4 projects.
## MIDI keyboards
SLOOP takes MIDI from two places at once:
- **The MIDI IN jack** (3.5 mm TRS, on the FM-1): a keyboard or a pad controller with a MIDI output, through a TRS-to-DIN MIDI adapter. If nothing plays, try the other type of adapter (type A / type B).
- **USB**, from a computer or a phone (a DAW, a MIDI routing app) or a USB MIDI host box. A USB keyboard plugged straight into the FM-1 cannot work: both are USB devices, and a USB link needs a host.
| MIDI channel | Plays |
| --- | --- |
| 1, 2, 3 | synth tracks 1, 2, 3 |
| 10 | the drum track (the nearest of its 16 sounds; GLO → DRUMS → CH changes the channel) |
| 4–16 | the selected track: set your keyboard to channel 4 and it follows ALGORITHM |
**MIDI clock in:** GLO → SYSTEM → **SYNC** = **USB** or **TRS** (INT: SLOOP's own tempo). START plays from the top, CONTINUE carries on where it stopped, STOP stops; the tempo (BPM) follows the master, and the steps follow its 24 pulses a beat, so SLOOP cannot drift away from it. When the clock stops for half a second, PLAY on the FM-1 plays at its own tempo again. SYNC is a setting of the FM-1: it stays when you load a project.
Bluetooth MIDI is not supported: SLOOP, like Felucca, never switches the radio on.
## USB audio: record on a computer
On USB the FM-1 is also an audio input, named **Felucca**: 44.1 kHz, 16-bit stereo, class compliant, so no driver is needed. In your DAW or in Audacity, choose that input and record: you get the master output, exactly what the headphones play (after DUST, DUCK and FILT; the click and the count-in too, if they are on).
**Its level: HOME menu → USB AUDIO.**
- **MASTER** (default): the recording follows the MASTER knob, as the headphones do. Keep MASTER well up while you record.
- **FULL**: a fixed level, as with MASTER all the way up, kept from clipping by the output limiter, whatever the knob. MASTER then only sets the headphones: the right choice for an audio interface or a computer input with no level control of its own.
USB AUDIO is a setting of the FM-1: it stays as you left it. MIDI, the web editor and the installer keep working on the same cable while the computer records.
- The first time, the computer sees the FM-1 as a slightly different device (MIDI + audio) and sets it up again; the MIDI port keeps its name.
- The audio input comes from Felucca 1.0 (Leo Kuroshita): the same code, adapted to SLOOP.
## Lights
Hold **HOME** for the menu: **LIGHTS**, **KEYS** and **NOTES** are together there (with **USB AUDIO**, the level of the USB audio input: see [USB audio](#usb-audio-record-on-a-computer)). PRESETS moves, **KNOB 1** sets, OCT+ steps round, OCT− closes. They are saved with the settings of the FM-1, not with a project: loading a project or NEW PROJECT does not change them.
- **LIGHTS** — OFF, LOW, MID, HIGH: every button glows at that level, so its label can be read in the dark (on a black FM-1 the labels are unreadable unlit). What is on — the page, PLAY, REC, an octave — stays at full light and still blinks as before.
- **KEYS** — OFF, C KEYS, WHITE KEYS: the Cs, or every white key, glow at the LIGHTS level too (KEYS turns LIGHTS on at LOW if it was off). Played keys and the layer landmarks keep their own light.
- **NOTES** — ON: on a synth track, the notes sounding light their keys, played live or by the sequencer (the drum track always does). By @renebohne. It works on every page and in every layer: where the keys play or erase notes (EDIT, ARP, SAVE, SCL) the notes are lit — in SCL the scale and on the drum track in EDIT the sounds of the pattern then glow dimly underneath; where the keys are tiles (FX effects, SEQ steps, GLO mute / solo) the notes glow dimly and the tiles keep their full light.
The glow is a short pulse on every scan of the panel (about 900 times a second): no flicker. LOW, MID and HIGH are 0.5, 1 and 2 µs a scan; the landmarks (keys 1, 5, 9, 13 while a layer is held) and the notes under the tiles glow at 4 µs, a lit LED is about 95 µs.
## Specifications
| | |
@@ -328,16 +396,16 @@ The full Felucca engine is underneath: nine synthesis engines (analog, 4-op FM,
| Performance | layers (hold a button: keys and knobs change job): punch-in FX, erase, note repeat, step entry, key / chords, mute / solo / tap tempo |
| Drum kits | 37 (5 sampled, 32 synthesised, 16 sounds each) |
| Effects | 16 punch-in effects; master DUST, DUCK, DJ filter; per track drive, slicer, sends to a stereo chorus, a tempo delay and a stereo reverb; master limiter |
| Recording | live, quantised as heard (latency-compensated), overdub; records at once while playing; free take sets loop length and tempo |
| Recording | live, quantised as heard (latency-compensated), overdub; records at once while playing; free take sets loop length and tempo, or the tempo set, from the first note or a one-bar count-in |
| Memory | undo / redo, 4 projects, 32 user presets, autosave of the working project, song of 4 sections × 16 steps × 1–64 bars |
| Audio | 44.1 kHz, fixed-point DSP |
| MIDI | USB class-compliant in / out; channels 1–3 the synths, 10 the drums |
| Audio | 44.1 kHz, fixed-point DSP; USB audio input (the master output, 16-bit stereo, class compliant) |
| MIDI | USB class-compliant in / out; TRS MIDI IN (3.5 mm jack); channels 1–3 the synths, 10 the drums, 4–16 the selected track; MIDI clock in (USB or TRS) |
| Update | over USB from the browser (package SHA-256 and CRC checked) |
## Rescue, going back, credits
- **USB rescue:** hold **OCT−** alone while switching on (*SLOOP USB RESCUE*), then install again.
- **Interrupted install:** the FM-1 stays in update mode; press Install again and it finishes. A damaged package is refused, and the FM-1 keeps waiting for a good one.
- **Back to the official firmware:** M-VAVE's updater, M-UPGRADE, and the FM-1 firmware from m-vave.com.
- **Credits:** SLOOP is based on Felucca by Leo Kuroshita (@kurogedelic), Hügelton Instruments — engines, sequencer, editor and installer. Font: Terminus (SIL OFL 1.1). Samples: Versilian Studios VSCO-2 CE and VCSL, Sonic Pi (all CC0). PHASE: CrispyZebra (GPL). VOICE after klattsch (MIT). Interface ideas after teenage engineering's pocket operators and EP-133, Elektron's step entry and Akai's MPC (swing, note repeat, erase) — SLOOP is not affiliated with any of them.
- **Back to the official firmware:** on the installer page, open **Return to the official firmware (V15)**: save a backup with the editor first, download FM-1 V15 from m-vave.com, select its FM-1.fwsc (only that exact file is accepted) and install it. M-VAVE's own updater, M-UPGRADE, works too (close every other app that uses MIDI first). To come back to SLOOP, install it again and restore your backup.
- **Credits:** SLOOP is based on Felucca by Leo Kuroshita (@kurogedelic), Hügelton Instruments — engines, sequencer, editor and installer. Played-note key lights: @renebohne (pull request #11). TRS MIDI input buffer fix: Felucca [Salt] by ChanceTheMaker, found by keremimo. Knob reading, MIDI input, overload shedding, LED glow, key debounce, MIDI clock, the USB audio input and the return to the official firmware after Felucca 1.0 / 1.0.1. Font: Terminus (SIL OFL 1.1). Samples: Versilian Studios VSCO-2 CE and VCSL, Sonic Pi (all CC0). PHASE: CrispyZebra (GPL). VOICE after klattsch (MIT). Interface ideas after teenage engineering's pocket operators and EP-133, Elektron's step entry and Akai's MPC (swing, note repeat, erase) — SLOOP is not affiliated with any of them.
- **Licence:** GPL-3.0, no warranty. M-VAVE and FM-1 are trademarks of their owners; SLOOP is not affiliated with them. Drum kit names describe styles; they do not refer to any product.
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+5 -7
View File
@@ -1,17 +1,15 @@
# SLOOP: build the firmware, then open the browser installer.
# Needs a WSL distribution with the JieLi toolchain and the SDK files in build/deps/ac79 (BUILDING.md).
# Uses the dependencies already prepared (WSL MinUI-Build, JieLi toolchain, SDK files in build/deps/ac79).
$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot
$Distro = if ($env:SLOOP_WSL_DISTRO) { $env:SLOOP_WSL_DISTRO } else { 'Ubuntu' }
$Toolchain = if ($env:SLOOP_TOOLCHAIN) { $env:SLOOP_TOOLCHAIN } else { '/root/.jieli/toolchain' }
Write-Host ""
Write-Host " S L O O P 2.2" -ForegroundColor White
Write-Host " S L O O P 2.3" -ForegroundColor White
Write-Host " ---- ---- ---- ----" -ForegroundColor DarkGray
Write-Host "== Building the firmware (WSL $Distro)" -ForegroundColor Cyan
python tools/build_windows.py --distro $Distro --toolchain $Toolchain --sdk build/deps/ac79
Write-Host "== Building the firmware (WSL MinUI-Build)" -ForegroundColor Cyan
python tools/build_windows.py --distro MinUI-Build --toolchain /root/fm1-codex-deps/jieli/toolchain --sdk build/deps/ac79
if ($LASTEXITCODE -ne 0) { throw "The build failed" }
Write-Host "== Making the installer site" -ForegroundColor Cyan
python web/make_site.py build/felucca.fwsc 2.2 build/sloop-site
python web/make_site.py build/felucca.fwsc 2.3 build/sloop-site
if ($LASTEXITCODE -ne 0) { throw "make_site failed" }
Write-Host ""
Write-Host "Installer: http://localhost:8766/webapp/installer/ (Chrome or Edge, FM-1 on USB)" -ForegroundColor Green
Binary file not shown.
Binary file not shown.
+422 -50
View File
@@ -81,7 +81,12 @@
.chop .chops { display: flex; flex-wrap: wrap; gap: 3px; margin: 4px 0; }
.chop .chip { background: none; color: var(--fg); border: 1px solid var(--line); padding: 1px 6px; }
.chop .chip.on { background: var(--fg); color: var(--bg); }
.chop .chip { display: inline-flex; align-items: center; gap: 3px; cursor: pointer; user-select: none; }
.chop .chip input { margin: 0; accent-color: var(--fg); }
.chop .chip.off { color: var(--dim); text-decoration: line-through; }
.chop .chip.on input { accent-color: var(--bg); }
.chop input.len { width: 160px; }
.chop .selrow[hidden] { display: none; }
footer { margin-top: 24px; font-size: 11px; color: var(--dim); }
.row.pushed .v { font-weight: 600; }
/* librarian: local library and the device's user bank side by side, stacked on a phone */
@@ -298,6 +303,13 @@
<h2 data-t="projects" data-ic="symbol_folder"></h2>
<p class="dim" data-t="projHelp"></p>
<div class="slots" id="slots"></div>
<div class="group" id="bkgroup" style="margin-top:16px" hidden>
<h2 data-t="bkTitle" data-ic="port_disk"></h2>
<p class="dim" data-t="bkHelp"></p>
<p><button id="bk-save" data-t="bkSave"></button> <button id="bk-load" data-t="bkLoad"></button>
<input id="bk-file" type="file" accept=".json,application/json" hidden></p>
<progress id="bk-prog" max="1" value="0" hidden></progress>
</div>
</section>
<section class="panel" id="p-settings" data-tab="settings" data-dev hidden>
@@ -323,7 +335,8 @@ const CMD = { INFO: 1, GET: 2, SET: 3, DUMP: 4, DESC: 5, STEP_GET: 6, STEP_SET:
WATCH: 22, CHANGED: 23, RELOAD: 24, PING: 25, STEP_CHANGED: 26,
TRACK: 27, TRACK_MIX: 28, TRACK_DUMP: 29, TRACK_STEP: 30,
TRACK_PARAM: 31, TRACK_CHANGED: 32,
DRUM_STEP: 33 };
DRUM_STEP: 33,
BK_LIST: 34, BK_GET: 35, BK_PUT: 36 }; /* v6: backup / restore */
/* frames the device sends on its own (while WATCH is on); never replies */
const PUSH = new Set([CMD.CHANGED, CMD.RELOAD, CMD.STEP_CHANGED, CMD.TRACK_CHANGED]);
/* user preset bank: name 1..12 printable ASCII, a 16-step pattern of (note, flags 1 acc 2 slide 4 tie) */
@@ -466,6 +479,17 @@ const parse = {
const r = new Reader(a);
return stepExt(r, a, { track: r.b(), index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() });
},
/* v6: backup. LIST: rc, then per object id, length, CRC-32 (5 x 7 bit each) */
[CMD.BK_LIST](a) {
const r = new Reader(a), rc = r.b(), n = r.b(), items = [];
for (let i = 0; i < n; i++) items.push({ id: r.b(), len: u35dec(r), crc: u35dec(r) >>> 0 });
return { rc, items };
},
[CMD.BK_GET](a) {
const r = new Reader(a), id = r.b(), rc = r.b(), off = u35dec(r), count = r.b() | (r.b() << 7);
return { id, rc, off, count, data: unpack7(a.slice(r.i)) };
},
[CMD.BK_PUT](a) { const r = new Reader(a); return { op: r.b(), id: r.b(), rc: r.b() }; },
/* v5: the drum track's step: the lanes on (16 bits), their levels and ratchets (2 bits each) */
[CMD.DRUM_STEP](a) {
const r = new Reader(a);
@@ -536,6 +560,13 @@ const req = {
trackStep: (tr, i, st) => [CMD.TRACK_STEP, st ? [tr & 0x7F, ...req.stepSet(i, st)[1]] : [tr & 0x7F, i & 0x7F]],
/* v4: get (v == null) or set parameter id (P_*) of track tr, clamped as SET */
trackParam: (tr, id, v) => [CMD.TRACK_PARAM, v == null ? [tr & 0x7F, id & 0x7F] : [tr & 0x7F, id & 0x7F, ...v14enc(v)]],
/* v6: backup / restore */
bkList: () => [CMD.BK_LIST, []],
bkGet: (id, off, n) => [CMD.BK_GET, [id & 0x7F, ...u35enc(off), n & 0x7F, (n >> 7) & 0x7F]],
bkBegin: (id, len, crc) => [CMD.BK_PUT, [0, id & 0x7F, ...u35enc(len), ...u35enc(crc)]],
bkData: (id, off, bytes) => [CMD.BK_PUT, [1, id & 0x7F, ...u35enc(off), ...pack7(bytes)]],
bkCommit: (id) => [CMD.BK_PUT, [2, id & 0x7F]],
bkAbort: (id) => [CMD.BK_PUT, [3, id & 0x7F]],
};
/* which reply belongs to which request (the device echoes these) */
@@ -550,6 +581,8 @@ function replyMatches(cmd, args, a) {
case CMD.TRACK_MIX: case CMD.TRACK_DUMP: case CMD.DRUM_STEP: return a[0] === args[0];
case CMD.WATCH: return (a[0] & 1) === (args[0] & 1); /* bit 1: v4 firmware only */
case CMD.TRACK_STEP: case CMD.TRACK_PARAM: return a[0] === args[0] && a[1] === args[1];
case CMD.BK_GET: return a[0] === args[0] && [0, 1, 2, 3, 4].every((k) => a[2 + k] === args[1 + k]);
case CMD.BK_PUT: return a[0] === args[0] && a[1] === args[1];
default: return true;
}
}
@@ -942,20 +975,40 @@ function chopEqual(start, end, n) {
}
/* the chops of sorted markers: each to the next marker (the last to the end), cut at maxLen samples
when maxLen > 0 -> [{start, end}] (all of them; the slot takes CHOP.MAX) */
function chopList(marks, total, maxLen = 0) {
when maxLen > 0 -> [{start, end, i, off, full}] (all of them; the slot takes CHOP.MAX).
opt[i] (optional) = {off: left out of the slot, len: its own length in samples, over maxLen};
a chop is never longer than up to the next marker (`full`) */
function chopList(marks, total, maxLen = 0, opt = null) {
return marks.map((m, i) => {
let e = i + 1 < marks.length ? marks[i + 1] : total;
if (maxLen > 0) e = Math.min(e, m + maxLen);
return { start: m, end: Math.max(m + 1, e) };
const full = Math.max(m + 1, i + 1 < marks.length ? marks[i + 1] : total), o = (opt && opt[i]) || {};
let e = full;
if (o.len > 0) e = Math.min(e, m + o.len);
else if (maxLen > 0) e = Math.min(e, m + maxLen);
return { start: m, end: Math.max(m + 1, e), i, off: !!o.off, full };
});
}
/* the chops the slot gets: mode 0 the kept ones, the first CHOP.MAX of them; mode 1 the chop `sel` */
function chopPick(chops, mode = 0, sel = 0) {
if (mode === 1) return chops.length ? [chops[Math.max(0, Math.min(chops.length - 1, sel))]] : [];
return chops.filter((c) => !c.off).slice(0, CHOP.MAX);
}
/* the longest common length L (samples) so the chops, each cut at L, fit in room; Infinity if they fit */
function chopFit(chops, room) {
const len = chops.map((c) => c.end - c.start), sum = (L) => len.reduce((a, n) => a + Math.min(n, L), 0);
if (sum(Infinity) <= room) return Infinity;
let lo = 0, hi = Math.max(...len);
while (lo < hi) { const L = (lo + hi + 1) >> 1; if (sum(L) <= room) lo = L; else hi = L - 1; }
return lo;
}
/* chops -> slot zones {s (Int16Array, one gain for all: their levels are kept), root, lo, hi, fname}.
mode 0: one key each from key0 (each key plays its chop at its own speed, the keys between are silent)
mode 1: the chop `sel` alone over the whole keyboard, at its own speed on key0 */
mode 0: the kept chops (chopPick), one key each from key0 (each key plays its chop at its own speed,
the keys between are silent); mode 1: the chop `sel` alone over the whole keyboard, at its own speed
on key0. The file names keep the chop's own number. */
function chopZones(x, chops, key0, mode = 0, sel = 0) {
const use = mode === 1 ? [chops[Math.max(0, Math.min(chops.length - 1, sel))]] : chops.slice(0, CHOP.MAX);
const use = chopPick(chops, mode, sel);
let pk = 1e-9;
for (const c of use) for (let i = c.start; i < c.end; i++) pk = Math.max(pk, Math.abs(x[i]));
return use.map((c, j) => {
@@ -968,7 +1021,7 @@ function chopZones(x, chops, key0, mode = 0, sel = 0) {
}
const key = Math.min(127, key0 + (mode === 1 ? 0 : j));
return { s, root: key, lo: mode === 1 ? 0 : key, hi: mode === 1 ? 127 : key,
fname: `CHOP${String((mode === 1 ? sel : j) + 1).padStart(2, "0")}_${NOTE_NAMES[key % 12]}${Math.floor(key / 12) - 1}.wav` };
fname: `CHOP${String((c.i != null ? c.i : mode === 1 ? sel : j) + 1).padStart(2, "0")}_${NOTE_NAMES[key % 12]}${Math.floor(key / 12) - 1}.wav` };
});
}
@@ -1161,6 +1214,111 @@ const bank = {
};
/* the current sound: DUMP + the first 16 steps */
/* ---- v6: the complete backup (projects, sections, user presets, samples, settings) ---- */
function u35enc(v) { v >>>= 0; return [0, 1, 2, 3, 4].map((k) => Math.floor(v / 2 ** (7 * k)) & 0x7F); }
function u35dec(r) { let v = 0; for (let k = 0; k < 5; k++) v += r.b() * 2 ** (7 * k); return v >>> 0; }
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function b64enc(b) {
let s = "";
for (let i = 0; i < b.length; i += 3) {
const n = (b[i] << 16) | ((b[i + 1] || 0) << 8) | (b[i + 2] || 0);
s += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < b.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < b.length ? B64[n & 63] : "=");
}
return s;
}
function b64dec(s) {
s = String(s).replace(/[^A-Za-z0-9+/]/g, "");
const out = new Uint8Array((s.length * 3) >> 2);
let o = 0, acc = 0, bits = 0;
for (const c of s) {
acc = ((acc << 6) | B64.indexOf(c)) & 0xFFFFFF;
bits += 6;
if (bits >= 8) { bits -= 8; out[o++] = (acc >> bits) & 255; }
}
return out.subarray(0, o);
}
/* object ids (firmware editor.c ED_BK_IDS): 0 the working project, 1 the settings, 2..5 projects A..D,
6..7 the user preset banks, 32..34 the sample slots USR1..3 */
const BK = { FORMAT: "sloop-backup", VERSION: 1, SAMPLES: [32, 33, 34], RESTORE: [6, 7, 2, 3, 4, 5, 0, 1] };
class BackupError extends Error { constructor(code, msg) { super(msg); this.code = code; } }
/* read everything; progress(done, total bytes) */
async function backupCapture(rq, info, progress = () => {}) {
const L = parse[CMD.BK_LIST](await rq(req.bkList(), { timeout: 5000, retries: 0 }));
if (L.rc) throw new BackupError("bkRc" + L.rc, `LIST rc ${L.rc}`);
const total = L.items.reduce((s, it) => s + it.len, 0), objects = [];
let done = 0;
for (const it of L.items) {
const data = new Uint8Array(it.len);
for (let off = 0; off < it.len; off += 256) {
const n = Math.min(256, it.len - off);
const g = parse[CMD.BK_GET](await rq(req.bkGet(it.id, off, n), { timeout: 1500, retries: 2 }));
if (g.rc) throw new BackupError(g.rc === 5 ? "bkStale" : "bkRead", `GET ${it.id}+${off} rc ${g.rc}`);
if (g.data.length !== n) throw new BackupError("bkRead", `GET ${it.id}+${off}: ${g.data.length} bytes`);
data.set(g.data, off);
done += n;
progress(done, total);
}
if (crc32(data) !== it.crc) throw new BackupError("bkStale", `object ${it.id}: CRC`);
objects.push({ id: it.id, len: it.len, crc: it.crc, data: b64enc(data) });
}
return { format: BK.FORMAT, version: BK.VERSION, firmware: info.version, date: new Date().toISOString(), objects };
}
/* a backup file -> {id: Uint8Array}; every object checked against its length and CRC */
function backupObjects(file) {
if (!file || file.format !== BK.FORMAT || !(file.version >= 1) || !Array.isArray(file.objects)) throw new BackupError("bkBad", "not a SLOOP backup");
const m = new Map();
for (const o of file.objects) {
const d = b64dec(o.data || "");
if (![...BK.RESTORE, ...BK.SAMPLES].includes(o.id) || d.length !== o.len || crc32(d) !== (o.crc >>> 0))
throw new BackupError("bkBad", `object ${o.id}: damaged`);
m.set(o.id, d);
}
if (!m.has(0) || !m.has(1)) throw new BackupError("bkBad", "incomplete backup");
return m;
}
/* write it back: banks, projects, the working project, the settings, then the samples */
async function backupRestore(rq, file, progress = () => {}) {
const m = backupObjects(file);
const total = [...m.values()].reduce((s, d) => s + d.length, 0) || 1;
let done = 0;
for (const id of BK.RESTORE) {
if (!m.has(id)) continue;
const d = m.get(id);
let r = parse[CMD.BK_PUT](await rq(req.bkBegin(id, d.length, crc32(d)), { timeout: 1500, retries: 1 }));
if (r.rc) throw new BackupError("bkWrite", `begin ${id} rc ${r.rc}`);
for (let off = 0; off < d.length; off += 256) {
r = parse[CMD.BK_PUT](await rq(req.bkData(id, off, d.subarray(off, off + 256)), { timeout: 1500, retries: 1 }));
if (r.rc) throw new BackupError("bkWrite", `data ${id}+${off} rc ${r.rc}`);
done += Math.min(256, d.length - off);
progress(done, total);
}
r = parse[CMD.BK_PUT](await rq(req.bkCommit(id), { timeout: 5000, retries: 0 }));
if (r.rc === 3) throw new BackupError("bkStop", "stop the song first");
if (r.rc) throw new BackupError("bkWrite", `commit ${id} rc ${r.rc}`);
}
for (const id of BK.SAMPLES) {
if (!m.has(id)) continue;
const d = m.get(id), k = id - 32;
if (!d.length) {
const e = parse[CMD.SMP_ERASE](await rq(req.smpErase(k), { timeout: 2500, retries: 0 }));
if (e.rc) throw new BackupError("bkWrite", `erase USR${k + 1} rc ${e.rc}`);
continue;
}
let r = parse[CMD.SMP_BEGIN](await rq(req.smpBegin(k), { timeout: 1000, retries: 0 }));
if (r.rc) throw new BackupError("bkWrite", `USR${k + 1} begin rc ${r.rc}`);
const data = d.subarray(SMP.DATA_OFF);
for (let off = 0; off < data.length; off += 256) {
const w = parse[CMD.SMP_WRITE](await rq(req.smpWrite(k, SMP.DATA_OFF + off, data.subarray(off, off + 256)), { timeout: 1000, retries: 1 }));
if (w.rc) throw new BackupError("bkWrite", `USR${k + 1} write rc ${w.rc}`);
done += Math.min(256, data.length - off);
progress(done, total);
}
r = parse[CMD.SMP_END](await rq(req.smpEnd(k, d.subarray(0, SMP.HDR_LEN)), { timeout: 2000, retries: 0 }));
if (r.rc) throw new BackupError("bkWrite", `USR${k + 1} end rc ${r.rc}`);
}
return true;
}
async function capturePatch(rq, info, name) {
const dump = parse[CMD.DUMP](await rq(req.dump()), info);
const steps = [];
@@ -1252,7 +1410,7 @@ function makeMockDevice(opt = {}) {
D("BPM", F.BPM, 40, 240, 90), D("SWING", F.SWING, 0, 100, 0), E("CLICK", ["OFF", "REC", "ON"], 0), D("TUNE", F.INT, -50, 50, 0),
E("TIME", NDIV, 1), D("FDBK", F.PCT, 0, 120, 60), D("COLR", F.PCT, 0, 127, 70), D("MIX", F.PCT, 0, 127, 90),
D("SIZE", F.PCT, 0, 127, 90), D("DAMP", F.PCT, 0, 127, 60), D("CRT", F.LFOHZ, 0, 127, 40), D("CDP", F.PCT, 0, 127, 60),
E("MIDI", NDASH, 0), E("SYNC", NDASH, 0), E("ROUT", NDASH, 0), D("CPU", F.INT, 0, 0, 0),
E("MIDI", NDASH, 0), E("SYNC", ["INT", "USB", "TRS"], 0), E("ROUT", NDASH, 0), D("CPU", F.INT, 0, 0, 0),
D("SLOT", F.INT, 1, 4, 1), E("NAME", NDASH, 0), E("LOAD", NGO, 0), E("SAVE", NGO, 0),
E("ENG", ["ANALOG", "DIGITAL", "PHASE", "LOFI", "SAMPLE", "VOICE", "TRIO", "WHEEL",
"GRAIN"], 0), E("SET", NGO, 0),
@@ -1379,6 +1537,8 @@ function makeMockDevice(opt = {}) {
slots: [null, null, null, null],
smp: [0, 1, 2].map(() => ({ flash: new Uint8Array(SMP.SLOT_SIZE).fill(0xFF), zones: 0, name: "", len: 0, next: SMP.DATA_OFF })),
bank: new Array(opt.slots || 32).fill(null), /* user presets: {engine, name, p, pattern} */
settings: Uint8Array.from({ length: 88 }, (_, i) => (i * 37 + 5) & 0xFF), /* v6: the settings object (opaque here) */
bkSnap: null, bkPut: null,
watch: false, v4: false, lastReq: 0,
};
for (const k of ["engine", "preset", "p", "step"]) {
@@ -1521,7 +1681,7 @@ function makeMockDevice(opt = {}) {
s(opt.legacy ? "FELUCCA 0.4 BETA (MOCK)" : opt.v3 ? "FELUCCA 0.8 (MOCK)" : "FELUCCA SLOOP 2.0 (MOCK)"); b(ENG.length); b(P_COUNT); b(G_COUNT); b(NSTEP); b(P_E0);
ENG.forEach((e) => s(e.name));
if (!opt.legacy) b(NTRK);
if (v5) b(5);
if (v5) b(opt.noBackup ? 5 : 6); /* v6: backup / restore */
break;
case CMD.GET: case CMD.SET: {
if (a.length < 2) return null;
@@ -1676,6 +1836,53 @@ function makeMockDevice(opt = {}) {
b(a[0]); b(rc);
break;
}
/* v6 backup: the mock's objects are JSON bytes (projects, banks) and the raw sample slots */
case CMD.BK_LIST: {
if (opt.noBackup) return null;
const enc = (o) => Uint8Array.from(Array.from(JSON.stringify(o), (c) => c.charCodeAt(0) & 0x7F));
const bankOf = (h) => { const x = st.bank.slice(h * 16, h * 16 + 16); return x.some(Boolean) ? enc(x) : new Uint8Array(0); };
st.bkSnap = new Map([[0, enc(project())], [1, st.settings.slice()], ...[0, 1, 2, 3].map((k) => [2 + k, st.slots[k] ? enc(st.slots[k]) : new Uint8Array(0)]),
[6, bankOf(0)], [7, bankOf(1)], ...[0, 1, 2].map((k) => [32 + k, st.smp[k].zones ? st.smp[k].flash.slice(0, SMP.DATA_OFF + st.smp[k].len) : new Uint8Array(0)])]);
st.bkPut = null;
b(0); b(st.bkSnap.size);
for (const [id, d] of st.bkSnap) { b(id); out.push(...u35enc(d.length), ...u35enc(crc32(d))); }
break;
}
case CMD.BK_GET: {
if (opt.noBackup || a.length !== 8) return null;
const r = new Reader(a), id = r.b(), off = u35dec(r), n = r.b() | (r.b() << 7);
const d = st.bkSnap && st.bkSnap.get(id);
const rc = !d || !n || n > 256 || off + n > d.length ? 1 : st.bkPut && id === 0 ? 5 : 0;
b(id); b(rc); out.push(...u35enc(off)); b(rc ? 0 : n); b(rc ? 0 : n >> 7);
if (!rc) out.push(...pack7(d.subarray(off, off + n)));
break;
}
case CMD.BK_PUT: {
if (opt.noBackup || a.length < 2) return null;
const op = a[0], id = a[1], r = new Reader(a.slice(2));
let rc = 1;
if (op === 0 && a.length === 12 && [0, 1, 2, 3, 4, 5, 6, 7].includes(id)) {
const len = u35dec(r), crc = u35dec(r);
if ((id >= 2 || len) && len <= 1 << 20) { st.bkPut = { id, len, crc, pos: 0, buf: new Uint8Array(len) }; st.bkSnap = null; rc = 0; }
} else if (!st.bkPut || st.bkPut.id !== id) rc = 5;
else if (op === 1 && a.length >= 9) {
const off = u35dec(r), d = unpack7(a.slice(7));
if (off === st.bkPut.pos && d.length && d.length <= st.bkPut.len - off) { st.bkPut.buf.set(d, off); st.bkPut.pos += d.length; rc = 0; }
} else if (op === 2) {
const P = st.bkPut;
st.bkPut = null;
rc = P.pos !== P.len || crc32(P.buf) !== P.crc ? 2 : 0;
if (!rc) try {
const js = () => JSON.parse(Array.from(P.buf, (c) => String.fromCharCode(c)).join(""));
if (id === 1) { if (P.len !== st.settings.length) throw 0; st.settings = P.buf.slice(); }
else if (id === 0) { const o = js(); st.tracks = o.tracks; st.sel = o.sel; st.g = o.g; }
else if (id <= 5) st.slots[id - 2] = P.len ? js() : null;
else { const x = P.len ? js() : new Array(16).fill(null); for (let i = 0; i < 16; i++) st.bank[(id - 6) * 16 + i] = x[i] || null; }
} catch (e) { rc = 2; }
} else if (op === 3) { st.bkPut = null; rc = 0; }
b(op); b(id); b(rc);
break;
}
case CMD.SMP_INFO:
b(3); b(SMP.SLOT_SIZE / 1024);
st.smp.forEach((u) => { b(u.zones); s(u.zones ? u.name : ""); b(u.zones ? Math.ceil(u.len / 1024) : 0); });
@@ -1859,14 +2066,18 @@ const TEXT = {
samples: "サンプル", smpHelp: "WAV をドロップするか選んでください。1 スロットに 16 ファイルまで、モノ 22050 Hz の ADPCM で合計約 7 秒。SAMPLE エンジンの SET(または SLICE エンジンの SRC)で USR1〜USR3 を選ぶと鳴ります。",
zones: "ゾーン", smpName: "名前", chooseFiles: "ファイルを選ぶ", upload: "書き込む", erase: "消去", clearList: "リストを消す",
file: "ファイル", root: "ルート", keys: "鍵盤", length: "長さ", remove: "外す",
chopOpen: "音を開く", chopHelp: "録音(WAV、MP3、AIFF…)を開くかドロップし、チョップを決めてスロットへ。1 キーに 1 チョップ。",
chopOpen: "音を開く", chopHelp: "録音(WAV、MP3、AIFF…)を開くかドロップし、チョップを決めてスロットへ。1 キーに 1 チョップ。長い録音(7 秒以上)でも、使うチョップを選び長さを調整できます。",
chopDrop: "ここに録音をドロップ、またはクリック", chopPlay: "▶ 再生", chopStop: "■ 停止", chopTap: "TAP",
chopSnap: "アタックに吸着", chopClear: "マーカーを消去", chopHits: "アタック検出", chopSens: "感度",
chopGrid: "グリッド", chopEqual: "等分", chopKey: "最初のキー", chopModeKeys: "1 キーに 1 チョップ",
chopModeOne: "選択チョップを鍵盤全体に", chopMax: "最大長", chopTo: "送信先", chopZip: "WAV をダウンロード",
chopChops: "チョップ", chopTooLong: "スロットに入りません", chopTooMany: "(最大 16 チョップ。残りは使われません)",
chopLoaded: "読み込みました: ", chopSent: "チョップを書き込みました ",
chopHint: "スペース: 再生中に TAP(停止中は再生/停止)· 1–9 0: 試聴 · ダブルクリック: 追加 · ドラッグ: 移動 · ← →: 微調整 · Del: 削除 · ホイール: ズーム",
chopSel: "チョップ", chopKeep: "使う", chopLen: "長さ", chopFull: "次のマーカーまで", chopAll: "すべて使う", chopNone: "すべて外す",
chopFit: "スロットに合わせる", chopKept: "使用", chopFitted: "長いチョップを短くしました: 最大 ",
chopOverHint: "— チョップを外すか、短くするか、「スロットに合わせる」を押してください",
chopKeepHint: "チェックを外したチョップはスロットにも WAV にも入りません。長い録音でも必要な部分だけ選べます。",
chopHint: "スペース: 再生中に TAP(停止中は再生/停止)· 1–9 0: 試聴 · ダブルクリック: 追加 · ドラッグ: 移動 · ← →: 微調整 · K: 使う/外す · 下のつまみ: 長さ · Del: 削除 · ホイール: ズーム",
smpTooBig: "大きすぎます", smpDecodeFail: "読み込めません: ", smpUploading: "書き込み中 USR", smpDone: "書き込みました USR",
smpFail: "サンプルの書き込みに失敗しました: ", smpErased: "消去しました USR",
confirmErase: "USR{n} を消去しますか?", confirmUpload: "USR{n} に書き込みますか? 今の内容は消えます。",
@@ -1904,6 +2115,11 @@ const TEXT = {
mixer: "ミキサー", mixHelp: "本体の TRACKS ページと同じ 4 トラック。フェーダーはレベル(ドラムは GLO > DRUMS LEVEL)。パンはどのトラックも選択を変えずに書き込みます(0.8 のファームウェアでは一瞬そのトラックを選びます)。REC は本体での録音待機の表示です。",
level: "レベル", pan: "パン", mute: "ミュート", rec: "REC", selectTrack: "選択", selectedTrack: "選択中",
projHelp: "プロジェクトは本体の状態をまとめて保存します: 4 トラックの音色とパターン、選択中のトラック、グローバル設定。",
bkTitle: "バックアップ", bkHelp: "FM-1 の中身をすべて 1 つのファイルに保存します: 今の曲、プロジェクト 1〜4(ソングのセクション A〜D)、ユーザープリセット、サンプル USR1〜3、設定(色、キャリブレーション、ソング、ライト)。復元すると、本体はファイルの状態に戻ります(今の内容は上書きされます)。",
bkSave: "バックアップを保存", bkLoad: "ファイルから復元", bkSaving: "バックアップ中 ", bkSaved: "バックアップを保存しました",
bkRestoring: "復元中 ", bkRestored: "復元しました", bkConfirm: "FM-1 の今の内容をすべてこのバックアップで置き換えます。続けますか?",
bkBad: "SLOOP のバックアップファイルではないか、壊れています: ", bkStop: "FM-1 の再生を止めてから、もう一度復元してください。",
bkStale: "本体の内容が途中で変わりました。もう一度バックアップしてください: ", bkRead: "読み取りエラー: ", bkWrite: "書き込みエラー: ", bkRc4: "フラッシュがありません",
system: "システム", firmware: "ファームウェア", sync: "同期", tracksN: "トラック", stepsN: "ステップ数", enginesL: "エンジン",
smpSlots: "サンプルスロット", userBank: "ユーザープリセット", none: "なし",
},
@@ -1930,14 +2146,18 @@ const TEXT = {
samples: "Samples", smpHelp: "Drop or choose WAV files. Up to 16 files per slot, stored as mono 22050 Hz ADPCM (about 7 s in all). Select USR1–USR3 with SET on the SAMPLE engine (or SRC on the SLICE engine).",
zones: "zones", smpName: "Name", chooseFiles: "Choose files", upload: "Upload", erase: "Erase", clearList: "Clear list",
file: "File", root: "Root", keys: "Keys", length: "Length", remove: "Remove",
chopOpen: "Open a sound", chopHelp: "Open or drop a recording (WAV, MP3, AIFF…), mark the chops, send them to a slot: one chop per key.",
chopOpen: "Open a sound", chopHelp: "Open or drop a recording (WAV, MP3, AIFF…), mark the chops, send them to a slot: one chop per key. Any length: a recording longer than a slot (7 s) works, keep the chops you want and adjust them.",
chopDrop: "Drop a recording here, or click", chopPlay: "▶ Play", chopStop: "■ Stop", chopTap: "TAP",
chopSnap: "snap to the hit", chopClear: "Clear markers", chopHits: "Find hits", chopSens: "sensitivity",
chopGrid: "Grid", chopEqual: "Equal parts", chopKey: "First key", chopModeKeys: "one key per chop",
chopModeOne: "selected chop, whole keyboard", chopMax: "max length", chopTo: "Send to", chopZip: "Download WAVs",
chopChops: "chops", chopTooLong: "too long for a slot", chopTooMany: "(16 chops at most: the rest are left out)",
chopLoaded: "Loaded: ", chopSent: "Chops in ",
chopHint: "space: TAP while it plays (play/stop when stopped) · 1–9 0: listen · double-click: add · drag: move · ← →: nudge · Del: remove · wheel: zoom",
chopSel: "Chop", chopKeep: "keep", chopLen: "length", chopFull: "Up to the next marker", chopAll: "Keep all", chopNone: "Keep none",
chopFit: "Fit to slot", chopKept: "kept", chopFitted: "Long chops shortened to at most ",
chopOverHint: "— untick chops, shorten them, or press Fit to slot",
chopKeepHint: "Unticked chops go neither to the slot nor to the WAVs: from a long recording, keep only what you want.",
chopHint: "space: TAP while it plays (play/stop when stopped) · 1–9 0: listen · double-click: add · drag: move · ← →: nudge · K: keep / leave out · bottom handle: length · Del: remove · wheel: zoom",
smpTooBig: "too large", smpDecodeFail: "Cannot read: ", smpUploading: "Uploading USR", smpDone: "Uploaded USR",
smpFail: "Sample upload failed: ", smpErased: "Erased USR",
confirmErase: "Erase USR{n}?", confirmUpload: "Write to USR{n}? Its current contents will be replaced.",
@@ -1975,6 +2195,11 @@ const TEXT = {
mixer: "Mixer", mixHelp: "The four tracks of the device's TRACKS page. The fader is the level (drums: GLO > DRUMS LEVEL). Pan is written to any track without changing the selection (firmware 0.8: by selecting it for a moment). REC shows a track armed for live recording on the device.",
level: "Level", pan: "Pan", mute: "Mute", rec: "REC", selectTrack: "Select", selectedTrack: "Selected",
projHelp: "A project keeps the whole device state: the sound and pattern of all four tracks, the selected track and the global settings.",
bkTitle: "Backup", bkHelp: "Everything on the FM-1 in one file: the music you are working on, the projects 1–4 (the song sections A–D), the user presets, the samples USR1–3 and the settings (colours, calibration, the song, the lights). Restoring puts the FM-1 back as it was in the file (what is on it now is replaced).",
bkSave: "Save a backup", bkLoad: "Restore from a file", bkSaving: "Backing up ", bkSaved: "Backup saved",
bkRestoring: "Restoring ", bkRestored: "Restored", bkConfirm: "Replace everything on the FM-1 with this backup?",
bkBad: "Not a SLOOP backup, or damaged: ", bkStop: "Stop the FM-1 (PLAY), then restore again.",
bkStale: "The FM-1 changed during the backup; back up again: ", bkRead: "Read error: ", bkWrite: "Write error: ", bkRc4: "No flash",
system: "System", firmware: "Firmware", sync: "Sync", tracksN: "Tracks", stepsN: "Steps", enginesL: "Engines",
smpSlots: "Sample slots", userBank: "User presets", none: "none",
},
@@ -2279,6 +2504,7 @@ function buildUI() {
renderSlots();
renderSamples();
renderSysinfo();
$("bkgroup").hidden = !(dev.info.proto >= 6); /* v6 firmware: backup / restore */
}
/* the track selector (v3): T1..T3 synth parts, T4 the drum track; the editor shows the selected one */
@@ -2915,16 +3141,45 @@ async function smpErase(k) {
/* ---------------------------------------------------------------- CHOP --- */
/* Load a recording, mark the chops (live: TAP / space while it plays, each tap moved to the hit it
meant; or by hits, a tempo grid, equal parts; double-click adds, drag moves, Delete removes),
audition them (click, keys 1-9 0), then one chop per key into USR1..3 or as WAV files. */
const CH = { x: null, nov: null, name: "", marks: [], sel: -1, v0: 0, v1: 1, ctx: null, src: null, t0: 0, raf: 0,
drag: -1, key0: 60, mode: 0, maxLen: 0, ui: null };
audition them (click, keys 1-9 0), keep or leave out each one and set its length (a recording longer
than a slot: keep the chops you want, shorten them, or Fit to slot), then one chop per key into
USR1..3 or as WAV files. CH.opt[i] = {off, len} goes with marker i. */
const CH = { x: null, nov: null, name: "", marks: [], opt: [], sel: -1, v0: 0, v1: 1, ctx: null, src: null, t0: 0, raf: 0,
drag: -1, dragEnd: false, key0: 60, mode: 0, maxLen: 0, ui: null };
const chR = () => SMP.RATE;
const chSecs = (n) => (n / SMP.RATE).toFixed(2) + " s";
function chopChops() { return CH.x ? chopList(CH.marks, CH.x.length, Math.round(CH.maxLen * SMP.RATE)) : []; }
function chopUsed() { /* the chops the slot gets, and their samples */
const c = chopChops(), use = CH.mode === 1 ? (c[CH.sel] ? [c[CH.sel]] : c.slice(0, 1)) : c.slice(0, CHOP.MAX);
return { all: c, use, n: use.reduce((a, q) => a + (q.end - q.start), 0) };
function chopChops() { return CH.x ? chopList(CH.marks, CH.x.length, Math.round(CH.maxLen * SMP.RATE), CH.opt) : []; }
function chopUsed() { /* the chops the slot gets, their samples, and each chop's key */
const c = chopChops(), use = chopPick(c, CH.mode, Math.max(0, CH.sel)), key = new Map();
if (CH.mode === 0) use.forEach((q, j) => key.set(q.i, Math.min(127, CH.key0 + j)));
return { all: c, use, n: use.reduce((a, q) => a + (q.end - q.start), 0), key };
}
/* the label of chop i: its key, "—" when left out, nothing past the 16 kept ones or over the whole keyboard */
function chopKeyName(u, i) {
if (CH.mode === 1) return "";
const c = u.all[i];
return c && c.off ? " —" : u.key.has(i) ? " " + noteName(u.key.get(i)) : "";
}
function chopOpt(i) { return CH.opt[i] || (CH.opt[i] = { off: false, len: 0 }); }
function chopKeep(i, keep) { /* keep / leave out chop i (keep undefined: toggle) */
if (!CH.x || i < 0 || i >= CH.marks.length) return;
const o = chopOpt(i);
o.off = keep === undefined ? !o.off : !keep;
chopRender();
}
function chopKeepAll(keep) { if (CH.x) { CH.opt = CH.marks.map((_, i) => ({ ...chopOpt(i), off: !keep })); chopRender(); } }
function chopSetLen(i, len) { /* the length of chop i in samples (0: up to the next marker) */
if (!CH.x || i < 0 || i >= CH.marks.length) return;
chopOpt(i).len = Math.max(0, Math.round(len));
chopRender();
}
function chopFitAll() { /* shorten the longest kept chops so they all fit the slot */
const { use } = chopUsed(), L = chopFit(use, SMP.MAX_DATA * 2 - use.length); /* (an odd chop takes half a byte more) */
if (!isFinite(L)) return;
for (const c of use) if (c.end - c.start > L) chopOpt(c.i).len = L;
sayK("chopFitted", chSecs(L));
chopRender();
}
async function chopDecode(buf) { /* any file the browser decodes -> mono Float64 at SMP.RATE */
@@ -2945,6 +3200,7 @@ async function chopLoad(f) {
CH.nov = chopNovelty(x);
CH.name = f.name.replace(/\.[^.]*$/, "").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 8) || "CHOP";
CH.marks = [];
CH.opt = [];
CH.sel = -1;
CH.v0 = 0;
CH.v1 = x.length;
@@ -2953,16 +3209,27 @@ async function chopLoad(f) {
chopRender();
}
function chopSetMarks(m) {
CH.marks = [...new Set(m.map((v) => Math.max(0, Math.min(CH.x.length - 1, Math.round(v)))))].sort((a, b) => a - b);
/* new markers; opt (aligned with m) their options, else each keeps the options of the marker it was */
function chopSetMarks(m, opt = null) {
const was = new Map(CH.marks.map((v, i) => [v, CH.opt[i]])), seen = new Set(), pairs = [];
m.forEach((v, i) => {
const p = Math.max(0, Math.min(CH.x.length - 1, Math.round(v)));
if (seen.has(p)) return;
seen.add(p);
const o = opt ? opt[i] : was.get(p);
pairs.push([p, o ? { ...o } : { off: false, len: 0 }]);
});
pairs.sort((a, b) => a[0] - b[0]);
CH.marks = pairs.map((q) => q[0]);
CH.opt = pairs.map((q) => q[1]);
if (CH.sel >= CH.marks.length) CH.sel = CH.marks.length - 1;
chopRender();
}
function chopAdd(pos) { /* a new marker; one within 30 ms is moved there instead */
const near = CH.marks.findIndex((m) => Math.abs(m - pos) < 0.03 * chR());
const m = CH.marks.slice();
if (near >= 0) m[near] = pos; else m.push(pos);
chopSetMarks(m);
const m = CH.marks.slice(), opt = CH.marks.map((_, i) => CH.opt[i]);
if (near >= 0) m[near] = pos; else { m.push(pos); opt.push(null); }
chopSetMarks(m, opt);
CH.sel = CH.marks.indexOf(Math.round(pos));
chopDraw();
}
@@ -3044,12 +3311,18 @@ function chopDraw() {
g.clearRect(0, 0, W, Hh);
if (!CH.x) { g.fillStyle = DIM; g.font = "12px sans-serif"; g.fillText(t("chopDrop"), 8, Hh / 2); return; }
const x = CH.x, v0 = CH.v0, span = CH.v1 - CH.v0, X = (p) => (p - v0) / span * W, mid = Hh / 2 + 6;
const { all: chops, use } = chopUsed();
chops.forEach((c, i) => { /* the chops: the selected one filled, unused ones hatched */
const a = X(c.start), b = X(c.end);
if (b < 0 || a > W) return;
const U = chopUsed(), { all: chops, use } = U;
const hatch = (a, b) => { /* what the slot does not get */
g.save(); g.beginPath(); g.rect(a, 12, b - a, Hh - 12); g.clip(); g.strokeStyle = LINE;
for (let q = Math.floor(a / 8) * 8 - 8; q < b; q += 8) { g.beginPath(); g.moveTo(q, Hh); g.lineTo(q + 8, 12); g.stroke(); }
g.restore();
};
if (chops.length && chops[0].start > 0) hatch(X(0), X(chops[0].start));
chops.forEach((c, i) => { /* the chops: the selected one filled, left-out parts hatched */
const a = X(c.start), b = X(c.end), f = X(c.full);
if (f < 0 || a > W) return;
if (i === CH.sel) { g.fillStyle = LINE; g.fillRect(a, 12, b - a, Hh - 12); }
if (!use.includes(c)) { g.strokeStyle = LINE; for (let q = Math.floor(a / 8) * 8; q < b; q += 8) { g.beginPath(); g.moveTo(q, Hh); g.lineTo(q + 8, 12); g.stroke(); } }
if (!use.includes(c)) hatch(a, f); else if (c.end < c.full) hatch(b, f);
});
g.fillStyle = FG;
for (let px = 0; px < W; px++) { /* the wave: min / max per pixel */
@@ -3064,9 +3337,15 @@ function chopDraw() {
if (px < -1 || px > W + 1) return;
g.fillStyle = FG;
g.fillRect(Math.round(px), 0, i === CH.sel ? 2 : 1, Hh);
const key = CH.mode === 1 ? "" : (i < CHOP.MAX ? " " + noteName(Math.min(127, CH.key0 + i)) : "");
g.fillText(String(i + 1) + key, px + 3, 10);
g.fillText(String(i + 1) + chopKeyName(U, i), px + 3, 10);
});
const sc = chops[CH.sel];
if (sc) { /* the selected chop's end: a handle at the bottom, drag it */
const px = Math.round(X(sc.end));
g.fillStyle = FG;
g.fillRect(px - 1, Hh - 30, 2, 30);
g.beginPath(); g.moveTo(px, Hh - 30); g.lineTo(px - 7, Hh - 38); g.lineTo(px - 7, Hh - 22); g.closePath(); g.fill();
}
if (CH.src && CH.src.whole && CH.ctx) { /* the playhead, as heard */
const p = X(chopHeard());
g.fillStyle = DIM;
@@ -3099,6 +3378,17 @@ function chopUI() {
u.meter = el("progress", { max: SMP.MAX_DATA * 2, value: 0 });
u.room = el("span", { class: "dim" });
u.list = el("div", { class: "chops" });
/* the selected chop: keep it or not, its length; and all of them at once */
u.selName = el("b", { class: "selname" });
u.keep = el("input", { type: "checkbox", onchange: () => chopKeep(CH.sel, u.keep.checked) });
u.len = el("input", { type: "range", class: "len", min: 10, max: 1000, step: 1, title: t("chopLen"),
oninput: () => { const c = chopChops()[CH.sel]; if (c) { const ms = +u.len.value, full = c.full - c.start; chopSetLen(CH.sel, ms >= Math.floor(full / SMP.RATE * 1000) ? 0 : ms * SMP.RATE / 1000); } } });
u.lenTxt = el("span", { class: "dim" });
u.selPlay = el("button", { onclick: () => chopAudition(CH.sel) }, "▶");
u.full = el("button", { onclick: () => chopSetLen(CH.sel, 0) }, t("chopFull"));
u.selRow = el("div", { class: "head selrow" }, u.selName, el("label", {}, u.keep, " " + t("chopKeep")),
el("span", { text: t("chopLen") }), u.len, u.lenTxt, u.selPlay, u.full);
u.fit = el("button", { onclick: chopFitAll }, t("chopFit"));
u.send = [0, 1, 2].map((k) => el("button", { ic: "symbol_upload", onclick: () => chopSend(k) }, `USR${k + 1}`));
const region = () => { /* first..last marker when there are two, else all */
const m = CH.marks;
@@ -3123,30 +3413,51 @@ function chopUI() {
el("button", { onclick: () => { if (CH.x) { const [a, b] = region(); chopSetMarks(chopEqual(a, b, +u.n.value)); } } }, t("chopEqual")), u.n),
el("div", { class: "head" }, el("span", { text: t("chopKey") }), u.key, u.mode,
el("span", { text: t("chopMax") }), u.max, u.meter, u.room),
el("div", { class: "head" }, el("button", { onclick: () => chopKeepAll(true) }, t("chopAll")),
el("button", { onclick: () => chopKeepAll(false) }, t("chopNone")), u.fit,
el("span", { class: "dim", text: t("chopKeepHint") })),
u.list, u.selRow,
el("div", { class: "head" }, el("span", { text: t("chopTo") }), ...u.send,
el("button", { ic: "symbol_download", onclick: chopZip }, t("chopZip"))),
u.list);
el("button", { ic: "symbol_download", onclick: chopZip }, t("chopZip"))));
/* the wave: click = select + listen, double-click = a marker, drag a marker, wheel = zoom */
const posAt = (e) => { const r = u.cv.getBoundingClientRect(); return CH.v0 + (e.clientX - r.left) / r.width * (CH.v1 - CH.v0); };
const markAt = (e) => {
const r = u.cv.getBoundingClientRect(), per = (CH.v1 - CH.v0) / r.width;
return CH.marks.findIndex((m) => Math.abs(m - posAt(e)) < 5 * per);
};
const endAt = (e) => { /* on the selected chop's end handle (the bottom of the wave)? */
const c = chopChops()[CH.sel];
if (!c) return false;
const r = u.cv.getBoundingClientRect(), per = (CH.v1 - CH.v0) / r.width;
return e.clientY - r.top > r.height - 40 && Math.abs(c.end - posAt(e)) < 7 * per;
};
u.cv.addEventListener("pointerdown", (e) => {
if (!CH.x) { file.click(); return; }
u.cv.focus();
if (endAt(e)) { CH.dragEnd = true; u.cv.setPointerCapture(e.pointerId); return; }
const k = markAt(e);
if (k >= 0) { CH.drag = k; CH.sel = k; u.cv.setPointerCapture(e.pointerId); chopDraw(); return; }
const p = posAt(e), i = chopChops().findIndex((c) => p >= c.start && p < c.end);
if (i >= 0) chopAudition(i);
});
u.cv.addEventListener("pointermove", (e) => {
if (CH.drag < 0) { u.cv.style.cursor = CH.x && markAt(e) >= 0 ? "ew-resize" : "default"; return; }
if (CH.dragEnd) { /* the selected chop's length; up to the next marker = full */
const c = chopChops()[CH.sel];
if (!c) return;
const n = Math.round(Math.max(0.01 * SMP.RATE, Math.min(c.full - c.start, posAt(e) - c.start)));
chopOpt(CH.sel).len = n >= c.full - c.start ? 0 : n;
chopDraw();
return;
}
if (CH.drag < 0) { u.cv.style.cursor = CH.x && (markAt(e) >= 0 || endAt(e)) ? "ew-resize" : "default"; return; }
const m = CH.marks, k = CH.drag, lo = k ? m[k - 1] + 1 : 0, hi = k + 1 < m.length ? m[k + 1] - 1 : CH.x.length - 1;
m[k] = Math.round(Math.max(lo, Math.min(hi, posAt(e))));
chopDraw();
});
u.cv.addEventListener("pointerup", () => { if (CH.drag >= 0) { CH.drag = -1; chopRender(); } });
u.cv.addEventListener("pointerup", () => {
if (CH.dragEnd) { CH.dragEnd = false; chopRender(); }
if (CH.drag >= 0) { CH.drag = -1; chopRender(); }
});
u.cv.addEventListener("dblclick", (e) => { if (CH.x) chopAdd(u.snap.checked ? chopSnap(CH.x, CH.nov, posAt(e), 0.02) : Math.round(posAt(e))); });
u.cv.addEventListener("wheel", (e) => {
if (!CH.x) return;
@@ -3168,13 +3479,17 @@ function chopUI() {
if (k === " ") { e.preventDefault(); if (CH.src && CH.src.whole) chopTap(e); else chopPlay(Math.round(CH.v0), CH.x.length, true); }
else if (k === "Enter" || k === "Escape") { e.preventDefault(); if (CH.src) chopStop(); else chopPlay(Math.round(CH.v0), CH.x.length, true); }
else if (/^[0-9]$/.test(k)) { e.preventDefault(); chopAudition(k === "0" ? 9 : +k - 1); }
else if ((k === "Delete" || k === "Backspace") && CH.sel >= 0) { e.preventDefault(); chopSetMarks(CH.marks.filter((_, i) => i !== CH.sel)); }
else if ((k === "Delete" || k === "Backspace") && CH.sel >= 0) {
e.preventDefault();
chopSetMarks(CH.marks.filter((_, i) => i !== CH.sel), CH.marks.map((_, i) => CH.opt[i]).filter((_, i) => i !== CH.sel));
}
else if ((k === "k" || k === "K") && CH.sel >= 0) { e.preventDefault(); chopKeep(CH.sel); }
else if ((k === "ArrowLeft" || k === "ArrowRight") && CH.sel >= 0) { /* nudge the selected marker: 2 ms, shift 20 ms */
e.preventDefault();
const m = CH.marks.slice();
m[CH.sel] += (k === "ArrowLeft" ? -1 : 1) * Math.round((e.shiftKey ? 0.02 : 0.002) * SMP.RATE);
const keep = CH.sel;
chopSetMarks(m);
chopSetMarks(m, CH.marks.map((_, i) => CH.opt[i]));
CH.sel = keep;
chopRender();
}
@@ -3189,17 +3504,36 @@ function chopUI() {
function chopRender() {
const u = CH.ui;
if (!u) return;
const { all, use, n } = chopUsed(), room = SMP.MAX_DATA * 2, over = n > room;
u.info.textContent = CH.x ? `${CH.name} · ${chSecs(CH.x.length)} · ${all.length} ${t("chopChops")}` : t("chopHelp");
const U = chopUsed(), { all, use, n } = U, room = SMP.MAX_DATA * 2, over = use.reduce((a, q) => a + ((q.end - q.start + 1) >> 1), 0) > SMP.MAX_DATA;
const kept = all.filter((c) => !c.off).length;
u.info.textContent = CH.x ? `${CH.name} · ${chSecs(CH.x.length)} · ${all.length} ${t("chopChops")}` +
(kept < all.length ? ` (${kept} ${t("chopKept")})` : "") : t("chopHelp");
u.meter.value = Math.min(room, n);
u.room.textContent = `${chSecs(n)} / ${chSecs(room)}` + (over ? " " + t("chopTooLong") : "") +
(CH.mode === 0 && all.length > CHOP.MAX ? " " + t("chopTooMany") : "");
u.room.textContent = `${chSecs(n)} / ${chSecs(room)}` + (over ? " " + t("chopTooLong") + " " + t("chopOverHint") : "") +
(CH.mode === 0 && kept > CHOP.MAX ? " " + t("chopTooMany") : "");
u.room.className = over ? "bad" : "dim";
u.fit.disabled = !over;
u.send.forEach((b) => { b.disabled = !use.length || over || smpBusy || !dev || !dev.smp; });
u.list.replaceChildren(...all.map((c, i) => el("button", {
class: "chip" + (i === CH.sel ? " on" : "") + (use.includes(c) ? "" : " off"),
title: `${chSecs(c.start)} · ${chSecs(c.end - c.start)}`, onclick: () => chopAudition(i),
}, `${i + 1}` + (CH.mode === 1 ? "" : i < CHOP.MAX ? " " + noteName(Math.min(127, CH.key0 + i)) : ""))));
u.list.replaceChildren(...all.map((c, i) => { /* a chip per chop: the box keeps it, the rest listens */
const box = el("input", { type: "checkbox", title: t("chopKeep"), onclick: (e) => { e.stopPropagation(); chopKeep(i, box.checked); } });
box.checked = !c.off;
return el("span", {
class: "chip" + (i === CH.sel ? " on" : "") + (use.includes(c) ? "" : " off"),
title: `${chSecs(c.start)} · ${chSecs(c.end - c.start)}` + (c.end < c.full ? ` / ${chSecs(c.full - c.start)}` : ""),
onclick: () => chopAudition(i),
}, box, `${i + 1}` + chopKeyName(U, i));
}));
const c = all[CH.sel]; /* the selected chop's row */
u.selRow.hidden = !c;
if (c) {
const full = c.full - c.start;
u.selName.textContent = `${t("chopSel")} ${CH.sel + 1}${chopKeyName(U, CH.sel)}`;
u.keep.checked = !c.off;
u.len.max = String(Math.max(10, Math.floor(full / SMP.RATE * 1000)));
u.len.value = String(Math.round((c.end - c.start) / SMP.RATE * 1000));
u.lenTxt.textContent = `${chSecs(c.end - c.start)} / ${chSecs(full)}`;
u.full.disabled = c.end >= c.full;
}
chopDraw();
}
@@ -3208,7 +3542,7 @@ async function chopSend(k) {
if (!CH.x || smpBusy) return;
const { use } = chopUsed();
if (!use.length) return;
const zones = chopZones(CH.x, chopChops(), CH.key0, CH.mode, Math.max(0, CH.sel));
const zones = chopZones(CH.x, chopChops(), CH.key0, CH.mode, Math.max(0, CH.sel)); /* (the kept ones) */
smpDraft[k].name = CH.name;
smpDraft[k].files = zones;
renderSamples();
@@ -3937,6 +4271,44 @@ function download(name, obj) {
}
const fileSlug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "patch";
const today = () => new Date().toISOString().slice(0, 10);
/* v6: backup / restore (the work: backupCapture / backupRestore above) */
function bkProgress(key) {
const pr = $("bk-prog");
pr.hidden = false;
return (d, n) => { pr.value = d / n; sayK(key, `${Math.round(100 * d / n)} %`); };
}
function bkReport(e) {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.code === "bkStop" ? "" : e.message);
else report(e);
}
$("bk-save").addEventListener("click", () => op(async () => {
try {
const arc = await backupCapture(rq, dev.info, bkProgress("bkSaving"));
download(`SLOOP-backup-${today()}.json`, arc);
sayK("bkSaved");
} catch (e) { bkReport(e); } finally { $("bk-prog").hidden = true; }
}));
$("bk-load").addEventListener("click", () => { if (dev) $("bk-file").click(); });
$("bk-file").addEventListener("change", async () => {
const f = $("bk-file").files[0];
$("bk-file").value = "";
if (!f || !dev) return;
let file;
try { file = JSON.parse(await f.text()); backupObjects(file); }
catch (e) { sayK("bkBad", e.message); return; }
if (!confirm(t("bkConfirm"))) return;
await op(async () => {
try {
selfLoad();
await backupRestore(rq, file, bkProgress("bkRestoring"));
dev.slotUsed = [null, null, null, null];
renderSlots();
try { await smpInfo(); renderSamples(); } catch (e) { /* shown by the next action */ }
await afterSoundChange("bkRestored");
} catch (e) { bkReport(e); } finally { $("bk-prog").hidden = true; }
});
});
$("libexp1").addEventListener("click", () => {
const p = lib.find((x) => x.id === libSel);
if (p) download(`felucca-patch-${fileSlug(p.name)}.json`, libraryFile("patch", [p], libCtx()));
+136 -33
View File
@@ -42,12 +42,16 @@
pre { color: var(--dim); font-size: 11px; white-space: pre-wrap; margin-top: 12px; max-height: 160px; overflow: auto; }
hr { border: 0; border-top: 1px solid var(--line); margin: 28px 0 18px; }
.ed { display: inline-block; margin: 8px 0 0; padding: 10px 14px; background: var(--tile); text-decoration: none; }
details { margin: 22px 0 0; } summary { cursor: pointer; font-weight: 600; }
button#stock-go { font: 600 14px/1 inherit; font-family: inherit; background: var(--tile); color: var(--fg); border: 1px solid var(--line);
padding: 12px 16px; cursor: pointer; }
button#stock-go:disabled { color: var(--dim); cursor: default; }
@media (max-width: 420px) { .tiles { grid-template-columns: repeat(2, 1fr); } .logo svg { width: 170px; } }
</style>
</head>
<body>
<main>
<div class="top"><div class="logo"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 260" width="760" height="260" role="img" aria-label="SLOOP" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTo2MThlZGZkNC1mNWMwLTRiODYtYjUwNy1hYWMxYTgwMGNjNmUAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaEaCttkEwLj6pcDfPYG3hbcAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDo4MTI3OWE0NS1lN2FjLTQ3ZmEtOWU3OC0zYjVmODc1NjFjMTVscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoBe1O7TBl0aAWSCXfah2z9AAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggkERAc1MCSOiA7AsNa0NSkGyI3c5Eo9Qk/A5Gnihj/7akZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaB+VQR5SI+Xn2UYJEFqeFVQAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCB9PxBfbdmSPDSRpYcYOtkvsm9+fsJn4Xgd5LP5lMq5UWRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBi0Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjYxOGVkZmQ0LWY1YzAtNGI4Ni1iNTA3LWFhYzFhODAwY2M2ZS9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjY3YmIxMzljLWUxMzEtNDBkMi05Y2Y0LWE1NTdmMWI4MGQzZHJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCCQREBzUwJI6IDsCw1rQ1KQbIjdzkSj1CT8DkaeKGP/tqJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggc6pv/aUneyqtzU2lIK0VVY/Xc2i/wg2ElW5rRwBMq+2iY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggTMUT+tohvmxrdse5RAGBg0iMBmrg0Pk+w/1mUeOrG+90Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated
<div class="top"><div class="logo"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 260" width="760" height="260" role="img" aria-label="SLOOP">
<rect width="760" height="260" fill="#000"/>
<path d="M59.29 200.71 A100.00 100.00 0 1 1 200.71 200.71" fill="none" stroke="#F2F2F2" stroke-width="12" stroke-linecap="round"/>
<rect x="95.00" y="46.00" width="10" height="136.00" rx="5" fill="#F2F2F2"/>
@@ -67,11 +71,12 @@
</div><button class="lang" id="lang"></button></div>
<div class="strip"><i></i><i></i><i></i><i></i></div>
<h1>Firmware for the M-VAVE FM-1</h1>
<p class="lead">A groovebox you play live: four tracks — three synths and a drum machine — 9 synth engines, 54 sounds, 34 drum kits from 808 to techno, afro and ambient, your own samples, 16 punch-in effects. House, techno, hip-hop, drum &amp; bass, synthwave, lo-fi, ambient: make what you want. No factory patterns, nothing to load: everything you hear, you play.</p>
<p class="lead">A groovebox you play live: four tracks — three synths and a drum machine — 9 synth engines, 68 sounds, 37 drum kits from 808 to techno, amapiano and ambient, your own samples, 16 punch-in effects. House, techno, hip-hop, drum &amp; bass, synthwave, lo-fi, ambient: make what you want. No factory patterns, nothing to load: everything you hear, you play.</p>
<div class="tiles">
<div class="tile" style="--c: var(--blue)"><b>54</b><span>sounds, 9 engines, your samples</span></div>
<div class="tile" style="--c: var(--green)"><b>34</b><span>drum kits, 909 to afro</span></div>
<div class="tile" style="--c: var(--blue)"><b>68</b><span>sounds, 9 engines, your samples</span></div>
<div class="tile" style="--c: var(--green)"><b>37</b><span>drum kits, 909 to afro</span></div>
<div class="tile" style="--c: var(--yellow)"><b>16</b><span>punch-in fx: hold fx + key</span></div>
<div class="tile" style="--c: var(--orange)"><b>rec</b><span>no click: the loop follows you</span></div>
</div>
@@ -87,8 +92,17 @@
<p class="small" data-t="beta"></p>
<p class="small"><span data-t="brick"></span>
<a href="https://github.com/kurogedelic/FM-1-transporter" target="_blank" rel="noopener">FM-1-transporter</a></p>
<p class="small" data-t="back"></p>
<p class="small"><a href="https://www.m-vave.com/download" target="_blank" rel="noopener">www.m-vave.com/download</a></p>
<details>
<summary data-t="stockTitle"></summary>
<p class="small" data-t="stockHelp"></p>
<p class="small"><a href="https://www.m-vave.com/download" target="_blank" rel="noopener">www.m-vave.com/download</a></p>
<p class="small" data-t="stockBackup"></p>
<p><a class="ed" href="../editor/" data-t="stockEditor"></a></p>
<p class="small"><label><input id="stock-saved" type="checkbox"> <span data-t="stockSaved"></span></label></p>
<p class="small"><label><span data-t="stockFile"></span><br><input id="stock-file" type="file" accept=".fwsc"></label></p>
<p><button id="stock-go" disabled data-t="stockGo"></button></p>
<p class="small" data-t="back"></p>
</details>
<p class="small">SLOOP is based on Felucca by Leo Kuroshita (@kurogedelic), <a href="https://hugelton.com" target="_blank" rel="noopener">Hügelton Instruments</a>.
Hold OCT− alone while switching on for USB rescue.<br>
Font: Terminus (Dimitar Toshkov Zhekov, SIL OFL 1.1). Samples: Versilian Studios VSCO-2 Community Edition and VCSL (CC0 1.0), and the Hügelton Sample Pack (© Hügelton Instruments, not CC0).<br>
@@ -123,6 +137,24 @@ function logicalImage(fwsc) {
return out;
}
// The official FM-1 V15 (M-VAVE Downloads -> PC Firmware -> FM-1 V15, FM-1.fwsc), for the return to the
// official firmware: only that exact file is accepted (its SHA-256 pins every byte: the loader, the app, the
// layout; the name of the file proves nothing). The digest is the one Felucca 1.0 pins.
const STOCK_V15_SHA256 = "db1642b2b6fa5c2cccb11ffd13878068bb28601678d3644049f99dc40e7edb8a";
const STOCK_V15_SIZE = 699956;
const STOCK_V15_PRODUCT = "FM-1_015";
async function sha256hex(bytes) {
const d = await crypto.subtle.digest("SHA-256", bytes);
return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, "0")).join("");
}
async function validateStockPackage(bytes) {
if (bytes.length !== STOCK_V15_SIZE || await sha256hex(bytes) !== STOCK_V15_SHA256 || productOf(bytes) !== STOCK_V15_PRODUCT)
throw new Error("select the unmodified official FM-1 V15 file (FM-1.fwsc)");
return { product: STOCK_V15_PRODUCT, image: logicalImage(bytes) };
}
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
//
@@ -335,15 +367,29 @@ class Updater {
return s2;
}
// resume: the device is already in update mode (loader) -> true when the write finished
async resume(image, onStep) {
// resume: the device is already in update mode (loader) -> true when the write finished. Only SLOOP's
// own loader is resumed, except for the return to the official firmware (opts.product: the official
// package, its identity checked once the FM-1 is back, after Felucca 1.0): that one is the official
// loader's own image, as M-UPGRADE would write it
async resume(image, onStep, opts = {}) {
const ota = await this.find(IS_OTA);
if (!ota) return false;
if (!OUR_LOADER(ota.id)) {
if (!OUR_LOADER(ota.id) && !opts.product) {
ota.link.close();
throw fail("foreign", `the FM-1 is in the update mode of another firmware (${ota.id.text}): finish that update with its own updater`, ota.id.text);
}
return (await this.write(ota, image, onStep || (() => {}))).finished;
const step = onStep || (() => {});
if (!(await this.write(ota, image, step)).finished) return false;
if (opts.product) {
step("reboot");
await sleep(3000);
const back = await this.waitFor((id) => !IS_OTA(id), 40000);
if (!back) throw fail("noreturn", "the FM-1 did not come back after the write: power-cycle it");
back.link.close();
if (back.id.text !== opts.product) throw fail("mismatch", `written, but the FM-1 reports ${back.id.text}`, back.id.text);
step("done", back.id.text);
}
return true;
}
}
@@ -373,6 +419,15 @@ const TEXT = {
badpkg: "インストールするファイルが壊れています。ページを再読み込みしてください。",
leave: "書き込み中です。ページを閉じないでください。",
license: "GPL-3.0、無保証。ソース:",
stockTitle: "公式ファームウェア(V15)に戻す",
stockHelp: "M-VAVE のサイトから公式の FM-1 V15 をダウンロードし、中の FM-1.fwsc(変更していないもの)を選んでください。ファイルはこのブラウザの中で確認され、どこにも送られません。",
stockBackup: "公式ファームウェアは SLOOP の曲・プロジェクト・サンプルを開けません。先にエディタでバックアップを保存してください(Projects → Backup)。SLOOP を入れ直せば、エディタから復元できます。",
stockEditor: "エディタを開いてバックアップする", stockSaved: "バックアップをパソコンに保存しました",
stockFile: "公式の FM-1.fwsc", stockGo: "公式 V15 をインストール",
stockValid: "公式 V15 を確認しました", stockBad: "公式 V15 ではありません: ",
stockConfirm: "FM-1 に公式 V15 をインストールします。SLOOP の曲は公式ファームウェアでは開けません。バックアップは保存しましたか?",
stockFinish: "FM-1 は SLOOP の書き込みモードです。先に「インストール」で SLOOP の書き込みを終えてから、公式 V15 に戻してください。",
back: "M-VAVE のアップデーター M-UPGRADE(Downloads → PC Software)でも戻せます。FM-1 が見つからない場合は、MIDI を使う他のアプリとブラウザのタブを閉じてください。",
},
en: {
intro: "Connect the FM-1 by USB. (Works in Chrome or Edge.)",
@@ -398,6 +453,15 @@ const TEXT = {
badpkg: "The file to install is damaged. Reload the page.",
leave: "Writing. Do not close the page.",
license: "GPL-3.0, no warranty. Source:",
stockTitle: "Return to the official firmware (V15)",
stockHelp: "Download the official FM-1 V15 from M-VAVE and select the FM-1.fwsc inside it, unmodified. The file is checked in this browser; it is not sent anywhere.",
stockBackup: "The official firmware cannot open SLOOP's music, projects or samples. Save a backup with the editor first (Projects → Backup); reinstall SLOOP and restore it from the editor whenever you want them back.",
stockEditor: "Open the editor to back up", stockSaved: "I saved a backup on this computer",
stockFile: "The official FM-1.fwsc", stockGo: "Install the official V15",
stockValid: "Official V15 verified", stockBad: "Not the official V15: ",
stockConfirm: "Install the official V15 on the FM-1? The official firmware cannot open SLOOP's music. Did you save a backup?",
stockFinish: "The FM-1 is in SLOOP's update mode. Press Install to finish the SLOOP update first, then return to the official V15.",
back: "M-VAVE's own updater, M-UPGRADE (Downloads → PC Software), works too. If it does not find the FM-1, close every other app and browser tab that uses MIDI.",
},
};
let lang = (navigator.language || "en").toLowerCase().startsWith("ja") ? "ja" : "en";
@@ -415,9 +479,15 @@ const sayK = (k, arg = "") => { lastKey = k; lastArg = arg; $("status").textCont
const say = (txt) => { lastKey = null; $("status").textContent = txt; };
const log = (t) => { $("log").textContent += t + "\n"; };
let image = null;
const meta = {"version": "2.2", "product": "FM-1_900", "pkg": "../../firmware/sloop-2.2.fwsc", "sha256": "154bd2206b8963fbc3aaf654324fd10999ff67edcd70fd7b493848e2cfc7c1ce"};
const meta = {"version": "2.3", "product": "FM-1_900", "pkg": "../../firmware/sloop-2.3.fwsc", "sha256": "f4866903ca3304a2c2c788ef6929d3bb0dcf8468c90b61495e038e97ffb1fa00"};
let writing = false;
let writing = false, stock = null;
const lockAll = (on) => {
writing = on;
$("go").disabled = on || !image;
$("stock-go").disabled = on || !stock || !$("stock-saved").checked;
$("stock-file").disabled = on;
};
window.addEventListener("beforeunload", (e) => { if (writing) { e.preventDefault(); e.returnValue = t("leave"); } });
(async () => {
@@ -433,28 +503,34 @@ window.addEventListener("beforeunload", (e) => { if (writing) { e.preventDefault
}
image = logicalImage(pkg);
say(`SLOOP ${meta.version}`);
$("go").disabled = false;
lockAll(writing);
} catch (e) { sayK("loadfail", e.message); }
})();
const total = 74 + 1179; /* reads: step 1, step 2 (head + app area, SLOOP 2.0 loader) */
const step = (k, a) => {
log(`${k} ${a ?? ""}`);
if (k === "start") sayK("start");
if (k === "verify") { sayK("verify"); $("bar").value = Math.min(100, (a / total) * 100); }
if (k === "loader") sayK("loader");
if (k === "write") { sayK("write"); $("bar").value = Math.min(100, ((74 + a) / total) * 100); }
if (k === "reboot") sayK("reboot");
if (k === "done") { $("bar").value = 100; sayK("done"); }
};
const failed = (e) => {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.detail || "");
else sayK("error", e && e.message);
log(String(e && e.stack || e));
};
$("go").addEventListener("click", async () => {
$("go").disabled = true;
if (writing) return;
lockAll(true);
let midi;
try { midi = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { sayK("denied"); $("go").disabled = false; return; }
writing = true;
catch (e) { sayK("denied"); lockAll(false); return; }
try {
const up = new Updater(midi, log);
const total = 74 + 1179; /* reads: step 1, step 2 (head + app area, SLOOP 2.0 loader) */
const step = (k, a) => {
log(`${k} ${a ?? ""}`);
if (k === "start") sayK("start");
if (k === "verify") { sayK("verify"); $("bar").value = (a / total) * 100; }
if (k === "loader") sayK("loader");
if (k === "write") { sayK("write"); $("bar").value = ((74 + a) / total) * 100; }
if (k === "reboot") sayK("reboot");
if (k === "done") { $("bar").value = 100; sayK("done"); }
};
const ota = await up.find((id) => /^ota-/i.test(id.model));
if (ota) {
ota.link.close();
@@ -462,13 +538,40 @@ $("go").addEventListener("click", async () => {
} else {
await up.install(image, meta.product, step);
}
} catch (e) {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.detail || "");
else sayK("error", e && e.message);
log(String(e && e.stack || e));
}
writing = false;
$("go").disabled = false;
} catch (e) { failed(e); }
lockAll(false);
});
/* back to the official V15 (after Felucca 1.0): only the exact official file, a backup first (the editor),
through the same update path as M-UPGRADE; a device left in the official updater's mode is finished */
$("stock-saved").addEventListener("change", () => lockAll(writing));
$("stock-file").addEventListener("change", async () => {
const f = $("stock-file").files[0];
stock = null;
lockAll(writing);
if (!f) return;
try { stock = await validateStockPackage(new Uint8Array(await f.arrayBuffer())); sayK("stockValid"); }
catch (e) { sayK("stockBad", e.message); }
lockAll(writing);
});
$("stock-go").addEventListener("click", async () => {
if (writing || !stock || !$("stock-saved").checked || !confirm(t("stockConfirm"))) return;
lockAll(true);
let midi;
try { midi = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { sayK("denied"); lockAll(false); return; }
try {
const up = new Updater(midi, log);
const ota = await up.find((id) => /^ota-/i.test(id.model));
if (ota) {
ota.link.close();
if (OUR_LOADER(ota.id)) sayK("stockFinish"); /* SLOOP's loader: finish SLOOP first (Install) */
else sayK((await up.resume(stock.image, step, { product: stock.product })) ? "done" : "stopped");
} else {
await up.install(stock.image, stock.product, step);
}
} catch (e) { failed(e); }
lockAll(false);
});
</script>
</body>
+125 -79
View File
@@ -17,22 +17,36 @@
*
* fm1_input_scan() runs one full frame (11 columns, ~0.6 ms) and calls
* FM1_INPUT_IDLE() while it waits.
* Keys/buttons: integrating debounce, asymmetric: a press counts after FM1_PRESS closed
* frames (~3 ms: notes are played in time), a release once the count is back to 0 (up to
* FM1_DEBOUNCE frames), so contact bounce never retriggers.
* Encoders: quadrature decoder (2-sample filter, + = clockwise) with detent
* counting: states an encoder rests in for >= FM1_REST_FRAMES are learned, and
* a step is emitted only on reaching a rest state after >= 2 net transitions.
* One click = one step at any speed, whether a detent is a half or a full
* quadrature cycle. fm1_enc_take() returns the steps.
* LEDs: set fm1_led[col] (packed row bits, bit1 PA5..bit4 PA8); they are lit
* while that column is selected; fm1_led_dim[col] the same, lit one frame in four
* (dim). fm1_led_key/btn helpers address them by id.
* Keys/buttons (as Felucca 1.0): debounced as soon as their column is read. A press counts after
* FM1_DEB_PRESS frames closed in a row (1.1-2.2 ms: the matrix has diodes and no ghosting, so a closed
* sample is a closed key; two in a row keep one stray sample from playing a note), a release after
* FM1_DEB_RELEASE frames open in a row (~9 ms): a contact bouncing open on the way down, or chattering
* on the way up, never ends a note early or plays it twice.
* Encoders: quadrature decoder (2-sample filter, + = clockwise) with detent counting, as
* Felucca 1.0 reworked it (its #23, "knobs skipping or jumping"): an FM-1 detent is one full
* quadrature cycle (4 transitions) and the knob rests in one state, the one seen at power-on
* (relearned only after FM1_REST_FRAMES, ~1 s, parked elsewhere). Steps are emitted on arriving
* back at it, the net transitions rounded to whole cycles (>= 2 counts one: a lost transition or
* two is forgiven; a two-state jump counts on in the direction of travel). One click = one step
* at any speed; bounce and back-and-forth cancel out. Never a second rest state: a knob held
* mid-click taught the complement as a rest and every click counted twice, and short mid-click
* pauses of a slow turn taught the mid states and the knob went dead (the 0.9 learner).
* fm1_enc_take() returns the steps.
* LEDs: set fm1_led[col] (packed row bits, bit1 PA5..bit4 PA8); they are lit while that column is
* selected (one tick, ~95 us a frame). Two dim layers (fm1_input_tick only), after Felucca 1.0.1 (its
* #35: the eye is logarithmic, an LED lit 1/4 or 1/6 of the time reads as nearly lit): a short pulse on
* every frame (~910 Hz, no flicker) at the start of the column's next tick, riding on the 595 shift of
* the next column (its outputs change only at the latch, so the pulse stays on column p and the key
* read before it is unchanged). fm1_led_dim[col]: the glow (landmarks, notes under tiles), FM1_GLOW_NS
* (~1/24 of a lit LED); fm1_led_bg[col]: the backlight (menu LIGHTS), fm1_led_bg_ns, shorter. TIMER4
* times the pulses bit by bit; only a pulse longer than the whole shift waits for the rest. An LED in
* several layers takes the brightest. fm1_led_key/btn helpers address them by id.
*/
#pragma once
#include <stdint.h>
#include "fm1_time.h"
#include "fm1_gpio.h"
#include "fm1_cc.h"
#ifndef FM1_INPUT_IDLE
#define FM1_INPUT_IDLE() ((void)0)
@@ -40,10 +54,10 @@
#ifndef FM1_LED_US
#define FM1_LED_US 40u /* LED on-time per column (brightness vs scan rate) */
#endif
#define FM1_DEBOUNCE 8u /* frames (~1.1 ms each in the IRQ scan): a release */
#define FM1_PRESS 3u /* a press: fast (keys are played in time), still 3 frames sure */
#define FM1_DEB_PRESS 2u /* frames closed in a row: a press (a frame = 11 ticks, ~1.1 ms) */
#define FM1_DEB_RELEASE 8u /* frames open in a row: a release (~9 ms) */
#define FM1_SETTLE_US 10u
#define FM1_REST_FRAMES 40u /* ~25 ms still = a detent position */
#define FM1_REST_FRAMES 900u /* ~1 s still off the detent state: that is the detent (power-on) */
#define FM1_NCOL 11u
#define FM1_NKEY 41u /* ids: 0..13 buttons, 14..40 note keys */
#define FM1_NENC 7u
@@ -75,17 +89,20 @@ static volatile struct {
uint8_t raw[FM1_NCOL]; /* last frame, packed rows, 1 = closed */
uint8_t cnt[FM1_NKEY];
uint8_t enc_prev[FM1_NENC], enc_last[FM1_NENC];
uint8_t enc_rest[FM1_NENC]; /* learned rest (detent) states, bit per state */
uint8_t enc_still[FM1_NENC]; /* frames since the last state change */
uint8_t enc_rest[FM1_NENC]; /* the detent state (0..3) */
uint16_t enc_still[FM1_NENC]; /* frames since the last state change */
int8_t enc_sub[FM1_NENC]; /* net transitions since the last rest state */
int16_t enc_steps[FM1_NENC]; /* + = clockwise */
uint32_t frames;
} fm1_in;
static uint8_t fm1_led[FM1_NCOL];
#ifndef FM1_LED_DIM_MASK
#define FM1_LED_DIM_MASK 3u /* dim LEDs: lit one scan frame in (mask + 1), ~225 Hz, no flicker */
#ifndef FM1_GLOW_NS
#define FM1_GLOW_NS 4000u /* the glow pulse a frame (ns); a lit LED ~95 us: ~1/24 the brightness */
#endif
static uint8_t fm1_led_dim[FM1_NCOL]; /* same layout as fm1_led: half-light marks */
#define FM1__NS_T(ns) (((uint32_t)(ns) * FM1_TICKS_PER_US + 500u) / 1000u) /* ns -> TIMER4 ticks */
static uint8_t fm1_led_dim[FM1_NCOL]; /* same layout as fm1_led: the glow */
static uint8_t fm1_led_bg[FM1_NCOL]; /* same layout: the backlight (labels readable in the dark) */
static volatile uint16_t fm1_led_bg_ns; /* the backlight pulse a frame (ns), 0 = off (menu LIGHTS) */
static void fm1__led_lines(uint32_t rowmask)
{
@@ -98,19 +115,26 @@ static void fm1__led_lines(uint32_t rowmask)
}
}
static void fm1__sr_bit(uint32_t w, uint32_t i) /* bit i of w (msb first) into the 595 */
{
if (w & (0x8000u >> i))
FM1_PR(FM1_PA, FM1_OUT) |= 1u << 4;
else
FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 4);
FM1_PR(FM1_PA, FM1_OUT) |= 1u << 3; /* read-modify-write per edge: each SFR write is */
FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 3); /* far slower than the 595 needs */
}
static void fm1__sr_latch(void) /* the outputs change here only */
{
FM1_PR(FM1_PA, FM1_OUT) |= 1u << 1;
FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 1);
}
static void fm1__sr_word(uint32_t w)
{
uint32_t i;
for (i = 0; i < 16u; i++) {
if (w & (0x8000u >> i))
FM1_PR(FM1_PA, FM1_OUT) |= 1u << 4;
else
FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 4);
FM1_PR(FM1_PA, FM1_OUT) |= 1u << 3; /* each SFR write is far slower than the 595 needs */
FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 3);
}
FM1_PR(FM1_PA, FM1_OUT) |= 1u << 1;
FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 1);
for (i = 0; i < 16u; i++)
fm1__sr_bit(w, i);
fm1__sr_latch();
}
static uint32_t fm1__rows(void)
@@ -161,34 +185,34 @@ static void fm1_input_init(void)
static void fm1__key(uint32_t id, uint32_t closed)
{
volatile uint8_t *c = &fm1_in.cnt[id];
uint32_t on;
if (closed) {
if (*c < FM1_DEBOUNCE)
(*c)++;
} else if (*c) {
(*c)--;
}
if (closed && *c >= FM1_PRESS)
on = 1;
else if (*c == 0)
on = 0;
else
uint32_t note = id >= 14u, bit = note ? 1u << (id - 14u) : 1u << id;
uint32_t on = ((note ? fm1_in.notes : fm1_in.buttons) & bit) != 0u;
if (closed == on) { /* agrees with the state: start over */
*c = 0;
return;
if (id >= 14u) {
if (on) {
if (!(fm1_in.notes & (1u << (id - 14u))))
fm1_in.notes_pressed |= 1u << (id - 14u);
fm1_in.notes |= 1u << (id - 14u);
}
else
fm1_in.notes &= ~(1u << (id - 14u));
} else if (on != ((fm1_in.buttons >> id) & 1u)) {
fm1_in.buttons ^= 1u << id;
if (on)
fm1_in.pressed |= 1u << id;
else
fm1_in.released |= 1u << id;
}
if (++*c < (on ? FM1_DEB_RELEASE : FM1_DEB_PRESS))
return;
*c = 0;
if (note) {
if (!on)
fm1_in.notes_pressed |= bit;
fm1_in.notes ^= bit;
} else {
fm1_in.buttons ^= bit;
if (!on)
fm1_in.pressed |= bit;
else
fm1_in.released |= bit;
}
}
static void fm1__keys(uint32_t p) /* the keys of column p, just read */
{
uint32_t r, raw = fm1_in.raw[p];
for (r = 1; r < 5u; r++)
if (FM1_KEYMAP[r][p] >= 0)
fm1__key((uint32_t)FM1_KEYMAP[r][p], (raw >> r) & 1u);
}
static void fm1__frame(void);
@@ -201,7 +225,8 @@ static void fm1_input_scan(void)
fm1__sr_word(0xFFFFu ^ (1u << p) ^ (p < 2u ? 1u << (11u + p) : 0u));
fm1__wait(FM1_SETTLE_US);
fm1_in.raw[p] = (uint8_t)fm1__rows();
fm1__led_lines(fm1_led[p] | ((fm1_in.frames & FM1_LED_DIM_MASK) ? 0u : fm1_led_dim[p]));
fm1__keys(p);
fm1__led_lines(fm1_led[p]);
fm1__wait(FM1_LED_US);
}
fm1__led_lines(0);
@@ -210,11 +235,7 @@ static void fm1_input_scan(void)
static void fm1__frame(void)
{
uint32_t p, r, e;
for (p = 0; p < FM1_NCOL; p++)
for (r = 1; r < 5u; r++)
if (FM1_KEYMAP[r][p] >= 0)
fm1__key((uint32_t)FM1_KEYMAP[r][p], (fm1_in.raw[p] >> r) & 1u);
uint32_t e; /* (the keys: fm1__keys, as each column is read) */
for (e = 0; e < FM1_NENC; e++) { /* quadrature decoder + detents */
const uint8_t *m = FM1_ENC[e];
uint32_t cur = ((fm1_in.raw[m[0]] >> m[1]) & 1u) << 1 | ((fm1_in.raw[m[2]] >> m[3]) & 1u);
@@ -227,15 +248,12 @@ static void fm1__frame(void)
}
if (fm1_in.enc_prev[e] == 0xFF) { /* first frame: the knob rests here */
fm1_in.enc_prev[e] = (uint8_t)cur;
fm1_in.enc_rest[e] = (uint8_t)(1u << cur);
fm1_in.enc_rest[e] = (uint8_t)cur;
}
if (fm1_in.enc_still[e] < 255u && ++fm1_in.enc_still[e] == FM1_REST_FRAMES) {
/* learn detent states: one state, or a complementary pair (00/11 or
* 01/10). Anything else restarts the set; with 3-4 rest states every
* arrival would look like a detent with |sub| < 2. */
uint32_t r = fm1_in.enc_rest[e], bit = 1u << cur, comp = 1u << (cur ^ 3u);
if (!(r & bit))
fm1_in.enc_rest[e] = (uint8_t)(r == comp ? (r | bit) : bit);
if (fm1_in.enc_still[e] < 0xFFFFu && ++fm1_in.enc_still[e] == FM1_REST_FRAMES &&
cur != fm1_in.enc_rest[e]) {
fm1_in.enc_rest[e] = (uint8_t)cur; /* parked ~1 s off the detent state (held at power-on): */
*sub = 0; /* that is the detent. Never a second state (see top) */
}
if (cur == fm1_in.enc_prev[e])
continue;
@@ -244,28 +262,56 @@ static void fm1__frame(void)
(*sub)++;
else if ((0x2814u >> idx) & 1u)
(*sub)--;
else if (*sub > 0) /* two states in one sample: a fast turn, */
*sub = (int8_t)(*sub + 2); /* the way it was going */
else if (*sub < 0)
*sub = (int8_t)(*sub - 2);
fm1_in.enc_prev[e] = (uint8_t)cur;
if ((fm1_in.enc_rest[e] >> cur) & 1u) { /* back on a detent */
if (*sub >= 2)
fm1_in.enc_steps[e]++;
else if (*sub <= -2)
fm1_in.enc_steps[e]--;
if (*sub > 100 || *sub < -100)
*sub = 0; /* (never off the detent that long) */
if (cur == fm1_in.enc_rest[e]) { /* back on the detent: whole cycles, a lost transition */
int32_t n = *sub < 0 ? -*sub : *sub; /* or two forgiven (one click = 4 transitions) */
n = n >= 2 ? (n + 2) / 4 : 0;
fm1_in.enc_steps[e] = (int16_t)(fm1_in.enc_steps[e] + (*sub < 0 ? -n : n));
*sub = 0;
}
}
fm1_in.frames++;
}
/* one column per call, from a timer ISR (see top) */
/* one column per call, from a timer ISR (see top). The dim pulses of column p ride on the shift of
* column n: the lines go lit | glow | backlight of p, each layer ends when its time is up (TIMER4,
* checked after every bit), and the latch comes with the lines dark. */
static uint8_t fm1__tick_col;
static void fm1_input_tick(void)
{
uint32_t p = fm1__tick_col, n = p + 1u == FM1_NCOL ? 0u : p + 1u;
uint32_t p = fm1__tick_col, n = p + 1u == FM1_NCOL ? 0u : p + 1u, i;
uint32_t w = 0xFFFFu ^ (1u << n) ^ (n < 2u ? 1u << (11u + n) : 0u);
uint32_t lit = fm1_led[p], a = fm1_led_dim[p] & ~lit, b = fm1_led_bg[p] & ~lit & ~a;
uint32_t ta = a ? FM1__NS_T(FM1_GLOW_NS) : 0u, tb = b ? FM1__NS_T(fm1_led_bg_ns) : 0u;
uint32_t tmax = ta > tb ? ta : tb;
fm1__led_lines(0);
fm1_in.raw[p] = (uint8_t)fm1__rows(); /* column p has been latched one tick */
fm1__sr_word(0xFFFFu ^ (1u << n) ^ (n < 2u ? 1u << (11u + n) : 0u));
fm1__led_lines(fm1_led[n] | ((fm1_in.frames & FM1_LED_DIM_MASK) ? 0u : fm1_led_dim[n]));
fm1_in.raw[p] = (uint8_t)fm1__rows(); /* column p has been latched one tick (the lines dark) */
if (tmax) {
uint32_t t0 = fm1_ticks(), cur = lit | a | (tb ? b : 0u), on, d;
fm1__led_lines(cur); /* (the 595 still drives column p) */
for (i = 0; i < 16u || cur; i++) { /* the shift; then wait if the pulse is longer */
if (i < 16u)
fm1__sr_bit(w, i);
d = fm1_ticks() - t0;
on = d < tmax ? lit | (d < ta ? a : 0u) | (d < tb ? b : 0u) : 0u;
if (on != cur) {
fm1__led_lines(on);
cur = on;
}
}
fm1__sr_latch(); /* column n, the lines dark */
} else {
fm1__sr_word(w);
}
fm1__led_lines(fm1_led[n]);
fm1__tick_col = (uint8_t)n;
fm1__keys(p); /* its keys now: no wait for the frame's end */
if (n == 0u)
fm1__frame();
}
+3 -1
View File
@@ -6,7 +6,9 @@
*
* fm1_uart1_midi_init(ring, len) len a power of two, ring aligned 16;
* before TIMER5 starts (PORTH RMW)
* fm1_uart1_rx_take() bytes DMA'd since the last call
* fm1_uart1_rx_take() bytes DMA'd since the last call; clears the
* pendings. A polled tally that can miss a byte:
* src/midi_uart.c reads the ring by content
*/
#pragma once
#include <stdint.h>
+14
View File
@@ -12,6 +12,8 @@
* EP DMA: fm1_usb_ep0_buf, fm1_usb_ep_txbuf / _rxbuf,
* fm1_usb_ep0_send / fm1_usb_ep_send (csync first),
* fm1_usb_rx_sync (ssync before reading an RX buffer)
* EP4 (own slots): fm1_usb_ep4_txbuf, fm1_usb_ep4_send (csync first);
* isochronous mode is TXCSR2 bit 6 through the SIE (usb.c)
* fm1_usb_ep_enable(m) CON0 &= ~(m << 19), m = bit per endpoint
* fm1_usb_sof_take() SOF pending -> clear, 1
* No IRQ: everything is polled (usb_poll from the TIMER5 ISR). */
@@ -25,6 +27,8 @@
#define FM1_USB_EP0_ADR (*(volatile uint32_t *)0x11818u)
#define FM1_USB_EP_TADR(n) (*(volatile uint32_t *)(0x1181Cu + 8u * ((n) - 1u))) /* EP1..3 */
#define FM1_USB_EP_RADR(n) (*(volatile uint32_t *)(0x11820u + 8u * ((n) - 1u))) /* EP1..3 */
#define FM1_USB_EP4_CNT (*(volatile uint32_t *)0x11834u)
#define FM1_USB_EP4_TADR (*(volatile uint32_t *)0x11838u)
#define FM1_USB_EP4_RADR (*(volatile uint32_t *)0x1183Cu)
#define FM1_USB_IO_CON0 (*(volatile uint32_t *)0x51000u)
#define FM1_CLK_CON1 (*(volatile uint32_t *)0x10010u)
@@ -91,6 +95,16 @@ FM1_INLINE void fm1_usb_ep_send(uint32_t ep, void *p, uint32_t n)
FM1_USB_EP_TADR(ep) = (uint32_t)(uintptr_t)p;
FM1_USB_EP_CNT(ep) = n;
}
/* EP4 IN (the USB audio stream, isochronous): its DMA address and count have their own
* registers (SDK usb_set_dma_taddr / usb_write_ep_cnt, id 0, ep 4) (after Felucca 1.0) */
FM1_INLINE void fm1_usb_ep4_txbuf(void *p) { FM1_USB_EP4_TADR = (uint32_t)(uintptr_t)p; }
FM1_INLINE void fm1_usb_ep4_send(void *p, uint32_t n)
{
__asm__ volatile("csync" ::: "memory");
FM1_USB_EP4_TADR = (uint32_t)(uintptr_t)p;
FM1_USB_EP4_CNT = n;
__asm__ volatile("csync" ::: "memory");
}
FM1_INLINE void fm1_usb_rx_sync(void) { __asm__ volatile("ssync" ::: "memory"); }
FM1_INLINE void fm1_usb_ep_enable(uint32_t eps) { FM1_USB_CON0 &= ~(eps << 19); }
+24 -43
View File
@@ -18,6 +18,7 @@ struct felucca_dbg {
uint32_t prev_stage, prev_page, prev_home, prev_rst, prev_frames; /* as found at boot */
} felucca_dbg __attribute__((section(".noinit")));
static volatile uint32_t audio_halves, audio_max_us;
static volatile uint32_t t5_nested_ticks; /* TIMER4 ticks TIMER5 spent nested in this ISR (main.c) */
#define SCOPE_N 512u
static int16_t scope_buf[SCOPE_N];
static uint32_t scope_w;
@@ -26,6 +27,9 @@ static void audio_block(int32_t *out, uint32_t n) /* mix (fx.c), then Q15
{
uint32_t i;
mix_block(out, n);
#if FELUCCA_UAC
uac_tap(usb_full_now ? usb_out : out, n); /* the USB audio input: the master output, or at full level */
#endif
for (i = 0; i < n; i++) {
if (i & 1u)
scope_buf[scope_w++ & (SCOPE_N - 1u)] = (int16_t)out[2u * i];
@@ -34,51 +38,19 @@ static void audio_block(int32_t *out, uint32_t n) /* mix (fx.c), then Q15
}
}
/* overload: a half that took > 85 % of its time sheds one voice before the
* next one, over all parts: the quietest releasing voice fades out over the next
* block (voice_kill), else the oldest held one goes into its release (stopped by
* a later shed if still needed). The only held voice is never touched, so a dense
* chord on a heavy engine thins out instead of starving the CPU. */
/* overload: shed_voice (voice.c) */
static volatile uint8_t shed_req;
static uint32_t shed_count;
static void shed_voice(void)
{
uint32_t p, i, ngate = 0;
voice_t *best = 0;
for (p = 0; p < NPART; p++)
for (i = 0; i < NVOICE; i++) {
voice_t *v = &trk[p].v[i];
if (v->active && !v->gate && v->stage != 4u && (!best || v->env < best->env))
best = v;
}
if (best) {
voice_kill(best);
shed_count++;
return;
}
for (p = 0; p < NPART; p++)
for (i = 0; i < NVOICE; i++) {
voice_t *v = &trk[p].v[i];
if (v->active && v->gate) {
ngate++;
if (!best || v->age < best->age)
best = v;
}
}
if (ngate > 1u) {
best->gate = 0;
best->stage = 3;
shed_count++;
}
}
static uint8_t shed_over; /* bit k: the half k halves ago was over 85 % */
void fm1_alnk0_irq(void) /* via isr_alnk0 (hal/fm1_isr.S) */
{
uint8_t p = fm1_audio_pending();
uint32_t t0 = fm1_ticks();
uint8_t p;
uint32_t t0;
felucca_dbg.in_audio = 1; /* first: TIMER5 nests from here on (main.c) */
p = fm1_audio_pending();
t0 = fm1_ticks();
t5_nested_ticks = 0;
fm1_audio_ack_aux(p);
felucca_dbg.in_audio = 1;
if (p & FM1_AUDIO_HALF) {
uint32_t half = fm1_audio_free_half(), b, us;
int32_t *o = &abuf[half * HALF_WORDS];
@@ -86,15 +58,24 @@ void fm1_alnk0_irq(void) /* via isr_alnk0 (hal/fm1_isr.S)
shed_req = 0;
shed_voice();
}
#if FELUCCA_UAC
uac_render_start();
usb_full_now = (uint8_t)(usb_full && uac.feed); /* menu USB AUDIO = FULL, while the computer records */
#endif
for (b = 0; b < HALF_FRAMES; b += CTL)
audio_block(o + 2u * b, CTL);
fm1_audio_ack_half();
audio_halves++;
us = (fm1_ticks() - t0) / FM1_TICKS_PER_US;
{ /* the deadline sees the render and TIMER5 nested in it (the USB audio stream); the load
* figures the render alone (after Felucca 1.0) */
uint32_t all = fm1_ticks() - t0;
us = (all - t5_nested_ticks) / FM1_TICKS_PER_US;
shed_over = (uint8_t)(shed_over << 1 | (all / FM1_TICKS_PER_US * 100u > (HALF_FRAMES * 1000000u / FS) * 85u));
}
if (us > audio_max_us)
audio_max_us = us;
if (us * 100u > (HALF_FRAMES * 1000000u / FS) * 85u)
shed_req = 1;
if ((shed_over & 3u) == 3u)
shed_req = 1; /* two in a row */
song.cpu_q8 = (song.cpu_q8 * 15u + (us * 256u) / (HALF_FRAMES * 1000000u / FS)) / 16u;
if (fm1_audio_free_half() != half)
felucca_dbg.late++; /* the DMA moved on while we rendered */
+192 -2
View File
@@ -19,7 +19,8 @@ enum { ED_INFO = 1, ED_GET, ED_SET, ED_DUMP, ED_DESC, ED_STEP_GET, ED_STEP_SET,
ED_WATCH, ED_CHANGED, ED_RELOAD, ED_PING, ED_STEP_CHANGED, /* v2: live sync */
ED_TRACK, ED_TRACK_MIX, ED_TRACK_DUMP, ED_TRACK_STEP, /* v3: tracks */
ED_TRACK_PARAM, ED_TRACK_CHANGED, /* v4: any track's parameters */
ED_DRUM_STEP }; /* v5: the 16 drum lanes */
ED_DRUM_STEP, /* v5: the 16 drum lanes */
ED_BK_LIST, ED_BK_GET, ED_BK_PUT }; /* v6: backup / restore */
static uint8_t ed_out[600];
static uint32_t ed_n;
@@ -358,6 +359,191 @@ static const param_desc_t *ed_desc(uint32_t scope, uint32_t id, int16_t **vp)
return 0;
}
/* ---- v6: backup / restore (web/EDITOR_PROTOCOL.md). Objects: 0 the working project, 1 the settings
* (colours, calibration, the song order, the lights, SYNC), 2..5 the projects A..D, 6..7 the user preset
* banks, 32..34 the user sample slots USR1..3 (read only here: restored with SMP_BEGIN / WRITE / END).
* LIST takes a snapshot of the working project and the settings; GET reads 1..256 bytes of an object.
* PUT stages one object in RAM (begin: id, length, CRC-32; data; commit), checks it as a load would,
* then writes it through the usual A/B commit: a cut-off restore never leaves half an object. */
#if FELUCCA_FLASH
#define ED_BK_RAW ((uint8_t *)&proj_tmp) /* the staging RAM (main loop, as the project loads) */
_Static_assert(sizeof proj_tmp >= sizeof(project_t) && sizeof proj_tmp >= sizeof(up_bank_t) &&
sizeof proj_tmp >= sizeof(persist_t), "backup staging");
static persist_t ed_bk_set; /* LIST's snapshot of the settings */
static uint8_t ed_bk_valid, ed_bk_put, ed_bk_id;
static uint32_t ed_bk_len, ed_bk_crc, ed_bk_pos, ed_bk_ms;
static void ed_bk_u32(uint32_t v) { uint32_t i; for (i = 0; i < 5u; i++) ed_b((v >> (7u * i)) & 127u); }
static uint32_t ed_bk_r32(const uint8_t *a)
{
return (uint32_t)a[0] | (uint32_t)a[1] << 7 | (uint32_t)a[2] << 14 | (uint32_t)a[3] << 21 | (uint32_t)a[4] << 28;
}
static void ed_bk_pack(const uint8_t *p, uint32_t n) /* pack7: a top-bits byte, then up to 7 bytes */
{
while (n) {
uint32_t k = n > 7u ? 7u : n, m = 0, i;
for (i = 0; i < k; i++)
m |= (uint32_t)(p[i] >> 7) << i;
ed_b(m);
for (i = 0; i < k; i++)
ed_b(p[i] & 127u);
p += k;
n -= k;
}
}
static const uint8_t *ed_bk_obj(uint32_t id, uint32_t *len) /* 0 = no such object; *len 0 = empty */
{
*len = 0;
if (id == 0u) {
*len = sizeof(project_t);
return ED_BK_RAW;
}
if (id == 1u) {
*len = sizeof ed_bk_set;
return (const uint8_t *)&ed_bk_set;
}
if (id >= 2u && id <= 5u) {
if (project_used(id - 2u))
*len = sizeof proj_slot[0];
return (const uint8_t *)&proj_slot[id - 2u];
}
if (id == 6u || id == 7u) {
if (up_bank[id - 6u].magic == UP_BANK_MAGIC)
*len = sizeof up_bank[0];
return (const uint8_t *)&up_bank[id - 6u];
}
if (id >= 32u && id < 32u + SMP_USER_SLOTS) {
const smp_user_hdr_t *h = (const smp_user_hdr_t *)smp_user_xip(id - 32u);
if (h->magic == SMP_USER_MAGIC && h->version == 1u && h->nz && h->nz <= 16u &&
h->data_len <= SMP_USER_SIZE - SMP_USER_DATA)
*len = SMP_USER_DATA + h->data_len;
return smp_user_xip(id - 32u);
}
return 0;
}
static const uint8_t ED_BK_IDS[] = {0, 1, 2, 3, 4, 5, 6, 7, 32, 33, 34};
static uint32_t ed_bk_commit(void)
{
uint8_t *raw = ED_BK_RAW;
uint32_t id = ed_bk_id, n = ed_bk_len;
if (ed_bk_pos != n || st_crc32(raw, n) != ed_bk_crc)
return 2;
if (id == 1u)
return settings_restore(raw, n);
if (id <= 5u)
return project_restore(id == 0u ? 4u : id - 2u, raw, n);
if (id == 6u || id == 7u) { /* a user preset bank (n 0: empty) */
const up_bank_t *b = (const up_bank_t *)raw;
if (n && (n != sizeof *b || b->magic != UP_BANK_MAGIC || b->rsize != sizeof(up_rec_t) || b->nslot != UP_PER_BANK))
return 2;
if (!flash_ok || st_save(OBJ_UPRESET0 + id - 6u, raw, n))
return 4;
memset(&up_bank[id - 6u], 0, sizeof up_bank[0]);
if (n)
memcpy(&up_bank[id - 6u], raw, n);
up_bank_check(id - 6u, (int)n);
up_gen++;
return 0;
}
return 1;
}
static int ed_backup(uint32_t cmd, const uint8_t *a, uint32_t na) /* 1: a backup command (reply built) */
{
uint32_t i, len, rc;
const uint8_t *p;
if (cmd == ED_BK_LIST) {
rc = !flash_ok ? 4u : 0u;
if (!rc) {
proj_capture((project_t *)ED_BK_RAW); /* the working project, as it is now */
persist_fill(&ed_bk_set);
ed_bk_valid = 1;
ed_bk_put = 0;
}
ed_b(rc);
ed_b(rc ? 0u : (uint32_t)sizeof ED_BK_IDS);
for (i = 0; !rc && i < sizeof ED_BK_IDS; i++) {
p = ed_bk_obj(ED_BK_IDS[i], &len);
ed_b(ED_BK_IDS[i]);
ed_bk_u32(len);
ed_bk_u32(st_crc32(p, len));
fm1_wdt_feed(); /* (a sample slot: up to 80 KiB through the CRC) */
}
return 1;
}
if (cmd == ED_BK_GET) { /* id, off (5), count (2) -> id, rc, off, count, data */
uint32_t off = na >= 6u ? ed_bk_r32(a + 1) : 0u, count = na >= 8u ? (uint32_t)a[6] | (uint32_t)a[7] << 7 : 0u;
p = na >= 1u ? ed_bk_obj(a[0], &len) : 0;
rc = na != 8u || !p || !count || count > 256u || off > len || count > len - off ? 1u
: !ed_bk_valid || (a[0] == 0u && ed_bk_put) ? 5u : 0u; /* 5: LIST first (the snapshot is gone) */
ed_b(na ? a[0] : 127u);
ed_b(rc);
ed_bk_u32(off);
ed_b(rc ? 0u : count & 127u);
ed_b(rc ? 0u : count >> 7);
if (!rc)
ed_bk_pack(p + off, count);
return 1;
}
if (cmd == ED_BK_PUT) { /* op, id, ... -> op, id, rc */
uint32_t op = na >= 2u ? a[0] : 99u, id = na >= 2u ? a[1] : 127u;
rc = 1;
if (!flash_ok) {
rc = 4;
} else if (op == 0u && na == 12u && (id <= 7u)) { /* begin: id, length (5), CRC-32 (5) */
len = ed_bk_r32(a + 2);
if (id >= 2u || len) { /* (the working project and the settings are never empty) */
if (len <= sizeof proj_tmp) {
ed_bk_put = 1;
ed_bk_valid = 0; /* (the staging RAM is the snapshot's) */
ed_bk_id = (uint8_t)id;
ed_bk_len = len;
ed_bk_crc = ed_bk_r32(a + 7);
ed_bk_pos = 0;
ed_bk_ms = fm1_ms;
rc = 0;
}
}
} else if (!ed_bk_put || ed_bk_id != id || fm1_ms - ed_bk_ms > 15000u) {
rc = 5; /* no begin for this object (or too long ago) */
} else if (op == 1u && na >= 9u && ed_bk_r32(a + 2) == ed_bk_pos) { /* data: off (5), pack7 */
uint32_t k = ed_unpack7(a + 7, na - 7u, ed_smp_buf, 256u);
if (k && k <= ed_bk_len - ed_bk_pos) {
memcpy(ED_BK_RAW + ed_bk_pos, ed_smp_buf, k);
ed_bk_pos += k;
ed_bk_ms = fm1_ms;
rc = 0;
}
} else if (op == 2u && na == 2u) { /* commit */
rc = ed_bk_commit();
ed_bk_put = 0;
if (!rc) {
sync_reload = 1;
ui.force = 1;
}
} else if (op == 3u && na == 2u) { /* abort */
ed_bk_put = 0;
rc = 0;
}
ed_b(op & 127u);
ed_b(id & 127u);
ed_b(rc);
return 1;
}
return 0;
}
#else
static int ed_backup(uint32_t cmd, const uint8_t *a, uint32_t na) /* no flash: nothing to back up */
{
(void)a;
(void)na;
if (cmd < ED_BK_LIST || cmd > ED_BK_PUT)
return 0;
ed_b(4);
return 1;
}
#endif
static void ed_handle(const uint8_t *f, uint32_t n) /* f: the bytes between F0 and F7 */
{
uint32_t cmd = f[3], i;
@@ -366,6 +552,10 @@ static void ed_handle(const uint8_t *f, uint32_t n) /* f: the bytes between F0
int16_t *vp;
const param_desc_t *d;
ed_begin(cmd);
if (ed_backup(cmd, a, na)) { /* v6: backup / restore */
ed_send();
return;
}
switch (cmd) {
case ED_INFO:
ed_str("FELUCCA " FELUCCA_VERSION, 24);
@@ -377,7 +567,7 @@ static void ed_handle(const uint8_t *f, uint32_t n) /* f: the bytes between F0
for (i = 0; i < NENGINES; i++)
ed_str(ENGINES[i]->name, 8);
ed_b(NTRK); /* v3 */
ed_b(5); /* v5: the protocol version */
ed_b(6); /* v6: the protocol version (backup) */
break;
case ED_GET:
case ED_SET:
+7 -1
View File
@@ -35,9 +35,15 @@
#ifndef FELUCCA_CDC
#define FELUCCA_CDC 1 /* USB CDC-ACM serial console */
#endif
#ifndef FELUCCA_UAC /* (before usb.c: it defaults to 0) */
#define FELUCCA_UAC 1 /* USB audio input: the master output, 16-bit stereo 44.1 kHz (usb.c, after Felucca 1.0) */
#endif
#ifndef FELUCCA_UAC_TONE
#define FELUCCA_UAC_TONE 0 /* bench: the USB input sends test triangles instead of the music */
#endif
#include "usb.c"
#ifndef FELUCCA_UART
#define FELUCCA_UART 0 /* 1 = TRS MIDI IN on UART1 (untested) */
#define FELUCCA_UART 1 /* TRS MIDI IN on UART1 (3.5 mm jack) */
#endif
#if FELUCCA_UART
#include "midi_uart.c"
+40
View File
@@ -93,6 +93,40 @@ static inline int32_t knee(int32_t x)
return x < 0 ? -a : a;
}
/* the USB audio input at full level (menu USB AUDIO = FULL): the same output stage with its own state,
* fed as if MASTER were all the way up, so the recording level does not follow the knob. The DAC path
* (master_out) is untouched. audio.c sets usb_full_now for a render while the computer records. */
static uint8_t usb_full; /* menu USB AUDIO: 0 MASTER (follows the knob), 1 FULL (panel.c lights_word) */
static uint8_t usb_full_now; /* this render fills usb_out (audio.c) */
static int32_t usb_out[2u * CTL];
static struct { int32_t lim, dc[2], dce[2], lc[4], lce[4]; } uo = {LIM_T, {0, 0}, {0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
static void master_out_usb(int32_t *l, int32_t *r)
{
int32_t al, ar, a;
*l = dc_block(*l, &uo.dc[0], &uo.dce[0]);
*r = dc_block(*r, &uo.dc[1], &uo.dce[1]);
if (fx_lowcut) {
*l = lowcut1(*l, &uo.lc[0], &uo.lce[0]);
*l = lowcut1(*l, &uo.lc[1], &uo.lce[1]);
*r = lowcut1(*r, &uo.lc[2], &uo.lce[2]);
*r = lowcut1(*r, &uo.lc[3], &uo.lce[3]);
}
al = *l < 0 ? -*l : *l;
ar = *r < 0 ? -*r : *r;
a = al > ar ? al : ar;
if (a > uo.lim)
uo.lim += (a - uo.lim) >> 2;
else if (uo.lim > LIM_T)
uo.lim -= ((uo.lim - LIM_T) >> 12) + 1;
if (uo.lim > LIM_T) {
int32_t g = (int32_t)(((uint32_t)LIM_T << 15) / (uint32_t)uo.lim);
*l = ((*l >> 4) * g) >> 11;
*r = ((*r >> 4) * g) >> 11;
}
*l = knee(*l);
*r = knee(*r);
}
static inline void master_out(int32_t *l, int32_t *r)
{
int32_t al, ar, a;
@@ -436,5 +470,11 @@ static void mix_block(int32_t *out, uint32_t n)
master_out(&l, &r);
out[2u * i] = l;
out[2u * i + 1u] = r;
if (usb_full_now && i < CTL) { /* USB AUDIO = FULL: MASTER all the way up (4096) */
int32_t ul = (mix_l[i] >> 2) << 2, ur = (mix_r[i] >> 2) << 2;
master_out_usb(&ul, &ur);
usb_out[2u * i] = ul;
usb_out[2u * i + 1u] = ur;
}
}
}
+39 -15
View File
@@ -6,32 +6,53 @@ extern uint32_t _data_start[], _data_end[], _data_load[], _bss_start[], _bss_end
extern uint32_t _pool_start[], _pool_end[], _rt_start[], _rt_end[], _rt_load[];
/* TIMER5 outranks ALNK0 (timer5_start): the scan keeps its pace while a half buffer renders. Nested in
* the render it only scans and counts ms; the USB and UART polls wait for the first tick after the
* render, so usb_poll never runs nested. The USB audio stream cannot wait (one packet per 1 ms frame, a
* render takes up to a few ms): uac_service also runs nested. It touches only EP4 (INDEX set on every
* access) and the consumer side of the audio ring, and usb_poll never runs nested, so the two never
* interleave. The time spent nested is handed to the audio ISR: its load figures stay render-only.
* (After Felucca 1.0.) */
void fm1_timer5_irq(void)
{
static uint32_t sub;
static uint32_t sub, owed;
uint32_t t0 = fm1_ticks(), usb_due = sub % 5u == 0u;
fm1_timer5_ack();
felucca_dbg.timer_irqs++;
if (felucca_dbg.in_audio)
felucca_dbg.nested++; /* a tick inside the audio render (it outranks ALNK0) */
fm1_input_tick();
if (sub % 5u == 0u)
usb_poll(); /* 2 kHz: all USB SIE traffic lives here */
#if FELUCCA_UART
if (sub % 5u == 2u)
uart_midi_poll(); /* 2 kHz: <= ~7 bytes per call at 31250 baud */
#endif
if (++sub == 10u)
sub = 0;
{ /* milliseconds from the 24 MHz TIMER4: TIMER5 ticks coalesce while ALNK0 renders */
{ /* milliseconds from the 24 MHz TIMER4 (robust to a late tick) */
static uint32_t last, acc;
uint32_t now = fm1_ticks();
acc += now - last;
last = now;
acc += t0 - last;
last = t0;
while (acc >= 1000u * FM1_TICKS_PER_US) {
acc -= 1000u * FM1_TICKS_PER_US;
fm1_ms++;
}
}
if (usb_due)
owed |= 1u; /* 2 kHz: all USB SIE traffic lives here */
#if FELUCCA_UART
if (sub % 5u == 2u)
owed |= 2u; /* 2 kHz: <= ~7 bytes per call at 31250 baud */
#endif
if (++sub == 10u)
sub = 0;
if (felucca_dbg.in_audio) {
felucca_dbg.nested++;
#if FELUCCA_UAC
if (usb_due)
uac_service();
#endif
t5_nested_ticks += fm1_ticks() - t0;
return;
}
if (owed & 1u)
usb_poll();
#if FELUCCA_UART
if (owed & 2u)
uart_midi_poll();
#endif
owed = 0;
}
extern void isr_timer5(void);
@@ -95,6 +116,7 @@ static void felucca_init(void)
song.sel = 0;
song.master_q12 = 2048;
autosave_resume(); /* the project as it was left (project.c) */
song.g[G_SYNC] = (int16_t)lights_sync; /* a setting of the FM-1 (panel.c) */
layers_init(); /* the panel's layer buttons for the keys (ui_layers.c) */
go_home();
ui.force = 1;
@@ -118,6 +140,8 @@ static void fm1_main(void)
}
felucca_dbg.boots++;
felucca_dbg.max_us = 0;
felucca_dbg.in_audio = 0; /* .noinit: a reset inside the audio ISR left it set, and
TIMER5 would treat every tick as nested (no USB poll) */
felucca_dbg.prev_stage = felucca_dbg.stage; /* a WDT reset leaves the last breadcrumb here */
felucca_dbg.prev_page = felucca_dbg.page;
felucca_dbg.prev_home = felucca_dbg.home;
+42 -14
View File
@@ -4,18 +4,31 @@
* RX DMA into a 128-byte ring, polled from the TIMER5 ISR (no UART IRQ).
* Built only with FELUCCA_UART=1. Channel messages go into midi_in_q next to
* USB, as USB-MIDI packets (cable 0, CIN = status >> 4), so seq.c routes them by
* channel as it does USB; realtime, system common and SysEx are dropped. */
* channel as it does USB; clock and transport (F8 FA FB FC) are queued with cable 1 (seq.c: SYNC TRS);
* other realtime, system common and SysEx are dropped.
*
* The ring is read by content, not by the DMA count: every slot the parser has
* not yet been given holds UM_EMPTY, and the reader takes bytes until it meets
* one. The count (HRXCNT, latched every poll) can miss a byte while the byte
* itself is in the ring: the reader then stays one byte behind, so each message
* ends only with the next byte (a note-off held until the next note). Following
* the content cannot drift. (Fix from Felucca [Salt] 0.9-salt14 by ChanceTheMaker,
* found by keremimo on an FM-1 with an Akai MPC Sample; GPL-3.0.) */
#include "../hal/fm1_uart.h" /* registers; relative, so the host tests find it too */
#define UM_RING 128u
#define UM_EMPTY 0xFDu /* undefined MIDI realtime byte: never sent, marks unwritten slots */
static volatile uint8_t um_ring[UM_RING] __attribute__((aligned(16)));
static struct {
uint32_t rd, pend, bytes, drops, msgs;
uint32_t rd, bytes, drops, msgs;
uint8_t st, need, got, d0, sysex;
} um;
static void uart_midi_init(void) /* before timer5_start(): PORTH RMW */
{
uint32_t i;
for (i = 0; i < UM_RING; i++)
um_ring[i] = UM_EMPTY;
fm1_uart1_midi_init(um_ring, UM_RING);
}
@@ -26,8 +39,14 @@ static uint32_t um_len(uint32_t s) /* data bytes of a channel st
static void um_byte(uint32_t b)
{
if (b >= 0xF8u)
return; /* realtime: ignored, state kept */
if (b >= 0xF8u) { /* realtime: the state is kept; clock and transport */
if ((b == 0xF8u || b == 0xFAu || b == 0xFBu || b == 0xFCu) && mi_w - mi_r < MQ) {
midi_in_q[mi_w % MQ] = 0x1Fu | b << 8; /* (cable 1: from the TRS jack; seq.c mclk_event) */
RING_PUBLISH();
mi_w++;
}
return;
}
if (b & 0x80u) {
um.sysex = b == 0xF0u;
um.st = b < 0xF0u ? (uint8_t)b : 0; /* system common/SysEx cancel running status */
@@ -57,18 +76,27 @@ static void um_byte(uint32_t b)
}
}
static void uart_midi_poll(void) /* TIMER5 ISR, same context as usb_poll */
/* the bytes the DMA has written since the last call; a received UM_EMPTY (line
* noise) is passed over once the byte after it has landed */
static void um_drain(void)
{
um.pend += fm1_uart1_rx_take();
if (um.pend > UM_RING) {
um.drops += um.pend - UM_RING;
um.rd = (um.rd + um.pend - UM_RING) & (UM_RING - 1u);
um.pend = UM_RING;
}
while (um.pend) {
um_byte(um_ring[um.rd]);
uint32_t n;
for (n = 0; n < UM_RING; n++) {
uint32_t b = um_ring[um.rd];
if (b == UM_EMPTY) {
if (um_ring[(um.rd + 1u) & (UM_RING - 1u)] == UM_EMPTY)
break;
b = um_ring[um.rd]; /* the DMA writes in order: this one has landed too */
}
um_ring[um.rd] = UM_EMPTY;
um.rd = (um.rd + 1u) & (UM_RING - 1u);
um.pend--;
um.bytes++;
um_byte(b); /* a UM_EMPTY is an unknown realtime byte: ignored */
}
}
static void uart_midi_poll(void) /* TIMER5 ISR, same context as usb_poll */
{
fm1_uart1_rx_take(); /* acknowledges the pendings; the count is not used */
um_drain();
}
+27
View File
@@ -65,6 +65,33 @@ static int32_t panel_enc(uint32_t role)
#define SETTINGS_MAGIC 0x53455433u /* "SET3" */
struct { uint32_t magic, palette, lowcut, zoom; } settings __attribute__((section(".noinit")));
/* the lights (menu LIGHTS / KEYS / NOTES), for playing in the dark: kept in flash with the settings
* (project.c persist_t.lights), read at every boot; not in .noinit, so nothing there moves. The same
* word keeps SYNC and the REC screen's MODE / START (seq.c rec_tempo, rec_count) */
enum { LIGHTS_OFF, LIGHTS_LOW, LIGHTS_MID, LIGHTS_HIGH, LIGHTS_N };
enum { KEYS_OFF, KEYS_C, KEYS_WHITE, KEYS_N };
static uint8_t lights_lvl, lights_keys;
static uint8_t lights_notes; /* 1: on a synth track the sounding notes light their keys */
static uint8_t lights_sync; /* GLO > SYSTEM > SYNC (G_SYNC), kept here: 0 INT, 1 USB, 2 TRS */
static const uint16_t LIGHTS_NS[LIGHTS_N] = {0u, 500u, 1000u, 2000u}; /* the backlight pulse a frame (ns): a lit
* LED ~95 us, the glow (landmarks) 4 us (fm1_input.h) */
static uint32_t lights_word(void)
{
return (uint32_t)lights_lvl | (uint32_t)lights_keys << 4 | (uint32_t)(lights_notes != 0u) << 8 |
(uint32_t)(rec_tempo != 0u) << 9 | (uint32_t)(rec_count != 0u) << 10 | (uint32_t)(usb_full != 0u) << 11 |
(uint32_t)(lights_sync % 3u) << 12;
}
static void lights_from_word(uint32_t w)
{
lights_lvl = (uint8_t)((w & 15u) < LIGHTS_N ? (w & 15u) : LIGHTS_OFF);
lights_keys = (uint8_t)(((w >> 4) & 15u) < KEYS_N ? ((w >> 4) & 15u) : KEYS_OFF);
lights_notes = (uint8_t)((w >> 8) & 1u);
rec_tempo = (uint8_t)((w >> 9) & 1u); /* the REC screen: MODE, START (seq.c) */
rec_count = (uint8_t)((w >> 10) & 1u);
usb_full = (uint8_t)((w >> 11) & 1u); /* menu USB AUDIO (fx.c) */
lights_sync = (uint8_t)(((w >> 12) & 3u) % 3u);
}
static void settings_save(void); /* project.c: flash copy (FELUCCA_FLASH) */
static uint8_t settings_later; /* changed while playing: saved once stopped (project.c) */
+2 -1
View File
@@ -16,6 +16,7 @@ static const char *const N_ORDER[] = {"NOTE", "PLAY"};
static const char *const N_CLICK[] = {"OFF", "REC", "ON"}; /* G_CLOCK is the metronome (seq.c click_tick) */
static const char *const N_NOTE[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};
static const char *const N_DASH[] = {"--"};
static const char *const N_SYNC[] = {"INT", "USB", "TRS"}; /* G_SYNC: the tempo and PLAY / STOP from (seq.c mclk) */
static const char *const N_GO[] = {"--", "GO"};
static const char *const N_SLCR[] = {"OFF", "GATE", "STUT"}; /* SL_OFF .. SL_STUT (slicer.c) */
static const char *const N_SLDIV[] = {"1/8", "1/16", "1/32", "8T", "16T", "32T"}; /* SL_DEN */
@@ -108,7 +109,7 @@ static const param_desc_t GP[G_COUNT] = {
[G_CRATE] = PD("CRT", F_LFOHZ, 0, 127, 40),
[G_CDEPTH] = PD("CDP", F_PCT, 0, 127, 60),
[G_MIDI] = PE("MIDI", N_DASH, 0),
[G_SYNC] = PE("SYNC", N_DASH, 0),
[G_SYNC] = PE("SYNC", N_SYNC, 0), /* a setting of the FM-1, not of a project (panel.c lights_sync) */
[G_ROUTE] = PE("ROUT", N_DASH, 0),
[G_INFO] = PD("CPU", F_INT, 0, 0, 0),
[G_SLOT] = PD("SLOT", F_INT, 1, 4, 1),
+107 -11
View File
@@ -255,7 +255,7 @@ static void proj_apply(const project_t *p, int all)
{
uint32_t i, k;
for (i = 0; i < G_COUNT; i++)
if (all ? i != G_SLOT && i != G_LOAD && i != G_SAVE : i == G_DRLVL || i == G_DRREV)
if (all ? i != G_SLOT && i != G_LOAD && i != G_SAVE && i != G_SYNC : i == G_DRLVL || i == G_DRREV)
song.g[i] = (int16_t)clamp(p->g[i], GP[i].min, GP[i].max);
for (k = 0; k < NTRK; k++) {
track_t *t = &trk[k];
@@ -424,7 +424,11 @@ typedef struct {
#if FELUCCA_ARRANGER
arr_config_t arrangement;
#endif
uint32_t lights; /* SLOOP 2.3: the backlight (panel.c lights_word); appended,
* so 2.2 still reads its part (st_load cuts at its size) */
} persist_t;
#define PERSIST_SIZE_V22 __builtin_offsetof(persist_t, lights) /* the settings as 2.2 wrote them (no lights) */
_Static_assert(sizeof(persist_t) == PERSIST_SIZE_V22 + 4u, "lights: the last word, no padding before it");
#if FELUCCA_ARRANGER
#define PERSIST_MAGIC 0x50455233u /* "PER3": includes the song order */
#else
@@ -455,7 +459,9 @@ static void persist_boot(void) /* before settings_init / pane
}
{
int n = st_load(OBJ_SETTINGS, &p, sizeof p);
if ((n == (int)sizeof p && p.magic == PERSIST_MAGIC)
if (n == (int)PERSIST_SIZE_V22 && p.magic == PERSIST_MAGIC)
p.lights = 0; /* from 2.2: backlight off */
if (((n == (int)sizeof p || n == (int)PERSIST_SIZE_V22) && p.magic == PERSIST_MAGIC)
#if FELUCCA_ARRANGER
|| (n == (int)(16u + sizeof(panel_t)) && p.magic == 0x50455232u)
#endif
@@ -466,6 +472,10 @@ static void persist_boot(void) /* before settings_init / pane
settings.zoom = p.zoom;
if (p.panel.magic == PANEL_MAGIC)
panel = p.panel;
if (p.magic == PERSIST_MAGIC)
lights_from_word(p.lights);
else
p.lights = 0;
#if FELUCCA_ARRANGER
if (p.magic == PERSIST_MAGIC && arr_valid(&p.arrangement, 15u))
arrangement = p.arrangement;
@@ -504,21 +514,27 @@ static void persist_boot(void) /* before settings_init / pane
static int project_used(uint32_t slot) { return proj_ok(&proj_slot[slot & 3u]); }
static void persist_fill(persist_t *p) /* the settings as they are now */
{
memset(p, 0, sizeof *p);
p->magic = PERSIST_MAGIC;
p->palette = settings.palette;
p->lowcut = settings.lowcut;
p->zoom = settings.zoom;
p->panel = panel;
p->lights = lights_word();
#if FELUCCA_ARRANGER
p->arrangement = arrangement;
#endif
}
static void settings_save(void)
{
#if FELUCCA_FLASH
persist_t p;
if (!flash_ok)
return;
memset(&p, 0, sizeof p);
p.magic = PERSIST_MAGIC;
p.palette = settings.palette;
p.lowcut = settings.lowcut;
p.zoom = settings.zoom;
p.panel = panel;
#if FELUCCA_ARRANGER
p.arrangement = arrangement;
#endif
persist_fill(&p);
if (!memcmp(&p, &persist_saved, sizeof p))
return; /* unchanged: no erase cycle */
if (st_save(OBJ_SETTINGS, &p, sizeof p) == 0)
@@ -528,6 +544,82 @@ static void settings_save(void)
#if FELUCCA_FLASH
_Static_assert(sizeof(project_t) <= ST_PAYLOAD_MAX, "project does not fit one flash sector");
/* ---- backup restore (editor.c BK_PUT): each object checked as a load checks it, then written through the
* same A/B commit as a save. rc: 0 ok, 2 not a valid object, 3 stop the song first, 4 flash */
static int panel_valid(const panel_t *q) /* a permutation of the buttons and of the knobs */
{
uint32_t i, b = 0, e = 0;
if (q->magic != PANEL_MAGIC)
return 0;
for (i = 0; i < NB; i++) {
if (q->btn[i] >= 14u || (b >> q->btn[i]) & 1u)
return 0;
b |= 1u << q->btn[i];
}
for (i = 0; i < NE; i++) {
if (q->enc[i] >= 7u || (e >> q->enc[i]) & 1u || (q->dir[i] != 1 && q->dir[i] != -1))
return 0;
e |= 1u << q->enc[i];
}
return 1;
}
static uint32_t settings_restore(const void *raw, uint32_t n)
{
persist_t p;
if (n != sizeof p && n != PERSIST_SIZE_V22)
return 2;
memset(&p, 0, sizeof p);
memcpy(&p, raw, n);
if (p.magic != PERSIST_MAGIC || p.palette >= NPALETTES || p.lowcut > 1u || p.zoom > 1u || !panel_valid(&p.panel))
return 2;
#if FELUCCA_ARRANGER
if (!arr_valid(&p.arrangement, 15u))
return 2;
#endif
if (!flash_ok || st_save(OBJ_SETTINGS, &p, sizeof p))
return 4;
persist_saved = p;
settings.palette = p.palette;
settings.lowcut = p.lowcut;
settings.zoom = p.zoom;
panel = p.panel;
#if FELUCCA_ARRANGER
arrangement = p.arrangement;
#endif
lights_from_word(p.lights);
song.g[G_SYNC] = (int16_t)lights_sync;
palette_set(settings.palette);
fx_lowcut = (uint8_t)(settings.lowcut != 0);
ui.force = 1;
return 0;
}
/* slot 0..3 (n 0: empty), or 4: the working project (loaded now) */
static uint32_t project_restore(uint32_t slot, const void *raw, uint32_t n)
{
if (song.playing || transport_req)
return 3;
if (slot < 4u && !n) {
if (!flash_ok || st_save(OBJ_PROJECT0 + slot, raw, 0))
return 4;
memset(&proj_slot[slot], 0, sizeof proj_slot[slot]);
sec_dirty &= (uint8_t)~(1u << slot);
return 0;
}
if (!proj_import(&autosave_buf, raw, (int)n))
return 2;
if (slot == 4u) {
project_apply(&autosave_buf);
return 0;
}
if (!flash_ok || st_save(OBJ_PROJECT0 + slot, &autosave_buf, sizeof autosave_buf))
return 4;
memcpy(&proj_slot[slot], &autosave_buf, sizeof proj_slot[slot]);
sec_dirty &= (uint8_t)~(1u << slot);
return 0;
}
#endif
#if FELUCCA_ARRANGER
static void arrangement_save(void)
@@ -605,6 +697,10 @@ static void sections_flush(void) /* main loop */
}
srec_done = 0;
}
if ((uint32_t)song.g[G_SYNC] != lights_sync) { /* GLO > SYSTEM > SYNC: kept with the settings */
lights_sync = (uint8_t)song.g[G_SYNC];
settings_later = 1;
}
if (settings_later) { /* the menu closed while playing */
settings_later = 0;
song_dirty = 1; /* (settings_save when quiet, with the song) */
+133 -5
View File
@@ -378,8 +378,19 @@ static void rec_release(track_t *t, uint32_t note)
* - an empty project: a FREE TAKE (ft_on). Play freely, as long as you like: no tempo, no
* grid. REC on the next downbeat closes the loop: its length sets the tempo (1, 2 or 4
* bars, the nearest the current tempo; within 3 % of it the tempo is kept), the notes are
* quantised to 1/16 into it with their lengths, and the loop plays on. PLAY drops the take. */
* quantised to 1/16 into it with their lengths, and the loop plays on. PLAY drops the take.
* The REC screen (ui_studio.c) sets how (settings of the FM-1, panel.c lights_word):
* KNOB 1 MODE (an empty project): FREE (the free take above) or TEMPO (record at the tempo set,
* as in a project with notes);
* KNOB 3 START (TEMPO, or a project with notes): NOTE (the first note starts the loop, as above)
* or COUNT (PLAY clicks one bar, 4 beats, then the loop and the recording start; notes
* played meanwhile only sound). */
static volatile uint8_t rec_wait; /* 1: armed, waits for a note */
static uint8_t rec_tempo; /* REC screen MODE: 0 FREE, 1 TEMPO (an empty project) */
static uint8_t rec_count; /* REC screen START: 0 NOTE, 1 COUNT (one bar of clicks) */
static volatile uint8_t ci_on; /* the count-in runs (armed, COUNT, PLAY) */
static volatile uint8_t ci_beat; /* its beats clicked so far - 1 (the UI shows 4 - ci_beat) */
static uint32_t ci_u; /* clock units since it started */
static volatile uint8_t rec_go; /* recording just started (the UI says so) */
static void seq_start(void);
static void rec_begin(void)
@@ -750,10 +761,12 @@ static void arp_tick(track_t *t, uint32_t adv)
* note is the downbeat (the transport starts, recording on) */
static void arm_start(track_t *t)
{
if (!rec_wait || t != TSEL || song.playing)
if (!rec_wait || t != TSEL || song.playing || ci_on)
return;
if (project_empty()) {
if (project_empty() && !rec_tempo) {
ft_start(t); /* the first take sets the loop and the tempo */
} else if (rec_count) {
return; /* COUNT: PLAY counts in; a note only sounds */
} else {
#if FELUCCA_ARRANGER
arrangement_enabled = 0;
@@ -1471,15 +1484,107 @@ static track_t *midi_route(uint32_t ch, uint32_t note, int on)
return t;
}
/* MIDI clock in (GLO > SYSTEM > SYNC = USB or TRS; after Felucca 1.0's midi_clock.c, from contributions by
* ChanceTheMaker and keremimo): 24 pulses a beat. While the clock runs, the sequencer advances by the
* pulses (a pulse = BEAT_U / 24 units), interpolated up to the next one from the last interval but never
* past it, so it follows the master's tempo changes and cannot drift; BPM shows the master's tempo
* (the slicer, delay and arp follow it). START restarts from the top, CONTINUE carries on where it
* stopped, STOP stops. With no pulse for 0.5 s, the internal tempo takes over (PLAY works as ever). */
#define MCLK_PULSE_U (BEAT_U / 24u)
static struct {
uint32_t pos, done; /* units: the master's position (pulses since START), ours */
uint32_t last_ms, iv_ms; /* the last pulse, the interval between pulses (smoothed) */
uint32_t beat_ms; /* when pulse 0 of the last 24 came: the tempo */
uint8_t have, n24; /* a pulse since START; pulses towards the next tempo reading */
uint8_t alive; /* pulses are coming (from the SYNC source) */
} mclk;
static int mclk_on(void) /* the clock drives the sequencer */
{
return song.g[G_SYNC] && mclk.alive && fm1_ms - mclk.last_ms < 500u;
}
static void mclk_event(uint32_t st, uint32_t src) /* a realtime message; src 1 USB, 2 TRS */
{
uint32_t now = fm1_ms;
if (!song.g[G_SYNC] || src != (uint32_t)song.g[G_SYNC])
return;
if (st == 0xFAu || st == 0xFBu) { /* START: from the top; CONTINUE: on from where it stopped */
mclk.pos = mclk.done = 0;
mclk.have = 0;
if (st == 0xFAu)
transport_req = 1;
else if (!song.playing)
song.playing = 1;
return;
}
if (st == 0xFCu) { /* STOP */
transport_req = 2;
return;
}
if (st != 0xF8u)
return;
if (mclk.alive && now - mclk.last_ms < 200u) { /* the interval, smoothed (a gap is not a tempo) */
uint32_t iv = now - mclk.last_ms;
mclk.iv_ms = mclk.iv_ms ? (mclk.iv_ms * 3u + iv + 2u) / 4u : iv;
}
if (!mclk.alive || now - mclk.last_ms >= 500u) { /* (re)started: count a fresh beat */
mclk.n24 = 0;
mclk.beat_ms = now;
} else if (++mclk.n24 == 24u) { /* a beat: the tempo */
uint32_t dt = now - mclk.beat_ms;
mclk.n24 = 0;
mclk.beat_ms = now;
if (dt >= 250u && dt <= 1500u) /* 40..240 BPM */
song.g[G_BPM] = (int16_t)clamp((int32_t)((60000u + dt / 2u) / dt), 40, 240);
}
mclk.alive = 1;
mclk.last_ms = now;
if (song.playing || transport_req == 1u) { /* (a START queued with it: the next block starts) */
if (mclk.have)
mclk.pos += MCLK_PULSE_U;
mclk.have = 1; /* the first pulse after START is the downbeat */
}
}
static uint32_t mclk_adv(uint32_t n) /* units to advance this block (mclk_on) */
{
uint32_t el, off = 0, tgt, adv, cap = n * 2u * (uint32_t)song.g[G_BPM];
if (!mclk.have)
return 0; /* START seen: wait for the downbeat */
el = fm1_ms - mclk.last_ms;
if (mclk.iv_ms) {
if (el > mclk.iv_ms)
el = mclk.iv_ms;
off = el * MCLK_PULSE_U / mclk.iv_ms; /* (<= 200 x 110250: fits 32 bits) */
if (off >= MCLK_PULSE_U)
off = MCLK_PULSE_U - 1u;
}
tgt = mclk.pos + off;
adv = (int32_t)(tgt - mclk.done) > 0 ? tgt - mclk.done : 0u;
if (adv > cap)
adv = cap; /* behind: catch up at twice the tempo, no burst */
mclk.done += adv;
return adv;
}
/* everything that happens between two rendered blocks: transport, input, the steps of every
* track at the clock, the click, the rolls and the arps; then the clock moves on by n samples */
static void events_block(uint32_t n)
{
uint32_t i, pr, adv = n * (uint32_t)song.g[G_BPM];
uint32_t i, pr, adv;
if (transport_req == 1u) {
transport_req = 0;
if (ft_on) {
ft_close(); /* (PLAY from elsewhere: the editor) */
} else if (ci_on) {
ci_on = 0; /* PLAY again during the count-in: back to armed */
} else if (rec_wait && rec_count && !song.playing && !mclk_on() &&
!(project_empty() && !rec_tempo)) {
ci_on = 1; /* COUNT: one bar of clicks first (below) */
ci_u = 0;
ci_beat = 0;
drum_on(77u, 120u);
} else {
seq_start();
if (rec_wait && song.playing)
@@ -1495,8 +1600,27 @@ static void events_block(uint32_t n)
ft_bars = 0xFF;
}
}
if (ci_on) { /* the count-in: 4 beats at the tempo, then go */
if (!rec_wait || song.playing) {
ci_on = 0; /* (REC cancelled it, or it started some other way) */
} else {
uint32_t b;
ci_u += n * (uint32_t)song.g[G_BPM];
b = ci_u / BEAT_U;
if (b >= 4u) {
ci_on = 0;
seq_start();
if (song.playing)
rec_begin();
} else if (b != ci_beat) {
ci_beat = (uint8_t)b;
drum_on(76u, 72u);
}
}
}
if (rec_wait && song.playing)
rec_begin(); /* started some other way: record now */
adv = mclk_on() && song.playing ? mclk_adv(n) : n * (uint32_t)song.g[G_BPM]; /* (after a START) */
ft_block();
#if FELUCCA_ARRANGER
if (song.playing && arrangement_clock.running) {
@@ -1544,6 +1668,10 @@ static void events_block(uint32_t n)
uint32_t d1 = (pkt >> 16) & 0x7Fu, d2 = (pkt >> 24) & 0x7Fu;
track_t *t;
mi_r++;
if ((pkt & 15u) == 0xFu) { /* clock / transport: cable 0 USB, 1 TRS */
mclk_event((pkt >> 8) & 0xFFu, ((pkt >> 4) & 15u) ? 2u : 1u);
continue;
}
if (st != 0x90u && st != 0x80u)
continue;
t = midi_route(ch, d1, st == 0x90u && d2);
@@ -1570,7 +1698,7 @@ static void events_block(uint32_t n)
clk_beat++;
}
#if FELUCCA_ARRANGER
arr_elapse(&arrangement_clock, n, (uint32_t)song.g[G_BPM]);
arr_elapse(&arrangement_clock, adv, 1u); /* (units: n x BPM, or the MIDI clock) */
#endif
}
}
+6 -3
View File
@@ -63,9 +63,12 @@ static uint8_t st_buf[ST_PAYLOAD_MAX] __attribute__((aligned(4)));
static int st_head(uint32_t obj, uint32_t copy, st_hdr_t *h) /* commit record valid: 0 */
{
if (obj >= OBJ_COUNT || copy > 1u)
return -1;
if (st_read(st_sector(obj, copy), h, sizeof *h))
return -1;
if (h->magic != ST_MAGIC || h->type != obj || h->len > ST_PAYLOAD_MAX ||
if (h->magic != ST_MAGIC || h->type != obj || h->slot != copy || h->len > ST_PAYLOAD_MAX || /* (slot: the copy
* it was written to; after Felucca 1.0) */
h->hcrc != st_crc32(h, sizeof *h - 4u))
return -1;
return 0;
@@ -122,7 +125,7 @@ static int st_save(uint32_t obj, const void *src, uint32_t len)
uint32_t seq, base, off;
int cur, rc;
st_hdr_t h;
if (len > ST_PAYLOAD_MAX)
if (obj >= OBJ_COUNT || len > ST_PAYLOAD_MAX)
return -1;
cur = st_current(obj, &h);
seq = cur < 0 ? 0u : h.seq;
@@ -149,7 +152,7 @@ static int st_save(uint32_t obj, const void *src, uint32_t len)
{ /* read back: a write-protected or failing part must not report SAVED */
st_hdr_t chk;
uint32_t c = cur == 0 ? 1u : 0u;
if (st_head(obj, c, &chk) || chk.seq != h.seq || st_body(obj, c, &chk))
if (st_head(obj, c, &chk) || memcmp(&chk, &h, sizeof h) || st_body(obj, c, &chk)) /* the whole record */
return -7;
}
return 0;
+1 -1
View File
@@ -3,7 +3,7 @@
/* Felucca user interface. Four columns map to KNOB 1..4. Rendering is lazy:
* every element remembers what it last drew and is redrawn only on change. */
#ifndef FELUCCA_VERSION
#define FELUCCA_VERSION "SLOOP 2.2" /* the beat machine firmware for the FM-1 (based on Felucca) */
#define FELUCCA_VERSION "SLOOP 2.3" /* the beat machine firmware for the FM-1 (based on Felucca) */
#endif
static void project_save(uint32_t slot);
static void arrangement_save(void);
+142 -31
View File
@@ -49,6 +49,54 @@ static int play_led(void)
}
/* the keys' lights: what the layer held does, else the keys down and the drum hits */
/* what sounds on track t, as keys: the drum hits (each lights its key a few frames) or, on a synth
* track, the voices still held, mapped back through the keyboard (octave, scale, chords; by
* @renebohne, PR #11). Shown at once with menu NOTES on, on every screen and layer (keys_notes_dim) */
static uint32_t keys_sounding(const track_t *t)
{
uint32_t i, m = 0;
if (is_drum(t)) {
for (i = 0; i < DRUM_LANES; i++)
if (pad_lit[i])
m |= 1u << key_of_white(i);
return m;
}
for (i = 0; i < NVOICE; i++) {
const voice_t *v = &t->v[i];
if (v->active && v->gate && v->stage <= 2) {
uint32_t k, note = v->note;
for (k = 0; k < 27u; k++)
if (kb_map(t, k) == note)
m |= 1u << k;
}
}
return m;
}
static uint32_t scale_keys(uint32_t root_only) /* SCL: the keys in the scale (or its roots only) */
{
uint32_t i, m = 0, root = (uint32_t)trk[0].p[P_ROOT] % 12u, mask = SCALE_MASK[clamp(trk[0].p[P_SCALE], 0, NSCALES - 1)];
for (i = 0; i < 27u; i++) {
uint32_t d = (53u + i - root + 120u) % 12u;
if ((mask >> d) & 1u && (!root_only || !d))
m |= 1u << i;
}
return m;
}
static uint32_t erase_lanes(const track_t *t) /* EDIT erase, drum track: the sounds the pattern holds */
{
uint32_t i, m = 0;
if (is_drum(t))
for (i = 0; i < trk_len(t); i++) {
uint32_t l, d = dstep_mask(&t->dstep[i]);
for (l = 0; d; l++, d >>= 1)
if (d & 1u)
m |= 1u << key_of_white(l);
}
return m;
}
static uint32_t keys_lit(void)
{
uint32_t m = 0, i, blink = (fm1_ms / 125u) & 1u;
@@ -70,15 +118,10 @@ static uint32_t keys_lit(void)
}
return m | fm1_in.notes;
}
case LY_SCALE: { /* the keys in the scale; the root blinks */
uint32_t root = (uint32_t)trk[0].p[P_ROOT] % 12u, mask = SCALE_MASK[clamp(trk[0].p[P_SCALE], 0, NSCALES - 1)];
for (i = 0; i < 27u; i++) {
uint32_t d = (53u + i - root + 120u) % 12u;
if ((mask >> d) & 1u && (d || blink))
m |= 1u << i;
}
return m;
}
case LY_SCALE: /* the keys in the scale; the root blinks */
if (lights_notes) /* NOTES: the scale goes dim (keys_notes_dim), what sounds lit */
return (blink ? scale_keys(1) : 0u) | keys_sounding(t) | fm1_in.notes;
return scale_keys(0) & ~(blink ? 0u : scale_keys(1));
case LY_MIX: /* tracks heard: 1..4; soloed: 5..8; tap: the beat */
for (i = 0; i < 4u; i++) {
if (!trk_silent(&trk[i]))
@@ -89,26 +132,38 @@ static uint32_t keys_lit(void)
if (play_led())
m |= 1u << key_of_white(15);
return m;
case LY_ERASE: /* the sounds the pattern holds */
if (is_drum(t))
for (i = 0; i < trk_len(t); i++) {
uint32_t l, d = dstep_mask(&t->dstep[i]);
for (l = 0; d; l++, d >>= 1)
if (d & 1u)
m |= 1u << key_of_white(l);
}
return m | fm1_in.notes;
default:
case LY_ERASE: /* the sounds the pattern holds (NOTES: dim, the hits lit) */
return (lights_notes ? 0u : erase_lanes(t)) | fm1_in.notes | (lights_notes ? keys_sounding(t) : 0u);
default: /* playing, ARP roll, SAVE song, every page and the menu */
break;
}
m = fm1_in.notes;
if (is_drum(t)) /* the drum track: each hit lights its key */
for (i = 0; i < DRUM_LANES; i++)
if (pad_lit[i])
m |= 1u << key_of_white(i);
if (is_drum(t) || lights_notes) /* the drum track: each hit lights its key; NOTES: the synths too */
m |= keys_sounding(t);
return m;
}
/* menu NOTES, on the layers whose keys are tiles (FX effects, SEQ steps, GLO mute / solo): what
* sounds glows dimly under the tiles, which keep their full light. SCL (the scale) and EDIT on the
* drum track (the sounds of the pattern): those glow, and what sounds is lit (keys_lit) */
static uint32_t keys_notes_dim(void)
{
if (!lights_notes)
return 0u;
switch (ui.layer) {
case LY_FX:
case LY_STEP:
case LY_MIX:
return keys_sounding(TSEL);
case LY_SCALE:
return scale_keys(0);
case LY_ERASE:
return erase_lanes(TSEL);
default:
return 0u;
}
}
/* the keys' landmarks, dim: the first key of each row of the 4 x 4 grid on screen (white keys
* 1, 5, 9, 13) while a layer is held, and on the drum track (its 16 sounds, 4 x 4 as on KIT) */
static uint32_t keys_guide(void)
@@ -118,10 +173,24 @@ static uint32_t keys_guide(void)
return 1u << key_of_white(0) | 1u << key_of_white(4) | 1u << key_of_white(8) | 1u << key_of_white(12);
}
/* the keys the backlight lights (menu KEYS): the Cs, or every white key; bit k = key k (0 = F3) */
static uint32_t lights_keys_mask(void)
{
uint32_t k, m = 0;
if (!lights_lvl || !lights_keys)
return 0u;
for (k = 0; k < 27u; k++) {
uint32_t pc = (53u + k) % 12u; /* key 0 = F3 (53) */
if (lights_keys == KEYS_C ? pc == 0u : ((0xAB5u >> pc) & 1u) != 0u) /* 0xAB5: C D E F G A B */
m |= 1u << k;
}
return m;
}
static void ui_leds(void)
{
uint8_t nl[FM1_NCOL] = {0}, dl[FM1_NCOL] = {0};
uint32_t k, c, keys, guide;
uint8_t nl[FM1_NCOL] = {0}, dl[FM1_NCOL] = {0}, bl[FM1_NCOL] = {0};
uint32_t k, c, keys, guide, back;
static uint8_t ready;
if (!ready) {
led_pos_init();
@@ -129,7 +198,8 @@ static void ui_leds(void)
}
led_put(nl, panel.btn[ui.layer != LY_PLAY ? LAYER_BTN[ui.layer] : cur_btn()],
ly_lock == LY_PLAY || ((fm1_ms / 300u) & 1u) != 0u || (fm1_in.buttons & ly_bit[ly_lock % LY_COUNT]) != 0u); /* locked: blinks */
led_put(nl, panel.btn[B_PLAY], play_led() || (song.playing && !song.rec && ft_on));
led_put(nl, panel.btn[B_PLAY], play_led() || (song.playing && !song.rec && ft_on) ||
(ci_on && ci_u % BEAT_U < BEAT_U / 4u)); /* (the count-in's beats) */
led_put(nl, panel.btn[B_REC], song.rec != 0u || ft_on || (rec_wait && ((fm1_ms / 125u) & 1u)) ||
(ui.hold_kind == 1u && ((fm1_ms / 60u) & 1u))); /* blinks: armed; fast: clearing */
if (is_drum(TSEL)) { /* the drum track: OCT- / OCT+ lit while ghost / hard */
@@ -140,15 +210,22 @@ static void ui_leds(void)
led_put(nl, panel.btn[B_OCTUP], song.octave > 0);
}
keys = keys_lit();
guide = keys_guide() & ~keys;
guide = (keys_guide() | keys_notes_dim()) & ~keys;
back = lights_keys_mask() & ~keys & ~guide;
for (k = 0; k < 27u; k++) {
led_put(nl, 14u + k, (int)((keys >> k) & 1u));
led_put(dl, 14u + k, (int)((guide >> k) & 1u));
led_put(bl, 14u + k, (int)((back >> k) & 1u));
}
if (lights_lvl) /* menu LIGHTS: every button glows, the lit ones stay full */
for (k = 0; k < NB; k++)
led_put(bl, panel.btn[k], 1);
for (c = 0; c < FM1_NCOL; c++) {
fm1_led[c] = nl[c];
fm1_led_dim[c] = dl[c];
fm1_led_bg[c] = (uint8_t)(bl[c] & ~nl[c]);
}
fm1_led_bg_ns = LIGHTS_NS[lights_lvl % LIGHTS_N];
}
/* ---------------------------------------------------------- input --- */
@@ -247,7 +324,7 @@ static void project_new(void)
}
TDRUM->p[P_E0] = DRUM_DEFAULT_KIT;
for (i = 0; i < G_COUNT; i++)
if (i != G_SLOT && i != G_DRCH)
if (i != G_SLOT && i != G_DRCH && i != G_SYNC)
song.g[i] = GP[i].def;
song.solo = 0;
song.octave = 0;
@@ -577,6 +654,38 @@ static int layers_input(uint32_t note_edges, uint32_t *pressed, uint32_t home)
return 1;
}
/* the REC screen while armed (ui_studio.c rec_screen_draw): KNOB 1 MODE free / tempo (an empty
* project), KNOB 2 the length of the selected track (1, 2 or 4 bars), KNOB 3 START note / count;
* MODE and START are settings of the FM-1 (panel.c lights_word: saved once stopped) */
static void rec_knobs(void)
{
static const uint8_t LENS[3] = {16u, 32u, 64u};
int32_t s;
uint32_t empty = (uint32_t)project_empty(), tempo = !empty || rec_tempo;
if ((s = panel_enc(EN_K1)) != 0 && empty) {
rec_tempo = (uint8_t)(s > 0);
settings_later = 1;
ui.hot_col = 0, ui.hot_t = 40;
}
if ((s = panel_enc(EN_K2)) != 0 && tempo) {
track_t *t = TSEL;
int32_t len = t->p[P_SLEN], i, to = len;
if (s > 0) {
for (i = 0; i < 3; i++) if (LENS[i] > len) { to = LENS[i]; break; }
} else {
for (i = 2; i >= 0; i--) if (LENS[i] < len) { to = LENS[i]; break; }
}
t->p[P_SLEN] = (int16_t)to;
ui.hot_col = 1, ui.hot_t = 40;
}
if ((s = panel_enc(EN_K3)) != 0 && tempo) {
rec_count = (uint8_t)(s > 0);
settings_later = 1;
ui.hot_col = 2, ui.hot_t = 40;
}
panel_enc(EN_K4);
}
/* REC: acts on the press (no lag). Held 0.7 s the press is undone and a ring fills: held on to the
* end, the selected track is cleared (EDIT + OCT- brings it back); let go before, nothing happens.
* (SAVE is the SONG layer: ui_layers.c; tapped, layer_tap) */
@@ -682,9 +791,11 @@ static void ui_input(void)
return;
pressed &= 1u << panel.btn[B_PLAY]; /* PLAY still plays */
}
if (rec_wait || ft_on) { /* the REC screen is up: KNOB 1..4 edit nothing */
for (k = 0; k < 4u; k++) /* hidden (tempo and sound still work; the track */
panel_enc(EN_K1 + k); /* too, while armed: the arm follows) */
if (rec_wait && !ft_on && !ci_on) { /* the REC screen, armed: how it records */
rec_knobs(); /* (tempo and sound still work; the track too: */
} else if (rec_wait || ft_on) { /* the arm follows) */
for (k = 0; k < 4u; k++) /* a take / the count-in: KNOB 1..4 edit nothing */
panel_enc(EN_K1 + k);
}
#if FELUCCA_ARRANGER
if (on_song_page()) {
+44 -10
View File
@@ -1,14 +1,19 @@
/* SPDX-License-Identifier: GPL-3.0-only
* Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments */
/* SLOOP menu (HOME held): COLOR, LOWCUT, ZOOM, HARDWARE CALIBRATION, ABOUT. */
/* SLOOP menu (HOME held): COLOR, LOWCUT, ZOOM, LIGHTS, KEYS, NOTES, USB AUDIO, HARDWARE CALIBRATION, ABOUT. */
/* ------------------------------------------------------------ menu --- */
enum { MI_COLOR, MI_LOWCUT, MI_ZOOM, MI_PANEL, MI_ABOUT, MI_BACK, MI_COUNT };
static const char *const MI_NAME[MI_COUNT] = {"COLOR", "LOWCUT", "ZOOM", "HARDWARE CALIBRATION", "ABOUT", "BACK"};
enum { MI_COLOR, MI_LOWCUT, MI_ZOOM, MI_LIGHTS, MI_KEYS, MI_NOTES, MI_USB, MI_PANEL, MI_ABOUT, MI_BACK, MI_COUNT };
static const char *const MI_NAME[MI_COUNT] = {"COLOR", "LOWCUT", "ZOOM", "LIGHTS", "KEYS", "NOTES", "USB AUDIO",
"HARDWARE CALIBRATION", "ABOUT", "BACK"};
static const char *const LIGHTS_NAME[LIGHTS_N] = {"OFF", "LOW", "MID", "HIGH"}; /* every button lit, the labels readable */
static const char *const KEYS_NAME[KEYS_N] = {"OFF", "C KEYS", "WHITE KEYS"}; /* keys lit too, at the LIGHTS level */
#define MI_DY 18 /* rows between two menu lines */
static void draw_menu(void)
{
uint32_t i, pass, sig = ui.menu * 7u + ui.menu_sel * 131u + settings.palette * 1009u + settings.lowcut * 7919u +
settings.zoom * 104729u;
settings.zoom * 104729u + lights_lvl * 1299709u + lights_keys * 15485863u +
lights_notes * 32452843u + usb_full * 49979687u;
if (!ui.force && sig == ui.menu_sig)
return;
ui.menu_sig = sig;
@@ -40,22 +45,29 @@ static void draw_menu(void)
cv_text(4, 198, &FONT_S, "VOICE: REF. KLATTSCH (MIT)", C_DIM);
} else {
for (i = 0; i < MI_COUNT; i++) {
int32_t y = 4 + (int32_t)i * 24;
int32_t y = 4 + (int32_t)i * MI_DY;
int sel = i == ui.menu_sel;
if (sel)
cv_rect(4, y + 6, 3, 3, C_WHITE);
cv_text(14, y, &FONT_S, MI_NAME[i], sel ? C_WHITE : C_GRAY);
if (i == MI_LOWCUT || i == MI_ZOOM)
cv_text(90, y, &FONT_S, (i == MI_LOWCUT ? settings.lowcut : settings.zoom) ? "ON" : "OFF", C_HI);
if (i == MI_LOWCUT || i == MI_ZOOM || i == MI_NOTES)
cv_text(100, y, &FONT_S, (i == MI_LOWCUT ? settings.lowcut : i == MI_ZOOM ? settings.zoom : lights_notes)
? "ON" : "OFF", C_HI);
if (i == MI_LIGHTS)
cv_text(100, y, &FONT_S, LIGHTS_NAME[lights_lvl % LIGHTS_N], C_HI);
if (i == MI_USB) /* the USB audio input: follows MASTER, or full level */
cv_text(100, y, &FONT_S, usb_full ? "FULL" : "MASTER", C_HI);
if (i == MI_KEYS)
cv_text(100, y, &FONT_S, KEYS_NAME[lights_keys % KEYS_N], lights_lvl ? C_HI : C_DIM); /* (needs LIGHTS) */
if (i == MI_COLOR) {
uint32_t k;
cv_text(90, y, &FONT_S, PALETTES[settings.palette].name, C_HI);
cv_text(100, y, &FONT_S, PALETTES[settings.palette].name, C_HI);
for (k = 0; k < 5u; k++)
cv_rect(160 + (int32_t)k * 14, y + 3, 10, 10, pal[k]);
}
}
cv_text(4, 170, &FONT_S, "PRESETS MOVE", C_DIM);
cv_text(4, 188, &FONT_S, "OCT+ OK OCT- BACK", C_DIM);
cv_text(4, 4 + MI_COUNT * MI_DY + 4, &FONT_S, "PRESETS MOVE KNOB 1 SET", C_DIM);
cv_text(4, 4 + MI_COUNT * MI_DY + 18, &FONT_S, "OCT+ OK OCT- BACK", C_DIM);
}
cv_oy = 0;
cv_blit(0, H_HEAD + 1 + pass * 124u);
@@ -106,6 +118,28 @@ static void menu_input(uint32_t pressed)
fx_lowcut = (uint8_t)(settings.lowcut != 0);
ok = 0;
}
if ((s != 0 || ok) && ui.menu == 1 && ui.menu_sel == MI_USB) { /* right FULL, left MASTER; OCT+ toggles */
usb_full = (uint8_t)(s > 0 ? 1u : s < 0 ? 0u : !usb_full);
ok = 0;
}
if ((s != 0 || ok) && ui.menu == 1 && ui.menu_sel == MI_NOTES) { /* (the same: right ON, left OFF) */
lights_notes = (uint8_t)(s > 0 ? 1u : s < 0 ? 0u : !lights_notes);
ok = 0;
}
if ((s != 0 || ok) && ui.menu == 1 && (ui.menu_sel == MI_LIGHTS || ui.menu_sel == MI_KEYS)) {
/* KNOB 1: brighter / dimmer (stops at the ends); OCT+ steps round */
uint8_t *v = ui.menu_sel == MI_LIGHTS ? &lights_lvl : &lights_keys;
uint32_t n = ui.menu_sel == MI_LIGHTS ? LIGHTS_N : KEYS_N;
if (s > 0 && *v + 1u < n)
(*v)++;
else if (s < 0 && *v > 0u)
(*v)--;
else if (!s)
*v = (uint8_t)((*v + 1u) % n);
if (ui.menu_sel == MI_KEYS && lights_keys && !lights_lvl)
lights_lvl = LIGHTS_LOW; /* keys lit need a level: the lowest */
ok = 0;
}
if (ok && ui.menu == 1) {
switch (ui.menu_sel) {
case MI_COLOR: /* OCT+ steps through the palettes too */
+115 -55
View File
@@ -492,28 +492,69 @@ static void te_digit(int32_t x, int32_t y, int32_t w, int32_t h, int32_t t, uint
}
static uint8_t rec_shown;
/* REC armed (stopped: waiting for the first note) or a free take running (seq.c). The four
* tracks stay in view below; the REC LED blinks while armed, is lit during the take. */
/* the four tracks, compact, from y0: the one that records is framed in red */
static void rec_rows(uint32_t rt, uint32_t take, uint32_t y0, uint32_t *cache)
{
uint32_t sig = rt * 3u + rec_wait + take * 5u + drum_kit() * 977u + y0, i, j;
for (i = 0; i < NTRK; i++) {
char b[16];
if (i == TRK_DRUM) str_cpy(b, DRUM_KIT_NAMES[drum_kit()], sizeof b);
else trk_short_name(i, b);
sig = studio_hash(sig, b) + (uint32_t)trk[i].p[P_SLEN] * 31u;
for (j = 0; j < NSTEP; j++) sig = sig * 3u + (uint32_t)trk_step_on(&trk[i], j);
}
if (!ui.force && sig == *cache)
return;
*cache = sig;
cv_begin(240, 76, C_BLACK);
for (i = 0; i < NTRK; i++) {
const track_t *t = &trk[i];
uint32_t len = (uint32_t)clamp(t->p[P_SLEN], 1, 64), armed = i == rt;
int32_t y = (int32_t)i * 19;
char b[16];
if (armed) cv_rect(0, y, 240, 18, TE_RED), cv_rect(1, y + 1, 238, 16, C_BLACK);
cv_rect(4, y + 3, 12, 12, armed ? TE_COL[i] : TE_DIM[i]);
if (i == TRK_DRUM) str_cpy(b, DRUM_KIT_NAMES[drum_kit()], sizeof b);
else trk_short_name(i, b);
b[10] = 0;
cv_text(22, y + 1, &FONT_S, b, armed ? C_WHITE : TE_G3);
for (j = 0; j < 16u; j++) {
uint32_t a = j * len / 16u, z = (j + 1u) * len / 16u, k, on = 0;
if (z == a) z = a + 1u;
for (k = a; k < z && k < NSTEP; k++) if (trk_step_on(t, k)) on = 1;
cv_rect(106 + (int32_t)j * 8, y + 5, 6, 8, on ? (armed ? TE_COL[i] : TE_DIM[i]) : TE_G1);
}
}
cv_blit(0, y0);
}
/* REC armed (stopped: waiting for the first note, or PLAY), its count-in, or a free take running
* (seq.c). Armed, the dials say how it records: KNOB 1 MODE free / tempo (an empty project),
* KNOB 2 LENGTH (1, 2 or 4 bars), KNOB 3 START note / count (ui_input.c rec_knobs). The four tracks
* stay in view; the REC LED blinks while armed, is lit during the take. */
static void rec_screen_draw(void)
{
static uint32_t head, body, rows, foot;
uint32_t sig, i, j, take = ft_on, empty = take || project_empty(), rt = take ? ft_trk % NTRK : song.sel;
static uint32_t head, body, rows, foot, dials;
static uint8_t layout;
uint32_t sig, take = ft_on, empty = take || project_empty(), rt = take ? ft_trk % NTRK : song.sel;
uint32_t blink = (fm1_ms / 250u) & 1u, secs = take ? ft_t * CTL / FS : 0u, bars = 0, bpm = 0;
uint32_t lay = take ? 1u : 2u, free = empty && !rec_tempo && !take, count = ci_on;
if (take)
bars = ft_fit(ft_t, &bpm);
if (!rec_shown) {
if (!rec_shown || lay != layout) {
lcd_fill(0, 0, 240, 240, C_BLACK);
ui.force = 1;
}
rec_shown = 1;
te_header(take ? "free take" : "rec ready", TE_RED, &head);
sig = take * 1000003u + empty * 7u + rt * 7919u + blink * 31u + secs * 131u + bars * 17u + bpm * 3u;
if (ui.force || sig != body) {
char b[24];
body = sig;
cv_begin(240, 106, C_BLACK);
if (take) { /* free take: the time, the loop it makes */
layout = (uint8_t)lay;
te_header(take ? "free take" : count ? "count-in" : "rec ready", TE_RED, &head);
if (take) { /* free take: the time, the loop it makes */
sig = 1000003u + rt * 7919u + blink * 31u + secs * 131u + bars * 17u + bpm * 3u;
if (ui.force || sig != body) {
char b[24];
uint32_t n = secs > 99u ? 99u : secs;
body = sig;
cv_begin(240, 106, C_BLACK);
te_disc(18, 30, 9, blink ? TE_RED : TE_DIM[3]);
if (n >= 10u)
te_digit(36, 4, 32, 56, 7, n / 10u, C_WHITE);
@@ -531,52 +572,71 @@ static void rec_screen_draw(void)
cv_text(146, 4, &FONT_L, "-", TE_G3);
}
te_text_c(120, 80, "press rec on the 1", TE_RED);
} else { /* ready: the first note starts everything */
te_disc(120, 30, 22, blink ? TE_RED : TE_DIM[3]);
te_disc(120, 30, 9, C_BLACK);
te_text_c(120, 62, empty ? "play freely" : "play a note", C_WHITE);
te_text_c(120, 80, empty ? "then rec on the 1" : "it starts the loop", TE_G3);
cv_blit(0, 42);
}
rec_rows(rt, take, 148u, &rows);
if (ui.force || foot != 1u) {
foot = 1u;
cv_begin(240, 16, C_BLACK);
cv_text(4, 0, &FONT_S, "rec: close", TE_G3);
cv_text(236 - text_w(&FONT_S, "play: drop"), 0, &FONT_S, "play: drop", TE_G3);
cv_blit(0, 224);
}
return;
}
foot = 0;
/* armed / counting in: what happens next */
sig = 2000003u + empty * 7u + free * 11u + rec_count * 13u + count * 17u + ci_beat * 19u + blink * 31u;
if (ui.force || sig != body) {
static const char *const L1[3] = {"play freely", "play a note", "press play"};
static const char *const L2[3] = {"then rec on the 1", "it starts the loop", "4 clicks, then rec"};
static const char *const L3[3] = {"the tempo follows you", "play: go rec: cancel", "rec: cancel"};
uint32_t m = free ? 0u : rec_count ? 2u : 1u;
body = sig;
cv_begin(240, 64, C_BLACK);
if (count) { /* the count-in: 4, 3, 2, 1 */
te_digit(96, 4, 30, 54, 6, 4u - (ci_beat > 3u ? 3u : ci_beat), C_WHITE);
te_disc(60, 31, 12, TE_RED);
cv_text(144, 14, &FONT_S, "count-in", TE_G4);
cv_text(144, 34, &FONT_S, "rec: cancel", TE_G3);
} else {
te_disc(28, 30, 18, blink ? TE_RED : TE_DIM[3]);
te_disc(28, 30, 7, C_BLACK);
cv_text(60, 6, &FONT_S, L1[m], C_WHITE);
cv_text(60, 24, &FONT_S, L2[m], TE_G4);
cv_text(60, 42, &FONT_S, L3[m], TE_G3);
}
cv_blit(0, 42);
}
/* the four tracks, compact: the one that records is framed in red */
sig = rt * 3u + rec_wait + take * 5u + drum_kit() * 977u;
for (i = 0; i < NTRK; i++) {
char b[16];
if (i == TRK_DRUM) str_cpy(b, DRUM_KIT_NAMES[drum_kit()], sizeof b);
else trk_short_name(i, b);
sig = studio_hash(sig, b) + (uint32_t)trk[i].p[P_SLEN] * 31u;
for (j = 0; j < NSTEP; j++) sig = sig * 3u + (uint32_t)trk_step_on(&trk[i], j);
}
if (ui.force || sig != rows) {
rows = sig;
cv_begin(240, 76, C_BLACK);
for (i = 0; i < NTRK; i++) {
const track_t *t = &trk[i];
uint32_t len = (uint32_t)clamp(t->p[P_SLEN], 1, 64), armed = i == rt;
int32_t y = (int32_t)i * 19;
char b[16];
if (armed) cv_rect(0, y, 240, 18, TE_RED), cv_rect(1, y + 1, 238, 16, C_BLACK);
cv_rect(4, y + 3, 12, 12, armed ? TE_COL[i] : TE_DIM[i]);
if (i == TRK_DRUM) str_cpy(b, DRUM_KIT_NAMES[drum_kit()], sizeof b);
else trk_short_name(i, b);
b[10] = 0;
cv_text(22, y + 1, &FONT_S, b, armed ? C_WHITE : TE_G3);
for (j = 0; j < 16u; j++) {
uint32_t a = j * len / 16u, z = (j + 1u) * len / 16u, k, on = 0;
if (z == a) z = a + 1u;
for (k = a; k < z && k < NSTEP; k++) if (trk_step_on(t, k)) on = 1;
cv_rect(106 + (int32_t)j * 8, y + 5, 6, 8, on ? (armed ? TE_COL[i] : TE_DIM[i]) : TE_G1);
}
rec_rows(rt, 0u, 106u, &rows);
{ /* the dials: how it records */
static char v[3][10];
static const char *const LAB_E[4] = {"mode", "length", "start", ""};
static const char *const LAB_F[4] = {"mode", "", "", ""};
static const char *const LAB_N[4] = {"", "length", "start", ""};
static const char *const LAB_0[4] = {"", "", "", ""};
const char *val[4] = {v[0], v[1], v[2], ""};
int32_t ratio[4] = {0, 0, 0, 0};
uint32_t len = (uint32_t)clamp(TSEL->p[P_SLEN], 1, 64);
str_cpy(v[0], rec_tempo ? "tempo" : "free", sizeof v[0]);
if (len % 16u == 0u) {
fmt_int(v[1], (int32_t)(len / 16u));
str_cpy(v[1] + str_len(v[1]), len == 16u ? " bar" : " bars", 6);
} else {
fmt_int(v[1], (int32_t)len);
str_cpy(v[1] + str_len(v[1]), " st", 4);
}
str_cpy(v[2], rec_count ? "count" : "note", sizeof v[2]);
ratio[0] = rec_tempo ? 1000 : 0;
ratio[1] = (int32_t)(len - 1u) * 1000 / 63;
ratio[2] = rec_count ? 1000 : 0;
{
const char *const *lab = count ? LAB_0 : !empty ? LAB_N : free ? LAB_F : LAB_E;
uint32_t k;
for (k = 0; k < 4u; k++)
if (!lab[k][0])
val[k] = ""; /* (a dial not shown: no value either) */
te_dials(184, lab, val, ratio, rt * 7u + count * 3u, &dials);
}
cv_blit(0, 148);
}
sig = take;
if (ui.force || sig != foot) {
foot = sig;
cv_begin(240, 16, C_BLACK);
cv_text(4, 0, &FONT_S, take ? "rec: close" : "rec: cancel", TE_G3);
cv_text(236 - text_w(&FONT_S, take ? "play: drop" : "play: go"), 0, &FONT_S, take ? "play: drop" : "play: go", TE_G3);
cv_blit(0, 224);
}
}
+407 -34
View File
@@ -7,8 +7,20 @@
* SysEx F0 22 24 35 7D F7 (soft key) asks the main loop to enter UBOOT.
* VID 0x1209 / PID 0x0001 is the pid.codes test id.
* FELUCCA_CDC=1 adds a CDC-ACM serial function (IAD composite: EP2 notify,
* EP3 bulk data) for the console in console.c. */
* EP3 bulk data) for the console in console.c.
* FELUCCA_UAC=1 adds a USB audio input (UAC1, class compliant): the master
* output as 16-bit stereo at 44.1 kHz on an isochronous asynchronous IN
* endpoint (EP4), so a computer can record the FM-1 over the cable. audio.c
* fills a ring (uac_render_start, uac_tap); uac_service sends one packet per
* USB frame from the TIMER5 ISR, nested in the render too (main.c). The
* update loader leaves both off: MIDI only. */
#include "../hal/fm1_usb.h" /* registers; relative, so the loader and the host tests find it too */
#ifndef FELUCCA_CDC
#define FELUCCA_CDC 0
#endif
#ifndef FELUCCA_UAC
#define FELUCCA_UAC 0
#endif
enum { S_FADDR = 0, S_POWER = 1, S_INTRTX1 = 2, S_INTRTX2 = 3, S_INTRRX1 = 4, S_INTRRX2 = 5, S_INTRUSB = 6,
S_INTRTX1E = 7, S_INTRTX2E = 8, S_INTRRX1E = 9, S_INTRRX2E = 10, S_INTRUSBE = 11, S_FRAME1 = 12,
S_FRAME2 = 13, S_INDEX = 14,
@@ -36,12 +48,52 @@ static struct {
} cdc = {{0x00, 0xC2, 0x01, 0x00, 0, 0, 8}}; /* 115200 8N1 */
#endif
#if FELUCCA_UAC
/* USB audio input. The I2S clock is not locked to USB (about 44,117.6 Hz against the host's 44,100):
* the endpoint is asynchronous, so each 1 ms packet carries what the ring holds, 44 or 45 frames
* (the 44.1 pattern) and one more or one fewer while the ring's fill drifts out of its band.
* The render writes HALF_FRAMES (128) frames every 2.9 ms; the fill measured when a render starts is
* the low point of that saw tooth, and is kept in UA_LO..UA_HI. A frame waits in the ring for that fill
* plus its place in the render: 80..256 frames, ~3.8 ms on average (256-frame halves and a 96..160
* band: ~5.8 ms). Measured under load (65 % CPU): a 64..112 band started renders at
* 48..119 with no glitch; one render was once seen 29 frames under the floor: a packet (46) must
* still be in hand then. */
#define UA_N 512u /* ring, frames (16-bit L | R << 16); a power of two */
#define UA_PRIME 104u /* silence ahead of the first rendered frame */
#define UA_LO 80u /* a render may start late: keep a packet and more in hand */
#define UA_HI 128u
#define UA_MAXF 46u /* frames in the largest packet */
#define UAC_MAXP (UA_MAXF * 4u)
#define UAC_RATE 44100u
_Static_assert(UA_HI + HALF_FRAMES + UA_MAXF < UA_N, "the ring holds the band, a render and a packet");
static uint32_t ua_ring[UA_N];
static volatile uint32_t ua_w, ua_r;
static uint32_t ep4tx[UA_MAXF] __attribute__((aligned(4)));
static struct {
volatile uint8_t alt; /* streaming interface setting: 1 = the host records */
volatile uint8_t go; /* the ring is primed: the consumer reads it (0: silence packets) */
volatile uint8_t flowing; /* the host takes our packets (it may set alt 1 well before it reads) */
uint8_t queued; /* a packet was queued since the stream (re)started */
uint8_t feed; /* this render feeds the ring (sampled when it starts) */
uint8_t wait; /* polls the queued packet has waited */
uint8_t e0_rx; /* SET_CUR sampling frequency: data stage pending */
volatile uint32_t fill_min; /* ring fill when the last render started */
uint32_t acc; /* 44.1 frames per ms: 0.1 frame steps */
uint32_t last; /* the last frame sent, repeated on an underrun */
uint32_t starts, pkts, frames; /* frames in packets sent from the ring */
uint32_t underruns, overruns, missed; /* glitches: ring empty (repeat), ring full (drop), no packet ready */
uint32_t stalls; /* the host stopped reading for > 20 ms (alt still 1) */
uint32_t adj_up, adj_down; /* packets one frame longer / shorter than the pattern */
uint32_t fill_lo, fill_hi; /* range of fill_min since the stream started */
} uac;
#endif
static struct {
uint8_t up, config, pend_addr, has_pend_addr, e0_tx, e0_zlp;
const uint8_t *e0_src;
uint16_t e0_left;
uint32_t resets, setups, rx_pkts, tx_pkts, sof_seen, timeouts, no_sof;
uint32_t suspends, max_gap, retries, frame_stalls;
uint32_t suspends, max_gap, retries, frame_stalls; /* diagnostics: suspend events, longest run of polls without SOF */
uint16_t frame, frame_same; /* last SOF frame number and how long it has not moved (x 10 ms) */
uint8_t detached; /* usb_detach() was called: no retry */
volatile uint8_t suspended; /* bus idle > 3 ms (unplugged or host asleep): the UI hides "USB" */
@@ -50,6 +102,8 @@ static struct {
uint8_t sx_len, sx_on;
volatile uint8_t uboot_req;
volatile uint8_t ota_req; /* F0 22 24 35 7F F7: M-UPGRADE upgrade command (FELUCCA_OTA) */
uint8_t rx_pend; /* EP1 OUT packet seen, not yet taken (the MIDI ring was too full) */
uint32_t rx_held, rx_bad; /* packets held back (NAK) for room, malformed events ignored */
} usb;
#if FELUCCA_OTA
@@ -69,7 +123,6 @@ static volatile uint32_t so_w, so_r;
#define MQ 64u
static uint32_t midi_in_q[MQ], midi_out_q[MQ];
static volatile uint32_t mi_w, mi_r, mo_w, mo_r;
static void midi_out_event(uint32_t pkt) /* from the audio ISR */
{
if (usb.config && mo_w - mo_r < MQ) {
@@ -80,24 +133,36 @@ static void midi_out_event(uint32_t pkt) /* from the audio ISR */
}
/* ------------------------------------------------------- descriptors --- */
/* interfaces: 0 audio control, 1 MIDI streaming, 2 audio streaming (FELUCCA_UAC), then CDC's two.
* bcdDevice: 3.00 MIDI, +0.01 CDC, +0.10 the audio input (hosts cache descriptors per version) */
#define CDC_IF (2 + FELUCCA_UAC)
#define UAC_AS_IF 2u
#define CFG_LEN (101 + 74 * FELUCCA_CDC + 74 * FELUCCA_UAC)
#define USB_NIF (2 + FELUCCA_UAC + 2 * FELUCCA_CDC)
#if FELUCCA_CDC
static const uint8_t DEV_DESC[18] = {18, 1, 0x00, 0x02, 0xEF, 0x02, 0x01, 64, 0x09, 0x12, 0x01, 0x00, 0x01, 0x03,
1, 2, 0, 1}; /* misc/IAD, bcdDevice 3.01 */
static const uint8_t CFG_DESC[175] = {
9, 2, 175, 0, 4, 1, 0, 0x80, 50,
8, 0x0B, 0, 2, 1, 1, 0, 0, /* IAD: MIDI (IF 0-1) */
static const uint8_t DEV_DESC[18] = {18, 1, 0x00, 0x02, 0xEF, 0x02, 0x01, 64, 0x09, 0x12, 0x01, 0x00,
0x01 + 0x10 * FELUCCA_UAC, 0x03, 1, 2, 0, 1}; /* misc/IAD */
static const uint8_t CFG_DESC[] = {
9, 2, CFG_LEN & 0xFF, CFG_LEN >> 8, USB_NIF, 1, 0, 0x80, 50,
8, 0x0B, 0, 2 + FELUCCA_UAC, 1, 1, 0, 0, /* IAD: audio + MIDI (IF 0-1, 0-2) */
#else
#ifndef FELUCCA_USB_PID
#define FELUCCA_USB_PID 0x0001 /* the update loader is 0x0002 */
#endif
static const uint8_t DEV_DESC[18] = {18, 1, 0x10, 0x01, 0, 0, 0, 64, 0x09, 0x12, FELUCCA_USB_PID & 0xFF,
FELUCCA_USB_PID >> 8, 0x00, 0x03,
FELUCCA_USB_PID >> 8, 0x00 + 0x10 * FELUCCA_UAC, 0x03,
1, 2, 0, 1};
static const uint8_t CFG_DESC[101] = {
9, 2, 101, 0, 2, 1, 0, 0x80, 50,
static const uint8_t CFG_DESC[] = {
9, 2, CFG_LEN & 0xFF, CFG_LEN >> 8, USB_NIF, 1, 0, 0x80, 50,
#endif
9, 4, 0, 0, 0, 1, 1, 0, 0,
#if FELUCCA_UAC
10, 0x24, 1, 0x00, 0x01, 31, 0, 2, 1, UAC_AS_IF, /* AC header 1.00: MIDI + audio streaming */
12, 0x24, 2, 1, 0x03, 0x06, 0, 2, 0x03, 0x00, 0, 0, /* input terminal 1: line, 2 ch (L R) */
9, 0x24, 3, 2, 0x01, 0x01, 0, 1, 0, /* output terminal 2: USB streaming, from 1 */
#else
9, 0x24, 1, 0x00, 0x01, 9, 0, 1, 1,
#endif
9, 4, 1, 0, 2, 1, 3, 0, 0,
7, 0x24, 1, 0x00, 0x01, 0x41, 0x00,
6, 0x24, 2, 1, 1, 0,
@@ -108,19 +173,29 @@ static const uint8_t CFG_DESC[101] = {
5, 0x25, 1, 1, 1,
9, 5, 0x81, 2, 64, 0, 0, 0, 0,
5, 0x25, 1, 1, 3,
#if FELUCCA_UAC
9, 4, UAC_AS_IF, 0, 0, 1, 2, 0, 0, /* IF2 audio streaming, alt 0: no bandwidth */
9, 4, UAC_AS_IF, 1, 1, 1, 2, 0, 0, /* alt 1: the stream */
7, 0x24, 1, 2, 1, 0x01, 0x00, /* AS general: terminal 2, delay 1, PCM */
11, 0x24, 2, 1, 2, 2, 16, 1, UAC_RATE & 0xFF, (UAC_RATE >> 8) & 0xFF, UAC_RATE >> 16,
/* type I: 2 ch, 16 bit, one rate */
9, 5, 0x84, 0x05, UAC_MAXP & 0xFF, UAC_MAXP >> 8, 1, 0, 0, /* EP4 IN isochronous async, 1 ms */
7, 0x25, 1, 0x01, 0, 0, 0, /* CS endpoint: sampling frequency control */
#endif
#if FELUCCA_CDC
8, 0x0B, 2, 2, 2, 2, 1, 0, /* IAD: CDC ACM (IF 2-3) */
9, 4, 2, 0, 1, 2, 2, 1, 0, /* IF2 communication */
8, 0x0B, CDC_IF, 2, 2, 2, 1, 0, /* IAD: CDC ACM (IF 2-3, 3-4) */
9, 4, CDC_IF, 0, 1, 2, 2, 1, 0, /* communication */
5, 0x24, 0x00, 0x10, 0x01, /* header 1.10 */
5, 0x24, 0x01, 0x00, 3, /* call management: data IF 3 */
5, 0x24, 0x01, 0x00, CDC_IF + 1, /* call management: the data IF */
4, 0x24, 0x02, 0x02, /* ACM: line coding + state */
5, 0x24, 0x06, 2, 3, /* union 2 -> 3 */
5, 0x24, 0x06, CDC_IF, CDC_IF + 1, /* union */
7, 5, 0x82, 3, 8, 0, 16, /* EP2 IN interrupt (never sent) */
9, 4, 3, 0, 2, 0x0A, 0, 0, 0, /* IF3 data */
9, 4, CDC_IF + 1, 0, 2, 0x0A, 0, 0, 0, /* data */
7, 5, 0x03, 2, 64, 0, 0, /* EP3 OUT bulk */
7, 5, 0x83, 2, 64, 0, 0, /* EP3 IN bulk */
#endif
};
typedef char cfg_len_ok[sizeof CFG_DESC == CFG_LEN ? 1 : -1];
static const uint8_t STR0[4] = {4, 3, 0x09, 0x04};
static const uint8_t STR1[] = {42, 3, 'H', 0, 0xFC, 0, 'g', 0, 'e', 0, 'l', 0, 't', 0, 'o', 0, 'n', 0, ' ', 0, 'I', 0,
'n', 0, 's', 0, 't', 0, 'r', 0, 'u', 0, 'm', 0, 'e', 0, 'n', 0, 't', 0, 's', 0};
@@ -195,6 +270,34 @@ static uint32_t sie_rd(uint32_t r)
return fm1_usb_sie_data();
}
#if FELUCCA_UAC
static void uac_ep4_reset(void) /* drop a queued packet; isochronous mode */
{
sie_wr(S_INDEX, 4);
sie_wr(S_TXCSR1, 0x48); /* ClrDataTog + FlushFIFO (SDK usb_g_ep_config) */
sie_wr(S_TXCSR2, 0);
sie_wr(S_TXCSR1, 0);
sie_wr(S_TXCSR2, 0x40); /* ISO */
}
static void uac_stream(uint32_t alt) /* SET_INTERFACE, configuration, bus reset */
{
uac.go = 0; /* the next render primes the ring again */
uac.flowing = 0; /* ... once the host has taken a packet */
uac.queued = 0;
uac.wait = 0;
RING_PUBLISH();
uac.alt = (uint8_t)alt;
uac.acc = 0;
uac.last = 0;
if (alt) { /* (the fill range of the last stream stays readable) */
uac.starts++;
uac.fill_lo = 0xFFFFFFFFu;
uac.fill_hi = 0;
}
}
#endif
static void ep1_config(void)
{
fm1_usb_ep_txbuf(1, ep1tx);
@@ -227,6 +330,14 @@ static void ep1_config(void)
fm1_usb_ep_enable((1u << 2) | (1u << 3));
cdc.rx_pend = 1; /* look once: a packet may already wait */
#endif
#if FELUCCA_UAC
fm1_usb_ep4_txbuf(ep4tx);
sie_wr(S_INDEX, 4);
sie_wr(S_TXMAXP, 0xFF);
uac_ep4_reset();
fm1_usb_ep_enable(1u << 4);
uac_stream(0);
#endif
}
static void e0_chunk(void)
@@ -277,6 +388,9 @@ static void ep0_service(void)
usb.e0_tx = 0;
#if FELUCCA_CDC
cdc.e0_rx = 0;
#endif
#if FELUCCA_UAC
uac.e0_rx = 0;
#endif
return;
}
@@ -285,6 +399,9 @@ static void ep0_service(void)
usb.e0_tx = 0;
#if FELUCCA_CDC
cdc.e0_rx = 0; /* else the next SETUP is taken as line coding */
#endif
#if FELUCCA_UAC
uac.e0_rx = 0;
#endif
}
if (usb.e0_tx) {
@@ -303,6 +420,12 @@ static void ep0_service(void)
cdc.e0_rx = 0;
goto ack;
}
#endif
#if FELUCCA_UAC
if (uac.e0_rx) { /* SET_CUR sampling frequency: 44100 is all we */
uac.e0_rx = 0; /* have, whatever the host asks for */
goto ack;
}
#endif
for (i = 0; i < 8u; i++)
s[i] = ep0buf[i];
@@ -333,6 +456,10 @@ static void ep0_service(void)
ep1_config();
else
sie_wr(S_INTRRX1E, 0);
#if FELUCCA_UAC
if (usb.config != 1u)
uac_stream(0);
#endif
goto ack;
case 0x8008:
e0_send(&usb.config, 1, wlength);
@@ -342,11 +469,26 @@ static void ep0_service(void)
case 0x8200:
e0_send(zero2, 2, wlength);
return;
case 0x010B: /* SET_INTERFACE alt 0 */
case 0x010B: /* SET_INTERFACE: alt 0 (alt 1 for the audio stream) */
#if FELUCCA_UAC
if (s[4] == UAC_AS_IF && wvalue <= 1u && usb.config) {
uac_ep4_reset();
uac_stream(wvalue);
goto ack;
}
#endif
if (wvalue == 0)
goto ack;
goto stall;
case 0x810A:
#if FELUCCA_UAC
if (s[4] == UAC_AS_IF) {
static uint8_t alt;
alt = uac.alt;
e0_send(&alt, 1, wlength);
return;
}
#endif
e0_send(zero2, 1, wlength);
return;
case 0x0201: { /* CLEAR_FEATURE(ENDPOINT_HALT): data toggle reset */
@@ -354,6 +496,10 @@ static void ep0_service(void)
uint32_t ep = s[4] & 0x0Fu, last = 3u;
#else
uint32_t ep = s[4] & 0x0Fu, last = 1u;
#endif
#if FELUCCA_UAC
if (wvalue == 0 && s[4] == 0x84u)
goto ack; /* isochronous: no halt, no toggle */
#endif
if (wvalue != 0 || ep > last)
goto stall; /* not an endpoint we have */
@@ -383,6 +529,27 @@ static void ep0_service(void)
goto ack;
case 0x2123: /* SEND_BREAK */
goto ack;
#endif
#if FELUCCA_UAC
case 0x2201: /* SET_CUR, endpoint: sampling frequency */
if (s[4] != 0x84u || s[3] != 1u)
goto stall;
if (wlength) {
uac.e0_rx = 1;
sie_wr(S_INDEX, 0);
sie_wr(S_CSR0, 0x40); /* the 3 bytes follow */
return;
}
goto ack;
case 0xA281: /* GET_CUR / MIN / MAX: the one rate */
case 0xA282:
case 0xA283: {
static const uint8_t RATE[3] = {UAC_RATE & 0xFF, (UAC_RATE >> 8) & 0xFF, UAC_RATE >> 16};
if (s[4] != 0x84u || s[3] != 1u)
goto stall;
e0_send(RATE, 3, wlength);
return;
}
#endif
default:
goto stall;
@@ -400,6 +567,15 @@ stall:
static void sysex_byte(uint8_t b)
{
static const uint8_t UBOOT_KEY[6] = {0xF0, 0x22, 0x24, 0x35, 0x7D, 0xF7};
if (b >= 0xF8u)
return; /* realtime may occur anywhere in SysEx */
if ((b & 0x80u) && b != 0xF0u && b != 0xF7u) {
usb.sx_on = 0;
#if FELUCCA_OTA
sx_collect = 0;
#endif
return; /* another status aborts the unfinished frame */
}
if (b == 0xF0) {
usb.sx_on = 1;
usb.sx_len = 0;
@@ -441,30 +617,81 @@ static void sysex_byte(uint8_t b)
}
}
static void ep1_rx(void)
/* one USB-MIDI event packet: SysEx bytes to sysex_byte, channel voice messages and the clock /
* transport realtime ones to the MIDI ring; a malformed packet (status not matching its CIN, a data
* byte with bit 7) is ignored (after Felucca 1.0) */
static void midi_in_event(uint32_t pkt)
{
uint32_t csr, n, i;
sie_wr(S_INDEX, 1);
csr = sie_rd(S_RXCSR1) | (sie_rd(S_RXCSR2) << 8);
if (!(csr & 1u))
uint32_t cin = pkt & 15u, st = (pkt >> 8) & 0xFFu;
if (cin >= 4u && cin <= 7u) { /* SysEx */
uint32_t k, nb = cin == 4u || cin == 7u ? 3u : cin == 6u ? 2u : 1u;
for (k = 0; k < nb; k++)
sysex_byte((uint8_t)(pkt >> (8u * (k + 1u))));
return;
n = sie_rd(S_RXCOUNT1) | (sie_rd(S_RXCOUNT2) << 8);
if (n > 64u)
n = 64u;
fm1_usb_rx_sync();
for (i = 0; i + 3u < n; i += 4u) {
uint32_t cin = ep1rx[i] & 15u, pkt = (uint32_t)ep1rx[i] | (uint32_t)ep1rx[i + 1] << 8 |
(uint32_t)ep1rx[i + 2] << 16 | (uint32_t)ep1rx[i + 3] << 24;
if (cin >= 4u && cin <= 7u) { /* SysEx */
uint32_t k, nb = cin == 4u || cin == 7u ? 3u : cin == 6u ? 2u : 1u;
for (k = 0; k < nb; k++)
sysex_byte(ep1rx[i + 1 + k]);
} else if (cin >= 8u && cin <= 0xEu && mi_w - mi_r < MQ) {
}
if (st >= 0x80u && st < 0xF8u) { /* channel / system common also ends a SysEx */
usb.sx_on = 0;
#if FELUCCA_OTA
sx_collect = 0;
#endif
}
if (cin == 0xFu && (st == 0xF8u || st == 0xFAu || st == 0xFBu || st == 0xFCu)) { /* clock, transport */
if (mi_w - mi_r < MQ) {
midi_in_q[mi_w % MQ] = 0xFu | st << 8;
RING_PUBLISH();
mi_w++;
}
return;
}
if (cin >= 8u && cin <= 0xEu && (st >> 4) == cin && !((pkt >> 16) & 0x80u) &&
(cin == 0xCu || cin == 0xDu || !(pkt & 0x80000000u))) {
if (mi_w - mi_r < MQ) {
midi_in_q[mi_w % MQ] = pkt;
RING_PUBLISH();
mi_w++;
}
return;
}
if (cin >= 8u)
usb.rx_bad++;
}
/* one EP1 OUT packet (<= 16 events) into the MIDI ring, or 0: fewer than 16 + 8 slots free, so the
* packet stays (the host is NAKed) and is taken on a later poll: a burst from a DAW never drops a
* note-off (0.9 dropped what did not fit: hanging notes), and 8 slots stay for the TRS input, which
* shares the ring and cannot wait. The update loader never drains the ring: no back-pressure there.
* (After Felucca 1.0.) */
#define EP1_ROOM (16u + 8u)
static int ep1_take(const uint8_t *b, uint32_t n)
{
uint32_t i;
#ifndef FELUCCA_LOADER
if (MQ - (mi_w - mi_r) < EP1_ROOM)
return 0;
#endif
for (i = 0; i + 3u < n; i += 4u)
midi_in_event((uint32_t)b[i] | (uint32_t)b[i + 1] << 8 | (uint32_t)b[i + 2] << 16 | (uint32_t)b[i + 3] << 24);
return 1;
}
static void ep1_rx(void) /* leaves the packet (NAK) while the ring is too full */
{
uint32_t csr, n;
sie_wr(S_INDEX, 1);
csr = sie_rd(S_RXCSR1) | (sie_rd(S_RXCSR2) << 8);
if (!(csr & 1u)) {
usb.rx_pend = 0;
return;
}
n = sie_rd(S_RXCOUNT1) | (sie_rd(S_RXCOUNT2) << 8);
if (n > 64u)
n = 64u;
fm1_usb_rx_sync();
if (!ep1_take(ep1rx, n)) {
usb.rx_held++;
return; /* rx_pend stays: taken on a later poll */
}
usb.rx_pend = 0;
usb.rx_pkts++;
csr = (csr & ~0x164u) | 0x10u;
sie_wr(S_RXCSR1, csr & 0xFFu);
@@ -611,6 +838,142 @@ static void ep3_tx(void) /* <= 63 bytes per packe
}
#endif
#if FELUCCA_UAC
/* ---- the audio input: audio.c produces (render start, then each block), TIMER5 consumes ---- */
static __attribute__((noinline)) void uac_render_start(void) /* audio ISR, before a half buffer renders */
{
uint32_t fill;
uac.feed = uac.alt && usb.config && uac.flowing;
if (!uac.feed) {
uac.go = 0; /* not read (yet / any more): prime when it is */
return;
}
if (!uac.go) { /* (re)start: silence ahead, then this render */
uint32_t r = ua_r, i;
for (i = 0; i < UA_PRIME; i++)
ua_ring[(r + i) & (UA_N - 1u)] = 0;
RING_PUBLISH();
ua_w = r + UA_PRIME;
uac.fill_min = UA_PRIME;
RING_PUBLISH();
uac.go = 1;
return;
}
fill = ua_w - ua_r;
uac.fill_min = fill;
if (fill < uac.fill_lo)
uac.fill_lo = fill;
if (fill > uac.fill_hi)
uac.fill_hi = fill;
}
static inline int32_t uac_s16(int32_t v)
{
return v > 32767 ? 32767 : v < -32768 ? -32768 : v;
}
static __attribute__((noinline)) void uac_tap(const int32_t *out, uint32_t n) /* audio ISR: one block (Q15) */
{
uint32_t w = ua_w, i;
if (!uac.feed)
return;
if (UA_N - (w - ua_r) < n) { /* nobody reads: drop the block */
uac.overruns++;
return;
}
#if FELUCCA_UAC_TONE
{ /* bench: triangles of period 100 frames instead of the music (L, R in antiphase): every
* recorded frame must follow the one before, so a lost or repeated frame shows exactly */
static uint32_t ph;
for (i = 0; i < n; i++, ph = ph == 99u ? 0u : ph + 1u) {
uint32_t q = ph < 50u ? ph : 100u - ph, q2 = ph < 50u ? 50u - ph : ph - 50u;
ua_ring[(w + i) & (UA_N - 1u)] = (uint32_t)(uint16_t)(int16_t)((int32_t)q * 1000 - 25000) |
(uint32_t)(uint16_t)(int16_t)((int32_t)q2 * 1000 - 25000) << 16;
}
(void)out;
}
#else
for (i = 0; i < n; i++)
ua_ring[(w + i) & (UA_N - 1u)] = (uint32_t)(uint16_t)uac_s16(out[2u * i]) |
(uint32_t)(uint16_t)uac_s16(out[2u * i + 1u]) << 16;
#endif
RING_PUBLISH();
ua_w = w + n;
}
/* the next packet into d: 44 / 45 frames (+-1 to hold the ring's fill), from the ring or, until it is
* primed, silence. An empty ring repeats the last frame. Returns the frame count. */
static uint32_t uac_packet(uint32_t *d)
{
uint32_t n = 44u, r, fill, k, i;
uac.acc += UAC_RATE % 1000u;
if (uac.acc >= 1000u) {
uac.acc -= 1000u;
n++;
}
if (!uac.go) {
for (i = 0; i < n; i++)
d[i] = 0;
return n;
}
if (uac.fill_min > UA_HI) {
n++;
uac.adj_up++;
} else if (uac.fill_min < UA_LO) {
n--;
uac.adj_down++;
}
r = ua_r;
fill = ua_w - r;
RING_PUBLISH(); /* the slots after the index */
k = fill < n ? fill : n;
for (i = 0; i < k; i++)
d[i] = ua_ring[(r + i) & (UA_N - 1u)];
if (k < n) {
uint32_t last = k ? d[k - 1u] : uac.last;
uac.underruns++;
for (; i < n; i++)
d[i] = last;
}
uac.last = d[n - 1u];
RING_PUBLISH();
ua_r = r + k;
uac.pkts++;
uac.frames += n;
return n;
}
/* TIMER5, 2 kHz, also nested in the render: the host takes one packet per 1 ms frame; queue the
* next one as soon as the last has gone (TxPktRdy clear). Not paced on SOF-pending (see usb_poll).
* The ring is fed only while the host reads: it often selects alt 1 long before its first IN token,
* and a recorder may stop reading without going back to alt 0 (a packet waiting > 20 ms). */
static void uac_service(void)
{
uint32_t csr, n;
if (!usb.up || !usb.config || !uac.alt)
return;
sie_wr(S_INDEX, 4);
csr = sie_rd(S_TXCSR1);
if (csr & 0x01u) { /* still queued */
if (uac.wait < 255u && ++uac.wait == 40u && uac.flowing) {
uac.flowing = 0;
uac.stalls++;
}
return;
}
if (uac.queued) {
if (csr & 0x04u)
uac.missed++; /* UnderRun: an IN token found nothing queued */
uac.flowing = 1;
}
uac.queued = 1;
uac.wait = 0;
n = uac_packet(ep4tx);
fm1_usb_ep4_send(ep4tx, n * 4u);
sie_wr(S_TXCSR1, 0x01); /* TxPktRdy (and UnderRun cleared) */
}
#endif
static void usb_poll(void) /* TIMER5 ISR, 2 kHz */
{
uint32_t iu, it, ir;
@@ -666,10 +1029,15 @@ static void usb_poll(void) /* TIMER5 ISR, 2 kHz */
#endif
usb.e0_tx = 0;
usb.has_pend_addr = 0;
usb.rx_pend = 0;
#if FELUCCA_CDC
cdc.dtr = 0;
cdc.e0_rx = 0;
cdc.rx_pend = 0;
#endif
#if FELUCCA_UAC
uac.e0_rx = 0;
uac_stream(0);
#endif
fm1_usb_ep0_buf(ep0buf);
sie_wr(S_INTRUSBE, 0x07);
@@ -679,6 +1047,8 @@ static void usb_poll(void) /* TIMER5 ISR, 2 kHz */
if (it & 0x01u)
ep0_service();
if (ir & 0x02u)
usb.rx_pend = 1; /* (the flag reads once: remember the packet) */
if (usb.rx_pend)
ep1_rx();
if (usb.config)
ep1_tx();
@@ -692,6 +1062,9 @@ static void usb_poll(void) /* TIMER5 ISR, 2 kHz */
ep3_tx();
}
#endif
#if FELUCCA_UAC
uac_service();
#endif
}
static void usb_start(void) /* boot, or main-loop retry while usb.up == 0 */
+40 -1
View File
@@ -118,6 +118,44 @@ static void voice_kill(voice_t *v) /* fade out over the nex
voice_kills++;
}
/* overload (after Felucca 1.0; audio.c asks for it when two halves in a row took > 85 % of their time):
* fade one voice out over the next blocks (voice_kill: no click), one more each half while it lasts. A
* single late half (a USB burst, a flash write) sheds nothing. First the quietest releasing voice; else
* the oldest held one that is not a part's lowest POLY note nor its MONO / LEGATO / UNISON lead, as the
* voice budget keeps them: a dense chord on a heavy engine thins out from the top, bass and lead stay. */
static uint32_t shed_count;
static void shed_voice(void)
{
uint32_t p, i;
voice_t *best = 0;
for (p = 0; p < NPART; p++)
for (i = 0; i < NVOICE; i++) {
voice_t *v = &trk[p].v[i];
if (v->active && !v->gate && v->stage != 4u && (!best || v->env < best->env))
best = v;
}
if (best) {
voice_kill(best);
shed_count++;
return;
}
for (p = 0; p < NPART; p++) {
const track_t *t = &trk[p];
uint32_t mode = (uint32_t)t->p[P_VOICE], low = mode == V_POLY ? lowest_held(t) : 0u;
for (i = 0; i < NVOICE; i++) {
voice_t *v = &trk[p].v[i];
if (v->active && v->gate && v->stage != 4u &&
((mode == V_POLY && i != low) || (mode != V_POLY && i > 0u)) && (!best || v->age < best->age))
best = v;
}
}
if (best) {
voice_kill(best);
shed_count++;
}
}
/* the budget is full: free a voice for part t. 0 = nothing to take (soft) */
static int voice_room(track_t *t, int soft)
{
@@ -383,9 +421,10 @@ static void trk_note_off(track_t *t, uint32_t note)
t->xp_vel[k++] = t->xp_vel[i];
}
t->xp_n = (uint8_t)k;
mono_remove(t, note); /* in any mode: a key let go after a VOICE change must
* not stay in the MONO stack (after Felucca 1.0) */
if (mode != V_POLY) {
uint32_t nv = mode == V_UNISON ? trk_nvoice(t) : 1u;
mono_remove(t, note);
if (t->mono_note == note) {
uint32_t next = mono_pick(t);
if (next) { /* fall back to a held note, legato */
+83
View File
@@ -0,0 +1,83 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Host test of the knob decoder (firmware/hal/fm1_input.h fm1__frame): an FM-1 detent is one full
* quadrature cycle and the knob rests in one state. Clicks are played as the scan sees them, one
* sample per frame (~1.1 ms): slow and fast turns, pauses mid-click (short and long), contact
* bounce, back-and-forth, two-state jumps. Each click must give exactly one step. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
#include "../firmware/hal/fm1_input.h"
static const uint8_t CW[4] = {0, 1, 3, 2}; /* + (clockwise): 00 -> 01 -> 11 -> 10 -> 00 */
static uint32_t pos; /* quadrature phase, 0..3 along CW */
static int fails;
static int32_t take(uint32_t e) { int32_t s = fm1_in.enc_steps[e]; fm1_in.enc_steps[e] = 0; return s; }
static void put(uint32_t e, uint32_t st) /* encoder e reads state st (A << 1 | B) */
{
const uint8_t *m = FM1_ENC[e];
fm1_in.raw[m[0]] = (uint8_t)((fm1_in.raw[m[0]] & ~(1u << m[1])) | ((st >> 1) & 1u) << m[1]);
fm1_in.raw[m[2]] = (uint8_t)((fm1_in.raw[m[2]] & ~(1u << m[3])) | (st & 1u) << m[3]);
}
static void frames(uint32_t e, uint32_t n) { while (n--) { put(e, CW[pos & 3u]); fm1__frame(); } }
static void move(uint32_t e, int dir, uint32_t hold) /* one transition, then hold frames */
{
pos = (pos + (dir > 0 ? 1u : 3u)) & 3u;
frames(e, hold);
}
static void click(uint32_t e, int dir, uint32_t hold) { int i; for (i = 0; i < 4; i++) move(e, dir, hold); }
static void check(const char *what, int ok) { printf("encoder: %-58s %s\n", what, ok ? "ok" : "FAIL"); fails += !ok; }
static void reset(void)
{
uint32_t i;
memset((void *)&fm1_in, 0, sizeof fm1_in);
for (i = 0; i < FM1_NENC; i++)
fm1_in.enc_prev[i] = fm1_in.enc_last[i] = 0xFF;
pos = 0;
frames(0, 50); /* power-on: resting on a detent */
}
int main(void)
{
uint32_t e = 0, k;
int32_t s;
reset();
for (k = 0; k < 10u; k++) click(e, 1, 6), frames(e, 30);
check("10 slow clicks clockwise: +10", take(e) == 10);
for (k = 0; k < 10u; k++) click(e, -1, 6), frames(e, 30);
check("10 slow clicks anticlockwise: -10", take(e) == -10);
for (k = 0; k < 24u; k++) click(e, 1, 2);
frames(e, 30);
check("24 fast clicks (2 frames a transition): +24", take(e) == 24);
for (k = 0; k < 5u; k++) { /* a slow turn that stops mid-click (50 ms) */
move(e, 1, 6); move(e, 1, 45); move(e, 1, 6); move(e, 1, 30);
}
s = take(e);
check("5 clicks with 50 ms pauses mid-click: +5 (0.9: the knob went dead)", s == 5);
for (k = 0; k < 5u; k++) {
move(e, 1, 6); move(e, 1, 6); frames(e, 200); move(e, 1, 6); move(e, 1, 30);
}
s = take(e);
check("5 clicks held half-way 0.2 s: +5 (0.9: counted twice)", s == 5);
for (k = 0; k < 5u; k++) { /* contact bounce on each transition */
move(e, 1, 1); move(e, -1, 1); move(e, 1, 4);
move(e, 1, 4); move(e, 1, 1); move(e, -1, 1); move(e, 1, 4); move(e, 1, 30);
}
check("5 clicks with contact bounce: +5", take(e) == 5);
move(e, 1, 6); move(e, 1, 6); move(e, -1, 6); move(e, -1, 30);
check("half a click and back: nothing", take(e) == 0);
for (k = 0; k < 6u; k++) { /* a fast flick: two transitions in one sample */
pos = (pos + 2u) & 3u; frames(e, 1);
pos = (pos + 2u) & 3u; frames(e, 1);
}
frames(e, 30);
s = take(e);
check("6 flicks seen as two-state jumps: no wrong direction", s >= 0 && s <= 6);
click(e, 1, 6); frames(e, 30); take(e);
move(e, 1, 6); move(e, 1, 1000); /* parked ~1 s mid-click (held at power-on) */
for (k = 0; k < 4u; k++) click(e, 1, 6), frames(e, 30);
check("parked 1 s off the detent, then 4 clicks: 4 steps", take(e) == 4);
printf("%s\n", fails ? "ENCODER TEST FAILED" : "encoder test passed");
return fails;
}
+107 -2
View File
@@ -100,18 +100,121 @@ static int test_usb_sysex(void)
return bad;
}
/* the RX DMA: bytes land in the ring in order, from where it last stopped */
static uint32_t dma_w;
static void dma_put(const uint8_t *p, uint32_t n)
{
while (n--) {
um_ring[dma_w] = *p++;
dma_w = (dma_w + 1u) & (UM_RING - 1u);
}
}
static int ring_clean(void)
{
uint32_t i;
for (i = 0; i < UM_RING; i++)
if (um_ring[i] != UM_EMPTY)
return 0;
return 1;
}
/* the ring read by content (the Salt fix): no byte left behind, across the wrap, line noise skipped */
static int test_uart_ring(void)
{
/* an MPC Sample pad: note-on, running-status poly aftertouch, note-off, then silence */
static const uint8_t pad[] = {0x90, 0x3A, 0x11, 0xA0, 0x3A, 0x75, 0x3A, 0x7F, 0x3A, 0x06, 0x80, 0x3A, 0x00};
uint32_t i, k, w0, ok;
int bad = 0;
memset(&um, 0, sizeof um);
for (i = 0; i < UM_RING; i++)
um_ring[i] = UM_EMPTY;
mi_r = mi_w;
dma_w = 0;
um_drain();
bad += check("uart ring: nothing landed, nothing read", mi_w == mi_r && um.rd == 0 && um.bytes == 0);
dma_put(pad, sizeof pad);
um_drain();
bad += check("uart ring: a burst's last message (note-off) at once",
mi_w - mi_r == 5u && midi_in_q[(mi_w - 1u) % MQ] == 0x003A8008u && ring_clean());
mi_r = mi_w;
ok = 1; /* byte by byte, many times round the ring */
for (k = 0; k < 40u; k++) {
w0 = mi_w;
for (i = 0; i < sizeof pad; i++) {
dma_put(pad + i, 1);
um_drain();
if (i == 2u)
ok &= mi_w == w0 + 1u; /* the note-on with its third byte */
}
ok &= mi_w == w0 + 5u && midi_in_q[(mi_w - 1u) % MQ] == 0x003A8008u && um.rd == dma_w;
mi_r = mi_w;
}
bad += check("uart ring: byte-by-byte arrival across the wrap", ok && ring_clean());
dma_put((const uint8_t[]){0x90, 0x3C, 0x40, UM_EMPTY}, 4); /* line noise as the last byte */
um_drain();
ok = mi_w - mi_r == 1u && um.rd != dma_w; /* the stray byte waits for its successor */
dma_put((const uint8_t[]){0x80, 0x3C, 0x00}, 3);
um_drain();
ok &= mi_w - mi_r == 2u && midi_in_q[(mi_w - 1u) % MQ] == 0x003C8008u && um.rd == dma_w;
bad += check("uart ring: a received FD is skipped, not taken for empty", ok && ring_clean());
mi_r = mi_w;
return bad;
}
/* EP1 OUT (USB-MIDI from the computer): back-pressure instead of drops, malformed events ignored */
static int test_usb_ep1(void)
{
uint8_t pk[64];
uint32_t i, w0, n = 0;
int bad = 0;
for (i = 0; i < 16u; i++) { /* 16 note-ons, channel 1 */
pk[4 * i] = 0x09; pk[4 * i + 1] = 0x90; pk[4 * i + 2] = (uint8_t)(48 + i); pk[4 * i + 3] = 100;
}
mi_r = mi_w;
mi_w += MQ - 20u; /* the ring nearly full: 20 slots free (< 16 + 8) */
w0 = mi_w;
bad += check("usb ep1: ring too full -> packet held, nothing dropped", ep1_take(pk, 64) == 0 && mi_w == w0);
mi_r = mi_w; /* the sequencer drained it */
bad += check("usb ep1: room again -> all 16 events taken", ep1_take(pk, 64) == 1 && mi_w == w0 + 16u &&
midi_in_q[(mi_w - 1u) % MQ] == 0x643F9009u);
mi_r = mi_w;
w0 = mi_w;
{
static const uint8_t m[] = {
0x09, 0x80, 60, 100, /* status does not match CIN 9: ignored */
0x09, 0x90, 0xC0, 100, /* data byte with bit 7: ignored */
0x08, 0x80, 60, 0, /* a good note-off */
0x0F, 0xF8, 0, 0, /* clock */
0x0F, 0xFA, 0, 0, /* start */
0x0F, 0xFE, 0, 0, /* active sensing: not queued */
0x0C, 0xC0, 5, 0, /* program change (2 bytes) */
};
n = ep1_take(m, sizeof m);
bad += check("usb ep1: malformed ignored, clock / start / note-off / PC queued",
n == 1u && mi_w == w0 + 4u && midi_in_q[w0 % MQ] == 0x003C8008u &&
midi_in_q[(w0 + 1u) % MQ] == 0xF80Fu && midi_in_q[(w0 + 2u) % MQ] == 0xFA0Fu &&
midi_in_q[(w0 + 3u) % MQ] == 0x0005C00Cu);
}
mi_r = mi_w;
return bad;
}
int main(void)
{
static const uint8_t in[] = {
0x90, 60, 100, 62, 101, /* note on + running status */
0xF8, 64, 0xFE, 102, /* realtime inside a message */
0xF8, 64, 0xFE, 102, /* realtime inside a message (the clock is queued, cable 1) */
0xC1, 5, 6, /* program change + running */
0xF0, 0x22, 0x24, 0x35, 0x7D, 0xF7, 70, 71, /* SysEx dropped; cancels running status */
0xB0, 7, 0x7F, 0xF2, 1, 2, 9, 9, /* CC, song position (dropped), data without status */
0x80, 60, 0,
};
static const uint32_t want[] = {
0x643C9009u, 0x653E9009u, 0x66409009u, 0x0005C10Cu, 0x0006C10Cu, 0x7F07B00Bu, 0x003C8008u,
0x643C9009u, 0x653E9009u, 0x0000F81Fu, 0x66409009u, 0x0005C10Cu, 0x0006C10Cu, 0x7F07B00Bu, 0x003C8008u,
};
uint32_t i, bad = 0, n = sizeof want / sizeof want[0];
for (i = 0; i < sizeof in; i++)
@@ -138,6 +241,8 @@ int main(void)
}
bad += (uint32_t)check("uart: channels 1, 2, 3, 10, 16 -> USB-MIDI packets", ok);
}
bad += (uint32_t)test_uart_ring();
bad += (uint32_t)test_usb_ep1();
bad += (uint32_t)test_usb_sysex();
printf("%s\n", bad ? "MIDI PARSER TEST FAILED" : "midi parser test passed");
return (int)bad;
+9
View File
@@ -61,6 +61,15 @@ run "user presets (UP_PUT parser, bank round trip, versions)" "$OUT/upreset_test
$CC -o "$OUT/midi_uart_test" tests/midi_uart_test.c
run "TRS MIDI parser" "$OUT/midi_uart_test"
$CC -Ifirmware/hal -o "$OUT/encoder_test" tests/encoder_test.c
run "knobs: one click = one step (slow, fast, pauses, bounce)" "$OUT/encoder_test"
HALF=$(sed -n 's/^#define HALF_FRAMES \([0-9]*\).*/\1/p' firmware/src/core.h)
$CC -DT_CDC=1 -DHALF_FRAMES=$HALF -o "$OUT/uac_test" tests/uac_test.c
run "USB audio input: descriptors (with CDC), ring and packets" "$OUT/uac_test"
$CC -DT_CDC=0 -DHALF_FRAMES=$HALF -o "$OUT/uac_test_nocdc" tests/uac_test.c
run "USB audio input: descriptors (without CDC), ring and packets" "$OUT/uac_test_nocdc"
uac_in_app() { ${CC%% *} -E -Ibuild/gen -Ifirmware/hal -Ifirmware/src firmware/src/felucca.c 2>/dev/null | grep -q uac_service; }
run "USB audio input: built into the firmware (FELUCCA_UAC set before usb.c)" uac_in_app
$CC -o "$OUT/ota_test" tests/ota_test.c
run "M-UPGRADE entry" "$OUT/ota_test" build/felucca.fwsc
+184
View File
@@ -368,8 +368,192 @@ static void t_mute(void)
check(nhits > n0 && TDRUM->att == 0, "solo off: the drums back");
}
/* overload shedding (voice.c shed_voice): a releasing voice first, then the oldest held voice that is
* neither a POLY part's lowest note nor a MONO part's lead; faded (stage 4), never cut */
static void t_shed(void)
{
track_t *t = &trk[0], *m = &trk[1];
uint32_t i, k, low_ok = 1, lead_ok = 1;
reset(120);
t->p[P_VOICE] = V_POLY;
m->p[P_VOICE] = V_MONO;
t->p[P_ATK] = 0;
t->p[P_REL] = 100; /* a long release: the released voice still rings */
trk_note_on(t, 48, 100); /* the bass, first and lowest */
trk_note_on(t, 64, 100);
trk_note_on(t, 67, 100);
trk_note_on(t, 72, 100);
trk_note_on(m, 40, 100); /* a MONO lead */
trk_note_on(t, 76, 100);
for (k = 0; k < 20u; k++)
run_block();
trk_note_off(t, 76); /* releasing */
run_block();
shed_voice();
for (k = 0, i = 0; i < NVOICE; i++)
k += t->v[i].note == 76 && t->v[i].stage == 4u;
check(k == 1u, "overload: the releasing voice goes first, faded (stage 4)");
for (k = 0; k < 6u; k++)
shed_voice();
for (i = 0; i < NVOICE; i++) {
if (t->v[i].note == 48 && t->v[i].active && t->v[i].stage == 4u)
low_ok = 0;
if (m->v[i].note == 40 && i == 0u && m->v[i].stage == 4u)
lead_ok = 0;
}
for (k = 0, i = 0; i < NVOICE; i++)
k += t->v[i].active && t->v[i].gate && (t->v[i].note == 64 || t->v[i].note == 67 || t->v[i].note == 72);
check(low_ok && lead_ok && k == 0u, "overload: the upper notes thin out, the bass and the MONO lead stay");
}
/* MIDI clock in (SYNC USB / TRS): START, 24 pulses a beat, tempo changes, STOP; the other source ignored */
static void mclk_push(uint32_t pkt) { midi_in_q[mi_w % MQ] = pkt; mi_w++; }
static void mclk_run(double *t, double *next, double per, double until, uint32_t src)
{
while (*t < until) {
while (*next <= *t) {
mclk_push(0xF80Fu | src << 4);
*next += per;
}
fm1_ms = (uint32_t)*t;
run_block();
*t += (double)CTL * 1000.0 / FS;
}
}
static void t_mclk(void)
{
double t = 0, next = 0, per = 60000.0 / 120 / 24;
reset(90); /* the internal tempo: 90 */
mi_r = mi_w;
song.g[G_SYNC] = 1; /* USB */
mclk_run(&t, &next, per, 700, 0); /* the clock runs before START (the tempo shows) */
check(!song.playing && song.g[G_BPM] == 120, "MIDI clock: stopped, BPM follows the master (120)");
mclk_push(0xFA0Fu); /* START, then the downbeat pulse */
next = t;
mclk_run(&t, &next, per, t + 4000.0 + per / 2, 0); /* two bars of 120 */
check(song.playing && clk_beat == 8u, "MIDI clock: START, 2 bars at 120 -> beat 8 exactly");
per = 60000.0 / 100 / 24; /* the master slows to 100 */
mclk_run(&t, &next, per, t + 4800.0, 0);
check(clk_beat == 16u && song.g[G_BPM] == 100, "MIDI clock: the master at 100 -> 2 more bars, BPM 100");
mclk_push(0xFC1Fu); /* STOP from the TRS jack: not the source */
mclk_run(&t, &next, per, t + 50.0, 0);
check(song.playing, "MIDI clock: SYNC USB ignores the TRS jack");
mclk_push(0xFC0Fu);
mclk_run(&t, &next, per, t + 10.0, 0);
check(!song.playing, "MIDI clock: STOP");
t += 1000.0; /* the master is gone: PLAY on the FM-1 plays */
fm1_ms = (uint32_t)t;
transport_req = 1;
run_block();
{
uint32_t b0 = clk_beat, k;
for (k = 0; k < (uint32_t)(FS / CTL); k++)
run_block();
check(song.playing && clk_beat >= b0 + 1u, "MIDI clock: no pulse for 0.5 s -> the internal tempo plays");
}
transport_req = 2;
run_block();
song.g[G_SYNC] = 0;
mi_r = mi_w;
}
/* the REC screen's MODE and START (SLOOP 2.3): an empty project records at the tempo set (TEMPO) or
* takes it from the playing (FREE); COUNT: PLAY clicks one bar, then the loop and the recording start */
static void t_recmode(void)
{
uint32_t k, bpb = (uint32_t)((double)FS * 60.0 / 100.0 / CTL + 0.5), c0;
reset(100);
song.sel = 0;
song.playing = 0;
rec_tempo = 0, rec_count = 0;
rec_wait = 1;
input_on(TSEL, 60, 100);
run_block();
check(ft_on && !song.playing, "REC mode FREE, empty project: the first note starts a free take");
transport_req = 2; run_block(); ft_bars = 0;
for (k = 0; k < 4u; k++) trk_note_off(&trk[k % NPART], 60);
reset(100);
song.sel = 0;
rec_tempo = 1, rec_count = 0;
rec_wait = 1;
input_on(TSEL, 60, 100);
run_block();
check(!ft_on && song.playing && song.rec == 1u && song.g[G_BPM] == 100,
"REC mode TEMPO, empty project: the first note starts the loop at 100 BPM, recording");
transport_req = 2; run_block();
reset(100);
song.sel = 0;
rec_tempo = 1, rec_count = 1;
rec_wait = 1;
input_on(TSEL, 62, 100);
run_block();
check(!song.playing && !ci_on && !ft_on && rec_wait, "REC START COUNT: a note only sounds, nothing starts");
c0 = nhits;
transport_req = 1; /* PLAY: the count-in */
run_block();
for (k = 0; k + 2u < 4u * bpb; k++) run_block();
check(ci_on && !song.playing, "REC START COUNT: PLAY -> one bar of clicks, not playing yet");
{
uint32_t n = 0, i;
for (i = c0; i < nhits; i++) n += hits[i].note == 76 || hits[i].note == 77;
check(n == 4u, "REC START COUNT: 4 clicks (one bar of 4/4)");
}
for (k = 0; k < 4u; k++) run_block();
check(!ci_on && song.playing && song.rec == 1u && !rec_wait,
"REC START COUNT: after the bar the loop starts and records");
transport_req = 2; run_block();
reset(100);
song.sel = 0;
rec_tempo = 1, rec_count = 1;
rec_wait = 1;
transport_req = 1; run_block();
for (k = 0; k < bpb; k++) run_block();
rec_wait = 0; /* REC again: cancelled */
for (k = 0; k < 4u * bpb; k++) run_block();
check(!ci_on && !song.playing && !song.rec, "REC START COUNT: REC during the count-in cancels it");
rec_wait = 1;
transport_req = 1; run_block();
transport_req = 1; run_block(); /* PLAY again: back to armed */
check(!ci_on && rec_wait && !song.playing, "REC START COUNT: PLAY again during the count-in: back to armed");
rec_wait = 0;
rec_tempo = 0, rec_count = 0;
}
/* menu USB AUDIO = FULL (2.3): the USB input at the level of MASTER all the way up, whatever the knob;
* the DAC path keeps following the knob */
static void t_usbfull(void)
{
uint32_t k, i;
int32_t out[CTL * 2], pk_dac = 0, pk_usb = 0;
reset(120);
song.master_q12 = 512; /* MASTER low */
master_cur = -1;
usb_full_now = 1;
for (k = 0; k < 8u; k++) trk_note_on(&trk[0], 48u + k * 3u, 110);
for (k = 0; k < 600u; k++) {
mix_block(out, CTL);
if (k > 100u)
for (i = 0; i < 2u * CTL; i++) {
int32_t a = out[i] < 0 ? -out[i] : out[i], u = usb_out[i] < 0 ? -usb_out[i] : usb_out[i];
if (a > pk_dac) pk_dac = a;
if (u > pk_usb) pk_usb = u;
}
}
usb_full_now = 0;
for (k = 0; k < 8u; k++) trk_note_off(&trk[0], 48u + k * 3u);
song.master_q12 = 2048;
check(pk_usb > pk_dac * 3 && pk_usb <= 32767, "USB AUDIO FULL: the USB level stays up when MASTER is low, no clipping");
}
int main(void)
{
t_usbfull();
t_recmode();
t_mclk();
t_shed();
t_drift();
t_burst();
t_swing_odd();
+324
View File
@@ -0,0 +1,324 @@
/* SPDX-License-Identifier: GPL-3.0-only
* Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments */
/* Host test of the USB audio input in src/usb.c (FELUCCA_UAC):
* descriptors the configuration parsed as a host does: lengths, interface and endpoint counts,
* class codes, the UAC1 chain (AC header collection, terminals, AS general, type I
* format, the isochronous endpoint), the IADs; with and without CDC (-DT_CDC=0/1)
* ring uac_render_start / uac_tap (the audio ISR) against uac_packet (TIMER5): renders of 256
* frames at the I2S rate, as late as the load makes them, packets at 1 kHz: sizes 43..46,
* 44.1 on average, every frame delivered in order, then an underrun (repeats), an
* overrun (drops, the ring never overfills) and a restart.
* The SIE is never touched (uac_service and usb_poll are not called). */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#ifndef HALF_FRAMES
#error "-DHALF_FRAMES=n (src/core.h; run_tests.sh passes it)"
#endif
#define RING_PUBLISH() __asm__ volatile("" ::: "memory")
#define FELUCCA_OTA 0
#define FELUCCA_CDC T_CDC
#define FELUCCA_UAC 1
static void fm1_delay_ms(uint32_t ms) { (void)ms; }
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" /* SIE register macros (never touched here) */
#include "../firmware/src/usb.c"
static int fails;
static int check(const char *what, int ok)
{
printf("%-64s %s\n", what, ok ? "ok" : "FAIL");
if (!ok)
fails++;
return ok;
}
static uint32_t le16(const uint8_t *p) { return p[0] | (uint32_t)p[1] << 8; }
/* ------------------------------------------------------------------ descriptors --- */
static void test_descriptors(void)
{
const uint8_t *c = CFG_DESC;
uint32_t total = le16(c + 2), n = sizeof CFG_DESC, off, nif = 0, i;
int lens_ok = 1, eps_ok = 1, ac_ok = 0, it_ok = 0, ot_ok = 0, asg_ok = 0, fmt_ok = 0, iso_ok = 0, csep_ok = 0;
int alt0_ok = 0, iad_ok = 1, midi_ok = 0, dup_ok = 1, coll_ok = 0;
uint8_t seen_if[16] = {0}, if_class[16] = {0}, if_sub[16] = {0};
int cur_if = -1, cur_alt = -1, cur_neps = 0, got_eps = 0, ac_len_left = -1, ac_total = 0, ac_wt = -1;
uint8_t coll[8], ncoll = 0, iad_n = 0;
uint32_t ep_seen[32] = {0};
char name[96];
check("device descriptor: 18 bytes, type 1, EP0 64", DEV_DESC[0] == 18 && DEV_DESC[1] == 1 && DEV_DESC[7] == 64);
check("bcdDevice bumped for the audio input (x.1x)", (DEV_DESC[12] & 0xF0u) == 0x10u && DEV_DESC[13] == 3);
check(T_CDC ? "device class misc / IAD (EF 02 01)" : "device class 0 (per interface)",
T_CDC ? DEV_DESC[4] == 0xEF && DEV_DESC[5] == 2 && DEV_DESC[6] == 1 : DEV_DESC[4] == 0);
check("configuration: type 2, wTotalLength = the bytes sent", c[1] == 2 && total == n);
for (off = 0; off < n;) {
const uint8_t *d = c + off;
if (d[0] < 2 || off + d[0] > n) {
lens_ok = 0;
break;
}
if (ac_len_left > 0 && d[1] == 0x24) {
ac_total += d[0];
ac_len_left -= d[0];
} else if (ac_len_left > 0) {
ac_len_left = -2; /* the CS AC block ended early */
}
switch (d[1]) {
case 0x0B: /* IAD */
iad_n++;
if (d[0] != 8 || d[2] + d[3] > 16)
iad_ok = 0;
if (iad_n == 1 && !(d[2] == 0 && d[3] == 3 && d[4] == 1))
iad_ok = 0; /* audio: IF 0..2 */
if (iad_n == 2 && !(d[2] == 3 && d[3] == 2 && d[4] == 2))
iad_ok = 0; /* CDC: IF 3..4 */
break;
case 4:
if (cur_if >= 0 && got_eps != cur_neps)
eps_ok = 0;
cur_if = d[2];
cur_alt = d[3];
cur_neps = d[4];
got_eps = 0;
if (cur_if < 16) {
if (!seen_if[cur_if])
nif++;
seen_if[cur_if] = 1;
if_class[cur_if] = d[5];
if_sub[cur_if] = d[6];
}
if (d[5] == 1 && d[6] == 2 && cur_alt == 0 && d[4] == 0)
alt0_ok = 1;
break;
case 5:
got_eps++;
if (d[2] == 0x84) {
iso_ok = d[0] == 9 && d[3] == 0x05 && le16(d + 4) == UA_MAXF * 4u && le16(d + 4) <= 1023u &&
d[6] == 1 && cur_alt == 1 && if_sub[cur_if] == 2;
}
if ((d[2] == 0x01 || d[2] == 0x81) && d[3] == 2 && if_sub[cur_if] == 3)
midi_ok++;
if (ep_seen[(d[2] & 15u) + (d[2] >> 7) * 16u]++)
dup_ok = 0; /* each address once (no alt shares one here) */
break;
case 0x24:
if (if_class[cur_if] == 1 && if_sub[cur_if] == 1) { /* audio control */
if (d[2] == 1) {
ac_ok = d[0] == 8u + d[7] && le16(d + 3) == 0x0100u;
ac_len_left = ac_wt = (int)le16(d + 5);
ac_total = 0;
ac_len_left -= d[0];
ac_total += d[0];
ncoll = d[7];
for (i = 0; i < ncoll && i < sizeof coll; i++)
coll[i] = d[8 + i];
} else if (d[2] == 2) {
it_ok = d[0] == 12 && d[3] == 1 && d[7] == 2 && le16(d + 8) == 3u && le16(d + 4) != 0x0101u;
} else if (d[2] == 3) {
ot_ok = d[0] == 9 && d[3] == 2 && le16(d + 4) == 0x0101u && d[7] == 1;
}
} else if (if_class[cur_if] == 1 && if_sub[cur_if] == 2) { /* audio streaming */
if (d[2] == 1)
asg_ok = d[0] == 7 && d[3] == 2 && le16(d + 5) == 1u;
else if (d[2] == 2)
fmt_ok = d[0] == 11 && d[3] == 1 && d[4] == 2 && d[5] == 2 && d[6] == 16 && d[7] == 1 &&
(d[8] | d[9] << 8 | d[10] << 16) == 44100;
}
break;
case 0x25:
if (d[2] == 1 && if_sub[cur_if] == 2)
csep_ok = d[0] == 7 && (d[3] & 1u);
break;
}
off += d[0];
}
if (cur_if >= 0 && got_eps != cur_neps)
eps_ok = 0;
coll_ok = ncoll == 2;
for (i = 0; i < ncoll && i < sizeof coll; i++)
if (coll[i] >= 16 || if_class[coll[i]] != 1 || (if_sub[coll[i]] != 2 && if_sub[coll[i]] != 3))
coll_ok = 0;
check("descriptor lengths add up to wTotalLength", lens_ok && off == n);
check("bNumInterfaces = the interfaces present", c[4] == nif && nif == (T_CDC ? 5u : 3u));
check("each interface setting has bNumEndpoints endpoints", eps_ok);
check("endpoint addresses unique", dup_ok);
check("AC header: UAC 1.00, length 8 + collection", ac_ok);
check("AC header wTotalLength = the class-specific AC descriptors", ac_len_left == 0 && ac_total == ac_wt);
check("AC collection: the MIDI and audio streaming interfaces", coll_ok);
check("input terminal 1: 2 ch, L R, not USB streaming", it_ok);
check("output terminal 2: USB streaming, source 1", ot_ok);
check("AS alt 0 has no endpoint", alt0_ok);
check("AS general: terminal 2, PCM", asg_ok);
check("type I format: 2 ch, 2-byte subframe, 16 bit, 44100 Hz only", fmt_ok);
check("EP 0x84: isochronous async, 184 B (46 frames), every frame, alt 1", iso_ok);
check("CS endpoint: sampling frequency control", csep_ok);
check("MIDI bulk endpoints 0x01 / 0x81 unchanged", midi_ok == 2);
snprintf(name, sizeof name, "IADs: %s", T_CDC ? "audio IF 0-2, CDC IF 3-4" : "none");
check(name, iad_ok && iad_n == (T_CDC ? 2 : 0));
}
/* --------------------------------------------------------------------- the ring --- */
/* time in ns. The producer renders HALF_FRAMES frames at FS_DEV, a render taking `rend` ns in
* HALF_FRAMES / 32 blocks of 32 (the samples count up: L = n, R = ~n, so the order can be checked); the consumer
* takes one packet per ms. */
#define FS_DEV 44117.6
static uint32_t prod_n, cons_n, cons_bad, cons_rep, cons_zero, sizes[64], npk;
static uint32_t last_frame;
static int32_t blk[64];
static void render_block(void)
{
uint32_t i;
for (i = 0; i < 32u; i++, prod_n++) {
blk[2 * i] = (int16_t)prod_n;
blk[2 * i + 1] = (int16_t)~prod_n;
}
uac_tap(blk, 32);
}
static void take_packet(void)
{
uint32_t d[UA_MAXF + 2], n = uac_packet(d), i;
sizes[n]++;
npk++;
for (i = 0; i < n; i++) {
uint16_t l = (uint16_t)d[i], r = (uint16_t)(d[i] >> 16);
if (d[i] == 0 && !uac.go) {
cons_zero++;
continue;
}
if ((uint16_t)~l != r) {
if (d[i] == 0) { /* primed silence ahead of the first render */
cons_zero++;
continue;
}
cons_bad++;
continue;
}
if (cons_n && l == (uint16_t)last_frame)
cons_rep++; /* a repeated frame (underrun) */
else if (cons_n && l != (uint16_t)(last_frame + 1u))
cons_bad++;
last_frame = l;
cons_n++;
}
}
/* run for `ms`; renders take `rend_ns` (or vary with the load when 0); consumer / producer can be paused */
static uint64_t now_ns, next_half, next_pkt;
static uint32_t blocks_left;
static uint64_t next_block, rend_len;
static uint32_t lcg = 12345;
/* render times: 7 % .. 85 % of a half (the overload shedding starts above 85 %) */
#define REND_MIN ((uint64_t)(HALF_FRAMES * 1e9 / FS_DEV * 0.07))
#define REND_MAX ((uint64_t)(HALF_FRAMES * 1e9 / FS_DEV * 0.85))
static void run(uint32_t ms, uint64_t rend_ns, int produce, int consume)
{
uint64_t end = now_ns + (uint64_t)ms * 1000000u;
while (now_ns < end) {
uint64_t t = end;
if (next_half < t)
t = next_half;
if (blocks_left && next_block < t)
t = next_block;
if (next_pkt < t)
t = next_pkt;
now_ns = t;
if (now_ns >= end)
break;
if (now_ns == next_half) {
next_half += (uint64_t)((double)HALF_FRAMES / FS_DEV * 1e9);
if (produce) {
lcg = lcg * 1103515245u + 12345u;
rend_len = rend_ns ? rend_ns : REND_MIN + (lcg >> 8) % (REND_MAX - REND_MIN);
uac_render_start();
blocks_left = HALF_FRAMES / 32u;
next_block = now_ns + rend_len / blocks_left;
}
} else if (blocks_left && now_ns == next_block) {
render_block();
blocks_left--;
next_block += rend_len / (HALF_FRAMES / 32u);
} else if (now_ns == next_pkt) {
lcg = lcg * 1103515245u + 12345u;
next_pkt = (now_ns / 1000000u + 1u) * 1000000u + (lcg >> 8) % 500000u; /* in the next frame */
if (consume)
take_packet();
}
}
}
static void test_ring(void)
{
uint32_t i, sum, base_n, base_p;
char s[120];
usb.config = 1;
memset(&uac, 0, sizeof uac);
uac_stream(1);
next_half = 300000;
next_pkt = 1000000;
run(3, 0, 1, 1); /* alt 1 set: no IN token yet */
check("not fed before the host reads (no overruns while it waits)", uac.overruns == 0 && ua_w == 0);
uac.flowing = 1; /* (uac_service: the first packet went) */
run(2000, 0, 1, 1);
memset(sizes, 0, sizeof sizes);
npk = 0;
base_n = cons_n;
base_p = uac.underruns + uac.overruns;
run(10000, 0, 1, 1);
for (i = sum = 0; i < 64u; i++)
sum += sizes[i] * i;
snprintf(s, sizeof s, "10 s, random render times: sizes 43..46 (44:%u 45:%u 46:%u 43:%u)", sizes[44], sizes[45],
sizes[46], sizes[43]);
check(s, sizes[44] + sizes[45] + sizes[46] + sizes[43] == npk);
snprintf(s, sizeof s, " mean packet %.4f frames (I2S %.1f Hz)", (double)sum / npk, FS_DEV);
check(s, (double)sum / npk > 44.05 && (double)sum / npk < 44.2);
check(" every frame once, in order; no underrun / overrun", cons_bad == 0 && cons_rep == 0 &&
uac.underruns + uac.overruns == base_p && cons_n - base_n == sum);
snprintf(s, sizeof s, " fill at render start stays %u..%u (band %u..%u)", uac.fill_lo, uac.fill_hi, UA_LO, UA_HI);
check(s, uac.fill_lo >= 46u && uac.fill_hi + HALF_FRAMES <= UA_N);
memset(sizes, 0, sizeof sizes);
npk = 0;
for (i = 0; i < 1000u; i++) { /* 1000 frames worst case: renders of 85 % */
run(1, REND_MAX, 1, 1);
}
for (i = sum = 0; i < 64u; i++)
sum += sizes[i] * i;
snprintf(s, sizeof s, "1000 packets, %.1f ms renders: mean %.3f, no glitch", REND_MAX / 1e6, (double)sum / npk);
check(s, (double)sum / npk > 44.0 && (double)sum / npk < 44.25 && cons_bad == 0 && cons_rep == 0 &&
uac.underruns + uac.overruns == base_p);
base_p = uac.underruns;
run(30, 0, 0, 1); /* the render stops (a crash would; a stuck ISR) */
check("producer stopped 30 ms: underruns counted, packets keep their size", uac.underruns > base_p &&
cons_bad == 0);
check(" the empty ring repeats the last frame", cons_rep > 0);
base_p = uac.overruns;
run(40, 0, 1, 0); /* the consumer stops (flowing still 1) */
check("consumer stopped 40 ms: overruns counted, the ring never overfills", uac.overruns > base_p &&
ua_w - ua_r <= UA_N);
uac_stream(0);
run(10, 0, 1, 1);
check("alt 0: nothing fed, nothing taken", ua_w - ua_r <= UA_N && !uac.feed);
uac_stream(1);
uac.flowing = 1;
cons_n = 0;
cons_bad = cons_rep = 0;
base_p = uac.underruns + uac.overruns;
run(3000, 0, 1, 1);
check("restart: primed again, in order, no glitch", cons_n > 3000u * 44u && cons_bad == 0 && cons_rep == 0 &&
uac.underruns + uac.overruns == base_p);
}
int main(void)
{
printf("-- USB audio input, CDC %s\n", T_CDC ? "on" : "off");
test_descriptors();
test_ring();
printf(fails ? "UAC TEST FAILED (%d)\n" : "uac: all ok\n", fails);
return fails != 0;
}
+128 -1
View File
@@ -31,7 +31,8 @@ static int32_t encs[7];
static uint32_t fm1_ticks(void) { return fm1_ms * 1000u * 24u; }
#define FM1_TICKS_PER_US 24u
static int32_t fm1_enc_take(uint32_t e) { int32_t s = encs[e]; encs[e] = 0; return s; }
static uint8_t fm1_led[16], fm1_led_dim[16];
static uint8_t fm1_led[16], fm1_led_dim[16], fm1_led_bg[16];
static volatile uint16_t fm1_led_bg_ns;
#define FM1_NCOL 16u
static const int8_t FM1_KEYMAP[5][16];
static void fm1_led_key(uint32_t id, int on) { (void)id; (void)on; }
@@ -328,7 +329,38 @@ int main(int argc, char **argv)
static track_t keep[NTRK];
memcpy(keep, trk, sizeof keep);
for (i = 0; i < NTRK; i++) steps_clear(&trk[i]);
rec_tempo = 0; rec_count = 0;
rec_wait = 1; ui.force = 1; frame(); ppm("live-rec-free");
/* the REC screen's dials (2.3): KNOB 1 MODE, KNOB 2 LENGTH, KNOB 3 START */
encs[panel.enc[EN_K1]] = 1; frame();
check(rec_tempo == 1u && rec_wait, "REC screen, empty project: KNOB 1 -> MODE tempo");
ui.force = 1; frame(); ppm("live-rec-tempo");
trk[song.sel].p[P_SLEN] = 16;
encs[panel.enc[EN_K2]] = 1; frame();
encs[panel.enc[EN_K2]] = 1; frame();
check(trk[song.sel].p[P_SLEN] == 64, "REC screen: KNOB 2 -> LENGTH 1, 2, 4 bars");
encs[panel.enc[EN_K2]] = -1; frame();
check(trk[song.sel].p[P_SLEN] == 32, "REC screen: KNOB 2 back -> 2 bars");
encs[panel.enc[EN_K3]] = 1; frame();
check(rec_count == 1u, "REC screen: KNOB 3 -> START count");
ui.force = 1; frame(); ppm("live-rec-count");
check((lights_word() >> 9 & 3u) == 3u, "REC screen: MODE and START saved with the settings");
ci_on = 1; ci_beat = 1; ui.force = 1; frame(); ppm("live-rec-countin");
encs[panel.enc[EN_K1]] = -1; frame();
check(rec_tempo == 1u, "REC screen: the count-in running, the dials wait");
ci_on = 0; ci_beat = 0;
trk[1].step[0].time = ST_NOTE; trk[1].step[0].n = 1; trk[1].step[0].note[0] = 60;
encs[panel.enc[EN_K1]] = -1; frame();
check(rec_tempo == 1u, "REC screen, a project with notes: no MODE (always the tempo set)");
ui.force = 1; frame(); ppm("live-rec-notes");
steps_clear(&trk[1]);
encs[panel.enc[EN_K3]] = -1; frame();
encs[panel.enc[EN_K1]] = -1; frame();
check(rec_tempo == 0u && rec_count == 0u, "REC screen: KNOB 3 / 1 back -> note, free");
rec_count = 1; encs[panel.enc[EN_K3]] = -1; frame();
check(rec_count == 1u, "REC screen, MODE free: no START (the take starts on the first note)");
rec_count = 0;
trk[song.sel].p[P_SLEN] = 16;
rec_wait = 0; ft_on = 1; ft_t = (uint32_t)(5.4 * FS / CTL); ui.force = 1; ui_draw(); ppm("live-free-take");
ft_on = 0; ft_t = 0; memcpy(trk, keep, sizeof keep);
rec_wait = 0; frame();
@@ -336,6 +368,101 @@ int main(int argc, char **argv)
for (i = 0; i < DRUM_KITS; i++) { TDRUM->p[P_E0] = (int16_t)i; ui.force = 1; drum_page = 1; frame(); }
drum_page = 0;
{ /* menu NOTES (PR #11 by @renebohne): sounding synth voices light their keys */
song.sel = 0; go_home(); ui.force = 1; frame();
trk[0].p[P_CHORD] = 0; trk[0].p[P_QUANT] = 0; trk[0].p[P_ROOT] = 0; trk[0].p[P_TRANS] = 0;
song.octave = 0;
lights_notes = 0;
trk[0].v[0].active = 1; trk[0].v[0].gate = 1; trk[0].v[0].stage = 1; trk[0].v[0].note = 60;
frame();
check((keys_lit() & (1u << 7)) == 0, "NOTES off: a sounding synth voice lights no key");
ui.menu = 1; ui.menu_sel = MI_NOTES; ui.force = 1; frame();
encs[panel.enc[EN_K1]] = 1; frame();
check(lights_notes == 1u, "menu NOTES: KNOB 1 right: ON");
ui.force = 1; frame(); ppm("page-menu-notes");
ui.menu = 0; ui.force = 1; go_home(); frame();
check((keys_lit() & (1u << 7)) != 0, "NOTES on: a sounding synth voice lights key 7 (C4)");
{ /* every screen and layer: lit where the keys are notes, a glow under the tiles */
static const struct { uint32_t ly; int lit; const char *name; } L[] = {
{LY_ERASE, 1, "EDIT erase"}, {LY_ROLL, 1, "ARP roll"}, {LY_SCALE, 1, "SCL key"}, {LY_SONG, 1, "SAVE song"},
{LY_FX, 0, "FX punch"}, {LY_STEP, 0, "SEQ steps"}, {LY_MIX, 0, "GLO mix"}};
uint32_t k, ok = 1, ly0 = ui.layer;
char what[96];
for (k = 0; k < sizeof L / sizeof L[0]; k++) {
ui.layer = (uint8_t)L[k].ly;
if (L[k].lit)
ok = (keys_lit() >> 7 & 1u) != 0;
else
ok = (keys_notes_dim() >> 7 & 1u) != 0 && (keys_lit() >> 7 & 1u) == 0;
snprintf(what, sizeof what, "NOTES on, %s layer: the sounding C4 %s", L[k].name, L[k].lit ? "lit" : "glows under the tiles");
check(ok, what);
}
ui.layer = LY_SCALE;
check((keys_notes_dim() & scale_keys(0)) == scale_keys(0), "NOTES on, SCL: the scale glows");
lights_notes = 0;
ui.layer = LY_ERASE;
check((keys_lit() >> 7 & 1u) == 0 && keys_notes_dim() == 0u, "NOTES off, EDIT erase: as before (no note lights)");
ui.layer = LY_SCALE;
check(keys_notes_dim() == 0u, "NOTES off, SCL: as before");
lights_notes = 1;
ui.layer = (uint8_t)ly0;
}
song.octave = -1;
frame();
check((keys_lit() & (1u << 19)) != 0 && (keys_lit() & (1u << 7)) == 0, "NOTES on: the octave moves the lit key");
song.octave = 0;
trk[0].v[0].gate = 0; trk[0].v[0].stage = 3;
frame();
check((keys_lit() & (1u << 7)) == 0, "NOTES on: the release turns the key off");
trk[0].v[0].active = 0;
check((lights_word() >> 8 & 1u) == 1u, "NOTES: saved with the light settings");
ui.menu = 1; ui.menu_sel = MI_USB; ui.force = 1; frame(); ppm("menu-usb");
usb_full = 0;
encs[panel.enc[EN_K1]] = 1; frame();
check(usb_full == 1u && (lights_word() >> 11 & 1u) == 1u, "menu USB AUDIO: KNOB 1 -> FULL, saved with the settings");
tap(B_OCTUP);
check(usb_full == 0u && ui.menu == 1, "menu USB AUDIO: OCT+ toggles back to MASTER");
ui.menu = 0; ui.force = 1; go_home(); frame();
ui.menu = 1; ui.menu_sel = MI_NOTES; ui.force = 1; frame();
tap(B_OCTUP);
check(lights_notes == 0u && ui.menu == 1, "menu NOTES: OCT+ toggles it off");
ui.menu = 0; ui.force = 1; go_home(); frame();
}
{ /* menu LIGHTS / KEYS: the backlight for playing in the dark */
uint32_t m, nbits;
go_home(); ui.force = 1; frame();
check(lights_lvl == LIGHTS_OFF && fm1_led_bg_ns == 0u && lights_keys_mask() == 0u, "LIGHTS: off by default");
ui.menu = 1; ui.menu_sel = MI_LIGHTS; ui.force = 1; frame();
encs[panel.enc[EN_K1]] = 1; frame();
check(lights_lvl == LIGHTS_LOW && fm1_led_bg_ns == 500u, "LIGHTS: KNOB 1 right: LOW (a 0.5 us pulse a frame)");
encs[panel.enc[EN_K1]] = 1; frame();
check(lights_lvl == LIGHTS_MID && fm1_led_bg_ns == 1000u, "LIGHTS: MID (1 us)");
encs[panel.enc[EN_K1]] = 1; frame(); encs[panel.enc[EN_K1]] = 1; frame();
check(lights_lvl == LIGHTS_HIGH && fm1_led_bg_ns == 2000u, "LIGHTS: HIGH (2 us, under the 4 us glow), and it stops there");
ui.force = 1; frame(); ppm("page-menu-lights");
encs[panel.enc[EN_K1]] = -1; frame();
check(lights_lvl == LIGHTS_MID, "LIGHTS: KNOB 1 left: dimmer");
tap(B_OCTUP);
check(lights_lvl == LIGHTS_HIGH && ui.menu == 1, "LIGHTS: OCT+ steps round, the menu stays");
tap(B_OCTUP);
check(lights_lvl == LIGHTS_OFF && fm1_led_bg_ns == 0u, "LIGHTS: ... back to OFF");
ui.menu_sel = MI_KEYS; ui.force = 1; frame();
encs[panel.enc[EN_K1]] = 1; frame();
m = lights_keys_mask();
check(lights_keys == KEYS_C && lights_lvl == LIGHTS_LOW && m == (1u << 7 | 1u << 19),
"KEYS: C KEYS (C4, C5), LIGHTS raised to LOW");
encs[panel.enc[EN_K1]] = 1; frame(); encs[panel.enc[EN_K1]] = 1; frame();
for (m = lights_keys_mask(), nbits = 0; m; m &= m - 1u)
nbits++;
check(lights_keys == KEYS_WHITE && nbits == 16u && !(lights_keys_mask() & (1u << 1)),
"KEYS: WHITE KEYS (16 of 27, F#3 dark), and it stops there");
lights_lvl = LIGHTS_OFF; frame();
check(lights_keys_mask() == 0u && fm1_led_bg_ns == 0u, "KEYS: nothing lit while LIGHTS is OFF");
lights_keys = KEYS_OFF;
ui.menu = 0; ui.force = 1; go_home(); frame();
}
{ /* fuzz: 20000 frames of random buttons (held or tapped), knobs and keys, with the audio running
* between frames; every draw stays on the screen (lcd_blit / lcd_fill assert it) */
uint32_t f, seed = 777, held = 0;
+26 -1
View File
@@ -241,6 +241,29 @@ editor takes them from `INFO`; older records load with the SLICER off and CHORD
`KIT` (34 kits: ORIGINAL..DUST, the GM sample kit and its treatments, then the synthesised kits from
808). `DESC` of `P_E1..P_E7` there still describes engine 0 (unused).
## v6: backup / restore (SLOOP 2.3)
`INFO` ends with 6. Objects: **0** the working project (a `project_t`, as the autosave), **1** the settings
(`persist_t`: colours, low cut, zoom, the panel calibration, the song order, the lights and SYNC word),
**2..5** the projects 1..4 (song sections A..D; length 0 = empty), **6..7** the user preset banks (`up_bank_t`,
16 records each; 0 = empty), **32..34** the user sample slots USR1..3 (header + ADPCM data, as in flash; 0 =
empty). Numbers are 5 × 7 bit (u35, LSB first); data is pack7.
| cmd | Request args | Reply args |
| --- | --- | --- |
| 34 BK_LIST | — | rc (0 ok, 4 no flash), count, then per object: id, length u35, CRC-32 u35 (zlib). Takes a snapshot of the working project and the settings for GET |
| 35 BK_GET | id, offset u35, count (2 × 7 bit, 1..256) | id, rc (0 ok, 1 arguments, 5 the snapshot is gone: LIST again), offset u35, count, pack7 data |
| 36 BK_PUT | op 0 begin: id 0..7, length u35, CRC-32 u35 · op 1 data: id, offset u35, pack7 (≤ 256 bytes, in order) · op 2 commit: id · op 3 abort: id | op, id, rc: 0 ok, 1 arguments, 2 not a valid object (CRC, magic, sizes, ranges), 3 stop the song first (projects), 4 flash, 5 no begin for this object (or more than 15 s ago) |
A restore stages one object in RAM (the project load buffer), checks it at the commit as a load checks it
(projects: magic, size and sum, older formats converted; banks: magic, record size, slot count; settings:
magic, palette, a permutation of the buttons and knobs, a valid song order) and writes it through the usual
A/B commit; the working project is loaded at once (the song must be stopped). Samples are restored with
`SMP_BEGIN` / `SMP_WRITE` / `SMP_END` (the header is the first 480 bytes of the object, the data from byte
512), an empty slot with `SMP_ERASE`. The editor's file is JSON: `{format: "sloop-backup", version: 1,
firmware, date, objects: [{id, len, crc, data (base64)}]}`; it is checked (lengths, CRCs) before anything is
written.
## Notes for the editor
- **One request at a time.** Wait for the reply, about 10–50 ms, before sending the next.
@@ -250,6 +273,8 @@ editor takes them from `INFO`; older records load with the SLICER off and CHORD
- **Port.** The device's MIDI port is named "Felucca" (USB 1209:0001; SLOOP keeps the name so editors
and installers find it). Updates use the same
port with other SysEx (the `F0 22 24 35 …` keys, `00 59 …` frames); never send those
from the editor.
from the editor. Since SLOOP 2.3 (after Felucca 1.0) the same USB device also has an audio input
("Felucca", 44.1 kHz stereo; bcdDevice 3.11): the MIDI port and this protocol are unchanged, and both
work while the computer records.
- **Safety.** Only `PROJECT` save, the sample-slot commands and `UP_PUT` / `UP_STORE` / `UP_ERASE` write flash, and only in
Felucca's own storage; never the app or the update area.
+422 -50
View File
@@ -81,7 +81,12 @@
.chop .chops { display: flex; flex-wrap: wrap; gap: 3px; margin: 4px 0; }
.chop .chip { background: none; color: var(--fg); border: 1px solid var(--line); padding: 1px 6px; }
.chop .chip.on { background: var(--fg); color: var(--bg); }
.chop .chip { display: inline-flex; align-items: center; gap: 3px; cursor: pointer; user-select: none; }
.chop .chip input { margin: 0; accent-color: var(--fg); }
.chop .chip.off { color: var(--dim); text-decoration: line-through; }
.chop .chip.on input { accent-color: var(--bg); }
.chop input.len { width: 160px; }
.chop .selrow[hidden] { display: none; }
footer { margin-top: 24px; font-size: 11px; color: var(--dim); }
.row.pushed .v { font-weight: 600; }
/* librarian: local library and the device's user bank side by side, stacked on a phone */
@@ -298,6 +303,13 @@
<h2 data-t="projects" data-ic="symbol_folder"></h2>
<p class="dim" data-t="projHelp"></p>
<div class="slots" id="slots"></div>
<div class="group" id="bkgroup" style="margin-top:16px" hidden>
<h2 data-t="bkTitle" data-ic="port_disk"></h2>
<p class="dim" data-t="bkHelp"></p>
<p><button id="bk-save" data-t="bkSave"></button> <button id="bk-load" data-t="bkLoad"></button>
<input id="bk-file" type="file" accept=".json,application/json" hidden></p>
<progress id="bk-prog" max="1" value="0" hidden></progress>
</div>
</section>
<section class="panel" id="p-settings" data-tab="settings" data-dev hidden>
@@ -323,7 +335,8 @@ const CMD = { INFO: 1, GET: 2, SET: 3, DUMP: 4, DESC: 5, STEP_GET: 6, STEP_SET:
WATCH: 22, CHANGED: 23, RELOAD: 24, PING: 25, STEP_CHANGED: 26,
TRACK: 27, TRACK_MIX: 28, TRACK_DUMP: 29, TRACK_STEP: 30,
TRACK_PARAM: 31, TRACK_CHANGED: 32,
DRUM_STEP: 33 };
DRUM_STEP: 33,
BK_LIST: 34, BK_GET: 35, BK_PUT: 36 }; /* v6: backup / restore */
/* frames the device sends on its own (while WATCH is on); never replies */
const PUSH = new Set([CMD.CHANGED, CMD.RELOAD, CMD.STEP_CHANGED, CMD.TRACK_CHANGED]);
/* user preset bank: name 1..12 printable ASCII, a 16-step pattern of (note, flags 1 acc 2 slide 4 tie) */
@@ -466,6 +479,17 @@ const parse = {
const r = new Reader(a);
return stepExt(r, a, { track: r.b(), index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() });
},
/* v6: backup. LIST: rc, then per object id, length, CRC-32 (5 x 7 bit each) */
[CMD.BK_LIST](a) {
const r = new Reader(a), rc = r.b(), n = r.b(), items = [];
for (let i = 0; i < n; i++) items.push({ id: r.b(), len: u35dec(r), crc: u35dec(r) >>> 0 });
return { rc, items };
},
[CMD.BK_GET](a) {
const r = new Reader(a), id = r.b(), rc = r.b(), off = u35dec(r), count = r.b() | (r.b() << 7);
return { id, rc, off, count, data: unpack7(a.slice(r.i)) };
},
[CMD.BK_PUT](a) { const r = new Reader(a); return { op: r.b(), id: r.b(), rc: r.b() }; },
/* v5: the drum track's step: the lanes on (16 bits), their levels and ratchets (2 bits each) */
[CMD.DRUM_STEP](a) {
const r = new Reader(a);
@@ -536,6 +560,13 @@ const req = {
trackStep: (tr, i, st) => [CMD.TRACK_STEP, st ? [tr & 0x7F, ...req.stepSet(i, st)[1]] : [tr & 0x7F, i & 0x7F]],
/* v4: get (v == null) or set parameter id (P_*) of track tr, clamped as SET */
trackParam: (tr, id, v) => [CMD.TRACK_PARAM, v == null ? [tr & 0x7F, id & 0x7F] : [tr & 0x7F, id & 0x7F, ...v14enc(v)]],
/* v6: backup / restore */
bkList: () => [CMD.BK_LIST, []],
bkGet: (id, off, n) => [CMD.BK_GET, [id & 0x7F, ...u35enc(off), n & 0x7F, (n >> 7) & 0x7F]],
bkBegin: (id, len, crc) => [CMD.BK_PUT, [0, id & 0x7F, ...u35enc(len), ...u35enc(crc)]],
bkData: (id, off, bytes) => [CMD.BK_PUT, [1, id & 0x7F, ...u35enc(off), ...pack7(bytes)]],
bkCommit: (id) => [CMD.BK_PUT, [2, id & 0x7F]],
bkAbort: (id) => [CMD.BK_PUT, [3, id & 0x7F]],
};
/* which reply belongs to which request (the device echoes these) */
@@ -550,6 +581,8 @@ function replyMatches(cmd, args, a) {
case CMD.TRACK_MIX: case CMD.TRACK_DUMP: case CMD.DRUM_STEP: return a[0] === args[0];
case CMD.WATCH: return (a[0] & 1) === (args[0] & 1); /* bit 1: v4 firmware only */
case CMD.TRACK_STEP: case CMD.TRACK_PARAM: return a[0] === args[0] && a[1] === args[1];
case CMD.BK_GET: return a[0] === args[0] && [0, 1, 2, 3, 4].every((k) => a[2 + k] === args[1 + k]);
case CMD.BK_PUT: return a[0] === args[0] && a[1] === args[1];
default: return true;
}
}
@@ -942,20 +975,40 @@ function chopEqual(start, end, n) {
}
/* the chops of sorted markers: each to the next marker (the last to the end), cut at maxLen samples
when maxLen > 0 -> [{start, end}] (all of them; the slot takes CHOP.MAX) */
function chopList(marks, total, maxLen = 0) {
when maxLen > 0 -> [{start, end, i, off, full}] (all of them; the slot takes CHOP.MAX).
opt[i] (optional) = {off: left out of the slot, len: its own length in samples, over maxLen};
a chop is never longer than up to the next marker (`full`) */
function chopList(marks, total, maxLen = 0, opt = null) {
return marks.map((m, i) => {
let e = i + 1 < marks.length ? marks[i + 1] : total;
if (maxLen > 0) e = Math.min(e, m + maxLen);
return { start: m, end: Math.max(m + 1, e) };
const full = Math.max(m + 1, i + 1 < marks.length ? marks[i + 1] : total), o = (opt && opt[i]) || {};
let e = full;
if (o.len > 0) e = Math.min(e, m + o.len);
else if (maxLen > 0) e = Math.min(e, m + maxLen);
return { start: m, end: Math.max(m + 1, e), i, off: !!o.off, full };
});
}
/* the chops the slot gets: mode 0 the kept ones, the first CHOP.MAX of them; mode 1 the chop `sel` */
function chopPick(chops, mode = 0, sel = 0) {
if (mode === 1) return chops.length ? [chops[Math.max(0, Math.min(chops.length - 1, sel))]] : [];
return chops.filter((c) => !c.off).slice(0, CHOP.MAX);
}
/* the longest common length L (samples) so the chops, each cut at L, fit in room; Infinity if they fit */
function chopFit(chops, room) {
const len = chops.map((c) => c.end - c.start), sum = (L) => len.reduce((a, n) => a + Math.min(n, L), 0);
if (sum(Infinity) <= room) return Infinity;
let lo = 0, hi = Math.max(...len);
while (lo < hi) { const L = (lo + hi + 1) >> 1; if (sum(L) <= room) lo = L; else hi = L - 1; }
return lo;
}
/* chops -> slot zones {s (Int16Array, one gain for all: their levels are kept), root, lo, hi, fname}.
mode 0: one key each from key0 (each key plays its chop at its own speed, the keys between are silent)
mode 1: the chop `sel` alone over the whole keyboard, at its own speed on key0 */
mode 0: the kept chops (chopPick), one key each from key0 (each key plays its chop at its own speed,
the keys between are silent); mode 1: the chop `sel` alone over the whole keyboard, at its own speed
on key0. The file names keep the chop's own number. */
function chopZones(x, chops, key0, mode = 0, sel = 0) {
const use = mode === 1 ? [chops[Math.max(0, Math.min(chops.length - 1, sel))]] : chops.slice(0, CHOP.MAX);
const use = chopPick(chops, mode, sel);
let pk = 1e-9;
for (const c of use) for (let i = c.start; i < c.end; i++) pk = Math.max(pk, Math.abs(x[i]));
return use.map((c, j) => {
@@ -968,7 +1021,7 @@ function chopZones(x, chops, key0, mode = 0, sel = 0) {
}
const key = Math.min(127, key0 + (mode === 1 ? 0 : j));
return { s, root: key, lo: mode === 1 ? 0 : key, hi: mode === 1 ? 127 : key,
fname: `CHOP${String((mode === 1 ? sel : j) + 1).padStart(2, "0")}_${NOTE_NAMES[key % 12]}${Math.floor(key / 12) - 1}.wav` };
fname: `CHOP${String((c.i != null ? c.i : mode === 1 ? sel : j) + 1).padStart(2, "0")}_${NOTE_NAMES[key % 12]}${Math.floor(key / 12) - 1}.wav` };
});
}
@@ -1161,6 +1214,111 @@ const bank = {
};
/* the current sound: DUMP + the first 16 steps */
/* ---- v6: the complete backup (projects, sections, user presets, samples, settings) ---- */
function u35enc(v) { v >>>= 0; return [0, 1, 2, 3, 4].map((k) => Math.floor(v / 2 ** (7 * k)) & 0x7F); }
function u35dec(r) { let v = 0; for (let k = 0; k < 5; k++) v += r.b() * 2 ** (7 * k); return v >>> 0; }
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function b64enc(b) {
let s = "";
for (let i = 0; i < b.length; i += 3) {
const n = (b[i] << 16) | ((b[i + 1] || 0) << 8) | (b[i + 2] || 0);
s += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < b.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < b.length ? B64[n & 63] : "=");
}
return s;
}
function b64dec(s) {
s = String(s).replace(/[^A-Za-z0-9+/]/g, "");
const out = new Uint8Array((s.length * 3) >> 2);
let o = 0, acc = 0, bits = 0;
for (const c of s) {
acc = ((acc << 6) | B64.indexOf(c)) & 0xFFFFFF;
bits += 6;
if (bits >= 8) { bits -= 8; out[o++] = (acc >> bits) & 255; }
}
return out.subarray(0, o);
}
/* object ids (firmware editor.c ED_BK_IDS): 0 the working project, 1 the settings, 2..5 projects A..D,
6..7 the user preset banks, 32..34 the sample slots USR1..3 */
const BK = { FORMAT: "sloop-backup", VERSION: 1, SAMPLES: [32, 33, 34], RESTORE: [6, 7, 2, 3, 4, 5, 0, 1] };
class BackupError extends Error { constructor(code, msg) { super(msg); this.code = code; } }
/* read everything; progress(done, total bytes) */
async function backupCapture(rq, info, progress = () => {}) {
const L = parse[CMD.BK_LIST](await rq(req.bkList(), { timeout: 5000, retries: 0 }));
if (L.rc) throw new BackupError("bkRc" + L.rc, `LIST rc ${L.rc}`);
const total = L.items.reduce((s, it) => s + it.len, 0), objects = [];
let done = 0;
for (const it of L.items) {
const data = new Uint8Array(it.len);
for (let off = 0; off < it.len; off += 256) {
const n = Math.min(256, it.len - off);
const g = parse[CMD.BK_GET](await rq(req.bkGet(it.id, off, n), { timeout: 1500, retries: 2 }));
if (g.rc) throw new BackupError(g.rc === 5 ? "bkStale" : "bkRead", `GET ${it.id}+${off} rc ${g.rc}`);
if (g.data.length !== n) throw new BackupError("bkRead", `GET ${it.id}+${off}: ${g.data.length} bytes`);
data.set(g.data, off);
done += n;
progress(done, total);
}
if (crc32(data) !== it.crc) throw new BackupError("bkStale", `object ${it.id}: CRC`);
objects.push({ id: it.id, len: it.len, crc: it.crc, data: b64enc(data) });
}
return { format: BK.FORMAT, version: BK.VERSION, firmware: info.version, date: new Date().toISOString(), objects };
}
/* a backup file -> {id: Uint8Array}; every object checked against its length and CRC */
function backupObjects(file) {
if (!file || file.format !== BK.FORMAT || !(file.version >= 1) || !Array.isArray(file.objects)) throw new BackupError("bkBad", "not a SLOOP backup");
const m = new Map();
for (const o of file.objects) {
const d = b64dec(o.data || "");
if (![...BK.RESTORE, ...BK.SAMPLES].includes(o.id) || d.length !== o.len || crc32(d) !== (o.crc >>> 0))
throw new BackupError("bkBad", `object ${o.id}: damaged`);
m.set(o.id, d);
}
if (!m.has(0) || !m.has(1)) throw new BackupError("bkBad", "incomplete backup");
return m;
}
/* write it back: banks, projects, the working project, the settings, then the samples */
async function backupRestore(rq, file, progress = () => {}) {
const m = backupObjects(file);
const total = [...m.values()].reduce((s, d) => s + d.length, 0) || 1;
let done = 0;
for (const id of BK.RESTORE) {
if (!m.has(id)) continue;
const d = m.get(id);
let r = parse[CMD.BK_PUT](await rq(req.bkBegin(id, d.length, crc32(d)), { timeout: 1500, retries: 1 }));
if (r.rc) throw new BackupError("bkWrite", `begin ${id} rc ${r.rc}`);
for (let off = 0; off < d.length; off += 256) {
r = parse[CMD.BK_PUT](await rq(req.bkData(id, off, d.subarray(off, off + 256)), { timeout: 1500, retries: 1 }));
if (r.rc) throw new BackupError("bkWrite", `data ${id}+${off} rc ${r.rc}`);
done += Math.min(256, d.length - off);
progress(done, total);
}
r = parse[CMD.BK_PUT](await rq(req.bkCommit(id), { timeout: 5000, retries: 0 }));
if (r.rc === 3) throw new BackupError("bkStop", "stop the song first");
if (r.rc) throw new BackupError("bkWrite", `commit ${id} rc ${r.rc}`);
}
for (const id of BK.SAMPLES) {
if (!m.has(id)) continue;
const d = m.get(id), k = id - 32;
if (!d.length) {
const e = parse[CMD.SMP_ERASE](await rq(req.smpErase(k), { timeout: 2500, retries: 0 }));
if (e.rc) throw new BackupError("bkWrite", `erase USR${k + 1} rc ${e.rc}`);
continue;
}
let r = parse[CMD.SMP_BEGIN](await rq(req.smpBegin(k), { timeout: 1000, retries: 0 }));
if (r.rc) throw new BackupError("bkWrite", `USR${k + 1} begin rc ${r.rc}`);
const data = d.subarray(SMP.DATA_OFF);
for (let off = 0; off < data.length; off += 256) {
const w = parse[CMD.SMP_WRITE](await rq(req.smpWrite(k, SMP.DATA_OFF + off, data.subarray(off, off + 256)), { timeout: 1000, retries: 1 }));
if (w.rc) throw new BackupError("bkWrite", `USR${k + 1} write rc ${w.rc}`);
done += Math.min(256, data.length - off);
progress(done, total);
}
r = parse[CMD.SMP_END](await rq(req.smpEnd(k, d.subarray(0, SMP.HDR_LEN)), { timeout: 2000, retries: 0 }));
if (r.rc) throw new BackupError("bkWrite", `USR${k + 1} end rc ${r.rc}`);
}
return true;
}
async function capturePatch(rq, info, name) {
const dump = parse[CMD.DUMP](await rq(req.dump()), info);
const steps = [];
@@ -1252,7 +1410,7 @@ function makeMockDevice(opt = {}) {
D("BPM", F.BPM, 40, 240, 90), D("SWING", F.SWING, 0, 100, 0), E("CLICK", ["OFF", "REC", "ON"], 0), D("TUNE", F.INT, -50, 50, 0),
E("TIME", NDIV, 1), D("FDBK", F.PCT, 0, 120, 60), D("COLR", F.PCT, 0, 127, 70), D("MIX", F.PCT, 0, 127, 90),
D("SIZE", F.PCT, 0, 127, 90), D("DAMP", F.PCT, 0, 127, 60), D("CRT", F.LFOHZ, 0, 127, 40), D("CDP", F.PCT, 0, 127, 60),
E("MIDI", NDASH, 0), E("SYNC", NDASH, 0), E("ROUT", NDASH, 0), D("CPU", F.INT, 0, 0, 0),
E("MIDI", NDASH, 0), E("SYNC", ["INT", "USB", "TRS"], 0), E("ROUT", NDASH, 0), D("CPU", F.INT, 0, 0, 0),
D("SLOT", F.INT, 1, 4, 1), E("NAME", NDASH, 0), E("LOAD", NGO, 0), E("SAVE", NGO, 0),
E("ENG", ["ANALOG", "DIGITAL", "PHASE", "LOFI", "SAMPLE", "VOICE", "TRIO", "WHEEL",
"GRAIN"], 0), E("SET", NGO, 0),
@@ -1379,6 +1537,8 @@ function makeMockDevice(opt = {}) {
slots: [null, null, null, null],
smp: [0, 1, 2].map(() => ({ flash: new Uint8Array(SMP.SLOT_SIZE).fill(0xFF), zones: 0, name: "", len: 0, next: SMP.DATA_OFF })),
bank: new Array(opt.slots || 32).fill(null), /* user presets: {engine, name, p, pattern} */
settings: Uint8Array.from({ length: 88 }, (_, i) => (i * 37 + 5) & 0xFF), /* v6: the settings object (opaque here) */
bkSnap: null, bkPut: null,
watch: false, v4: false, lastReq: 0,
};
for (const k of ["engine", "preset", "p", "step"]) {
@@ -1521,7 +1681,7 @@ function makeMockDevice(opt = {}) {
s(opt.legacy ? "FELUCCA 0.4 BETA (MOCK)" : opt.v3 ? "FELUCCA 0.8 (MOCK)" : "FELUCCA SLOOP 2.0 (MOCK)"); b(ENG.length); b(P_COUNT); b(G_COUNT); b(NSTEP); b(P_E0);
ENG.forEach((e) => s(e.name));
if (!opt.legacy) b(NTRK);
if (v5) b(5);
if (v5) b(opt.noBackup ? 5 : 6); /* v6: backup / restore */
break;
case CMD.GET: case CMD.SET: {
if (a.length < 2) return null;
@@ -1676,6 +1836,53 @@ function makeMockDevice(opt = {}) {
b(a[0]); b(rc);
break;
}
/* v6 backup: the mock's objects are JSON bytes (projects, banks) and the raw sample slots */
case CMD.BK_LIST: {
if (opt.noBackup) return null;
const enc = (o) => Uint8Array.from(Array.from(JSON.stringify(o), (c) => c.charCodeAt(0) & 0x7F));
const bankOf = (h) => { const x = st.bank.slice(h * 16, h * 16 + 16); return x.some(Boolean) ? enc(x) : new Uint8Array(0); };
st.bkSnap = new Map([[0, enc(project())], [1, st.settings.slice()], ...[0, 1, 2, 3].map((k) => [2 + k, st.slots[k] ? enc(st.slots[k]) : new Uint8Array(0)]),
[6, bankOf(0)], [7, bankOf(1)], ...[0, 1, 2].map((k) => [32 + k, st.smp[k].zones ? st.smp[k].flash.slice(0, SMP.DATA_OFF + st.smp[k].len) : new Uint8Array(0)])]);
st.bkPut = null;
b(0); b(st.bkSnap.size);
for (const [id, d] of st.bkSnap) { b(id); out.push(...u35enc(d.length), ...u35enc(crc32(d))); }
break;
}
case CMD.BK_GET: {
if (opt.noBackup || a.length !== 8) return null;
const r = new Reader(a), id = r.b(), off = u35dec(r), n = r.b() | (r.b() << 7);
const d = st.bkSnap && st.bkSnap.get(id);
const rc = !d || !n || n > 256 || off + n > d.length ? 1 : st.bkPut && id === 0 ? 5 : 0;
b(id); b(rc); out.push(...u35enc(off)); b(rc ? 0 : n); b(rc ? 0 : n >> 7);
if (!rc) out.push(...pack7(d.subarray(off, off + n)));
break;
}
case CMD.BK_PUT: {
if (opt.noBackup || a.length < 2) return null;
const op = a[0], id = a[1], r = new Reader(a.slice(2));
let rc = 1;
if (op === 0 && a.length === 12 && [0, 1, 2, 3, 4, 5, 6, 7].includes(id)) {
const len = u35dec(r), crc = u35dec(r);
if ((id >= 2 || len) && len <= 1 << 20) { st.bkPut = { id, len, crc, pos: 0, buf: new Uint8Array(len) }; st.bkSnap = null; rc = 0; }
} else if (!st.bkPut || st.bkPut.id !== id) rc = 5;
else if (op === 1 && a.length >= 9) {
const off = u35dec(r), d = unpack7(a.slice(7));
if (off === st.bkPut.pos && d.length && d.length <= st.bkPut.len - off) { st.bkPut.buf.set(d, off); st.bkPut.pos += d.length; rc = 0; }
} else if (op === 2) {
const P = st.bkPut;
st.bkPut = null;
rc = P.pos !== P.len || crc32(P.buf) !== P.crc ? 2 : 0;
if (!rc) try {
const js = () => JSON.parse(Array.from(P.buf, (c) => String.fromCharCode(c)).join(""));
if (id === 1) { if (P.len !== st.settings.length) throw 0; st.settings = P.buf.slice(); }
else if (id === 0) { const o = js(); st.tracks = o.tracks; st.sel = o.sel; st.g = o.g; }
else if (id <= 5) st.slots[id - 2] = P.len ? js() : null;
else { const x = P.len ? js() : new Array(16).fill(null); for (let i = 0; i < 16; i++) st.bank[(id - 6) * 16 + i] = x[i] || null; }
} catch (e) { rc = 2; }
} else if (op === 3) { st.bkPut = null; rc = 0; }
b(op); b(id); b(rc);
break;
}
case CMD.SMP_INFO:
b(3); b(SMP.SLOT_SIZE / 1024);
st.smp.forEach((u) => { b(u.zones); s(u.zones ? u.name : ""); b(u.zones ? Math.ceil(u.len / 1024) : 0); });
@@ -1859,14 +2066,18 @@ const TEXT = {
samples: "サンプル", smpHelp: "WAV をドロップするか選んでください。1 スロットに 16 ファイルまで、モノ 22050 Hz の ADPCM で合計約 7 秒。SAMPLE エンジンの SET(または SLICE エンジンの SRC)で USR1〜USR3 を選ぶと鳴ります。",
zones: "ゾーン", smpName: "名前", chooseFiles: "ファイルを選ぶ", upload: "書き込む", erase: "消去", clearList: "リストを消す",
file: "ファイル", root: "ルート", keys: "鍵盤", length: "長さ", remove: "外す",
chopOpen: "音を開く", chopHelp: "録音(WAV、MP3、AIFF…)を開くかドロップし、チョップを決めてスロットへ。1 キーに 1 チョップ。",
chopOpen: "音を開く", chopHelp: "録音(WAV、MP3、AIFF…)を開くかドロップし、チョップを決めてスロットへ。1 キーに 1 チョップ。長い録音(7 秒以上)でも、使うチョップを選び長さを調整できます。",
chopDrop: "ここに録音をドロップ、またはクリック", chopPlay: "▶ 再生", chopStop: "■ 停止", chopTap: "TAP",
chopSnap: "アタックに吸着", chopClear: "マーカーを消去", chopHits: "アタック検出", chopSens: "感度",
chopGrid: "グリッド", chopEqual: "等分", chopKey: "最初のキー", chopModeKeys: "1 キーに 1 チョップ",
chopModeOne: "選択チョップを鍵盤全体に", chopMax: "最大長", chopTo: "送信先", chopZip: "WAV をダウンロード",
chopChops: "チョップ", chopTooLong: "スロットに入りません", chopTooMany: "(最大 16 チョップ。残りは使われません)",
chopLoaded: "読み込みました: ", chopSent: "チョップを書き込みました ",
chopHint: "スペース: 再生中に TAP(停止中は再生/停止)· 1–9 0: 試聴 · ダブルクリック: 追加 · ドラッグ: 移動 · ← →: 微調整 · Del: 削除 · ホイール: ズーム",
chopSel: "チョップ", chopKeep: "使う", chopLen: "長さ", chopFull: "次のマーカーまで", chopAll: "すべて使う", chopNone: "すべて外す",
chopFit: "スロットに合わせる", chopKept: "使用", chopFitted: "長いチョップを短くしました: 最大 ",
chopOverHint: "— チョップを外すか、短くするか、「スロットに合わせる」を押してください",
chopKeepHint: "チェックを外したチョップはスロットにも WAV にも入りません。長い録音でも必要な部分だけ選べます。",
chopHint: "スペース: 再生中に TAP(停止中は再生/停止)· 1–9 0: 試聴 · ダブルクリック: 追加 · ドラッグ: 移動 · ← →: 微調整 · K: 使う/外す · 下のつまみ: 長さ · Del: 削除 · ホイール: ズーム",
smpTooBig: "大きすぎます", smpDecodeFail: "読み込めません: ", smpUploading: "書き込み中 USR", smpDone: "書き込みました USR",
smpFail: "サンプルの書き込みに失敗しました: ", smpErased: "消去しました USR",
confirmErase: "USR{n} を消去しますか?", confirmUpload: "USR{n} に書き込みますか? 今の内容は消えます。",
@@ -1904,6 +2115,11 @@ const TEXT = {
mixer: "ミキサー", mixHelp: "本体の TRACKS ページと同じ 4 トラック。フェーダーはレベル(ドラムは GLO > DRUMS LEVEL)。パンはどのトラックも選択を変えずに書き込みます(0.8 のファームウェアでは一瞬そのトラックを選びます)。REC は本体での録音待機の表示です。",
level: "レベル", pan: "パン", mute: "ミュート", rec: "REC", selectTrack: "選択", selectedTrack: "選択中",
projHelp: "プロジェクトは本体の状態をまとめて保存します: 4 トラックの音色とパターン、選択中のトラック、グローバル設定。",
bkTitle: "バックアップ", bkHelp: "FM-1 の中身をすべて 1 つのファイルに保存します: 今の曲、プロジェクト 1〜4(ソングのセクション A〜D)、ユーザープリセット、サンプル USR1〜3、設定(色、キャリブレーション、ソング、ライト)。復元すると、本体はファイルの状態に戻ります(今の内容は上書きされます)。",
bkSave: "バックアップを保存", bkLoad: "ファイルから復元", bkSaving: "バックアップ中 ", bkSaved: "バックアップを保存しました",
bkRestoring: "復元中 ", bkRestored: "復元しました", bkConfirm: "FM-1 の今の内容をすべてこのバックアップで置き換えます。続けますか?",
bkBad: "SLOOP のバックアップファイルではないか、壊れています: ", bkStop: "FM-1 の再生を止めてから、もう一度復元してください。",
bkStale: "本体の内容が途中で変わりました。もう一度バックアップしてください: ", bkRead: "読み取りエラー: ", bkWrite: "書き込みエラー: ", bkRc4: "フラッシュがありません",
system: "システム", firmware: "ファームウェア", sync: "同期", tracksN: "トラック", stepsN: "ステップ数", enginesL: "エンジン",
smpSlots: "サンプルスロット", userBank: "ユーザープリセット", none: "なし",
},
@@ -1930,14 +2146,18 @@ const TEXT = {
samples: "Samples", smpHelp: "Drop or choose WAV files. Up to 16 files per slot, stored as mono 22050 Hz ADPCM (about 7 s in all). Select USR1–USR3 with SET on the SAMPLE engine (or SRC on the SLICE engine).",
zones: "zones", smpName: "Name", chooseFiles: "Choose files", upload: "Upload", erase: "Erase", clearList: "Clear list",
file: "File", root: "Root", keys: "Keys", length: "Length", remove: "Remove",
chopOpen: "Open a sound", chopHelp: "Open or drop a recording (WAV, MP3, AIFF…), mark the chops, send them to a slot: one chop per key.",
chopOpen: "Open a sound", chopHelp: "Open or drop a recording (WAV, MP3, AIFF…), mark the chops, send them to a slot: one chop per key. Any length: a recording longer than a slot (7 s) works, keep the chops you want and adjust them.",
chopDrop: "Drop a recording here, or click", chopPlay: "▶ Play", chopStop: "■ Stop", chopTap: "TAP",
chopSnap: "snap to the hit", chopClear: "Clear markers", chopHits: "Find hits", chopSens: "sensitivity",
chopGrid: "Grid", chopEqual: "Equal parts", chopKey: "First key", chopModeKeys: "one key per chop",
chopModeOne: "selected chop, whole keyboard", chopMax: "max length", chopTo: "Send to", chopZip: "Download WAVs",
chopChops: "chops", chopTooLong: "too long for a slot", chopTooMany: "(16 chops at most: the rest are left out)",
chopLoaded: "Loaded: ", chopSent: "Chops in ",
chopHint: "space: TAP while it plays (play/stop when stopped) · 1–9 0: listen · double-click: add · drag: move · ← →: nudge · Del: remove · wheel: zoom",
chopSel: "Chop", chopKeep: "keep", chopLen: "length", chopFull: "Up to the next marker", chopAll: "Keep all", chopNone: "Keep none",
chopFit: "Fit to slot", chopKept: "kept", chopFitted: "Long chops shortened to at most ",
chopOverHint: "— untick chops, shorten them, or press Fit to slot",
chopKeepHint: "Unticked chops go neither to the slot nor to the WAVs: from a long recording, keep only what you want.",
chopHint: "space: TAP while it plays (play/stop when stopped) · 1–9 0: listen · double-click: add · drag: move · ← →: nudge · K: keep / leave out · bottom handle: length · Del: remove · wheel: zoom",
smpTooBig: "too large", smpDecodeFail: "Cannot read: ", smpUploading: "Uploading USR", smpDone: "Uploaded USR",
smpFail: "Sample upload failed: ", smpErased: "Erased USR",
confirmErase: "Erase USR{n}?", confirmUpload: "Write to USR{n}? Its current contents will be replaced.",
@@ -1975,6 +2195,11 @@ const TEXT = {
mixer: "Mixer", mixHelp: "The four tracks of the device's TRACKS page. The fader is the level (drums: GLO > DRUMS LEVEL). Pan is written to any track without changing the selection (firmware 0.8: by selecting it for a moment). REC shows a track armed for live recording on the device.",
level: "Level", pan: "Pan", mute: "Mute", rec: "REC", selectTrack: "Select", selectedTrack: "Selected",
projHelp: "A project keeps the whole device state: the sound and pattern of all four tracks, the selected track and the global settings.",
bkTitle: "Backup", bkHelp: "Everything on the FM-1 in one file: the music you are working on, the projects 1–4 (the song sections A–D), the user presets, the samples USR1–3 and the settings (colours, calibration, the song, the lights). Restoring puts the FM-1 back as it was in the file (what is on it now is replaced).",
bkSave: "Save a backup", bkLoad: "Restore from a file", bkSaving: "Backing up ", bkSaved: "Backup saved",
bkRestoring: "Restoring ", bkRestored: "Restored", bkConfirm: "Replace everything on the FM-1 with this backup?",
bkBad: "Not a SLOOP backup, or damaged: ", bkStop: "Stop the FM-1 (PLAY), then restore again.",
bkStale: "The FM-1 changed during the backup; back up again: ", bkRead: "Read error: ", bkWrite: "Write error: ", bkRc4: "No flash",
system: "System", firmware: "Firmware", sync: "Sync", tracksN: "Tracks", stepsN: "Steps", enginesL: "Engines",
smpSlots: "Sample slots", userBank: "User presets", none: "none",
},
@@ -2279,6 +2504,7 @@ function buildUI() {
renderSlots();
renderSamples();
renderSysinfo();
$("bkgroup").hidden = !(dev.info.proto >= 6); /* v6 firmware: backup / restore */
}
/* the track selector (v3): T1..T3 synth parts, T4 the drum track; the editor shows the selected one */
@@ -2915,16 +3141,45 @@ async function smpErase(k) {
/* ---------------------------------------------------------------- CHOP --- */
/* Load a recording, mark the chops (live: TAP / space while it plays, each tap moved to the hit it
meant; or by hits, a tempo grid, equal parts; double-click adds, drag moves, Delete removes),
audition them (click, keys 1-9 0), then one chop per key into USR1..3 or as WAV files. */
const CH = { x: null, nov: null, name: "", marks: [], sel: -1, v0: 0, v1: 1, ctx: null, src: null, t0: 0, raf: 0,
drag: -1, key0: 60, mode: 0, maxLen: 0, ui: null };
audition them (click, keys 1-9 0), keep or leave out each one and set its length (a recording longer
than a slot: keep the chops you want, shorten them, or Fit to slot), then one chop per key into
USR1..3 or as WAV files. CH.opt[i] = {off, len} goes with marker i. */
const CH = { x: null, nov: null, name: "", marks: [], opt: [], sel: -1, v0: 0, v1: 1, ctx: null, src: null, t0: 0, raf: 0,
drag: -1, dragEnd: false, key0: 60, mode: 0, maxLen: 0, ui: null };
const chR = () => SMP.RATE;
const chSecs = (n) => (n / SMP.RATE).toFixed(2) + " s";
function chopChops() { return CH.x ? chopList(CH.marks, CH.x.length, Math.round(CH.maxLen * SMP.RATE)) : []; }
function chopUsed() { /* the chops the slot gets, and their samples */
const c = chopChops(), use = CH.mode === 1 ? (c[CH.sel] ? [c[CH.sel]] : c.slice(0, 1)) : c.slice(0, CHOP.MAX);
return { all: c, use, n: use.reduce((a, q) => a + (q.end - q.start), 0) };
function chopChops() { return CH.x ? chopList(CH.marks, CH.x.length, Math.round(CH.maxLen * SMP.RATE), CH.opt) : []; }
function chopUsed() { /* the chops the slot gets, their samples, and each chop's key */
const c = chopChops(), use = chopPick(c, CH.mode, Math.max(0, CH.sel)), key = new Map();
if (CH.mode === 0) use.forEach((q, j) => key.set(q.i, Math.min(127, CH.key0 + j)));
return { all: c, use, n: use.reduce((a, q) => a + (q.end - q.start), 0), key };
}
/* the label of chop i: its key, "—" when left out, nothing past the 16 kept ones or over the whole keyboard */
function chopKeyName(u, i) {
if (CH.mode === 1) return "";
const c = u.all[i];
return c && c.off ? " —" : u.key.has(i) ? " " + noteName(u.key.get(i)) : "";
}
function chopOpt(i) { return CH.opt[i] || (CH.opt[i] = { off: false, len: 0 }); }
function chopKeep(i, keep) { /* keep / leave out chop i (keep undefined: toggle) */
if (!CH.x || i < 0 || i >= CH.marks.length) return;
const o = chopOpt(i);
o.off = keep === undefined ? !o.off : !keep;
chopRender();
}
function chopKeepAll(keep) { if (CH.x) { CH.opt = CH.marks.map((_, i) => ({ ...chopOpt(i), off: !keep })); chopRender(); } }
function chopSetLen(i, len) { /* the length of chop i in samples (0: up to the next marker) */
if (!CH.x || i < 0 || i >= CH.marks.length) return;
chopOpt(i).len = Math.max(0, Math.round(len));
chopRender();
}
function chopFitAll() { /* shorten the longest kept chops so they all fit the slot */
const { use } = chopUsed(), L = chopFit(use, SMP.MAX_DATA * 2 - use.length); /* (an odd chop takes half a byte more) */
if (!isFinite(L)) return;
for (const c of use) if (c.end - c.start > L) chopOpt(c.i).len = L;
sayK("chopFitted", chSecs(L));
chopRender();
}
async function chopDecode(buf) { /* any file the browser decodes -> mono Float64 at SMP.RATE */
@@ -2945,6 +3200,7 @@ async function chopLoad(f) {
CH.nov = chopNovelty(x);
CH.name = f.name.replace(/\.[^.]*$/, "").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 8) || "CHOP";
CH.marks = [];
CH.opt = [];
CH.sel = -1;
CH.v0 = 0;
CH.v1 = x.length;
@@ -2953,16 +3209,27 @@ async function chopLoad(f) {
chopRender();
}
function chopSetMarks(m) {
CH.marks = [...new Set(m.map((v) => Math.max(0, Math.min(CH.x.length - 1, Math.round(v)))))].sort((a, b) => a - b);
/* new markers; opt (aligned with m) their options, else each keeps the options of the marker it was */
function chopSetMarks(m, opt = null) {
const was = new Map(CH.marks.map((v, i) => [v, CH.opt[i]])), seen = new Set(), pairs = [];
m.forEach((v, i) => {
const p = Math.max(0, Math.min(CH.x.length - 1, Math.round(v)));
if (seen.has(p)) return;
seen.add(p);
const o = opt ? opt[i] : was.get(p);
pairs.push([p, o ? { ...o } : { off: false, len: 0 }]);
});
pairs.sort((a, b) => a[0] - b[0]);
CH.marks = pairs.map((q) => q[0]);
CH.opt = pairs.map((q) => q[1]);
if (CH.sel >= CH.marks.length) CH.sel = CH.marks.length - 1;
chopRender();
}
function chopAdd(pos) { /* a new marker; one within 30 ms is moved there instead */
const near = CH.marks.findIndex((m) => Math.abs(m - pos) < 0.03 * chR());
const m = CH.marks.slice();
if (near >= 0) m[near] = pos; else m.push(pos);
chopSetMarks(m);
const m = CH.marks.slice(), opt = CH.marks.map((_, i) => CH.opt[i]);
if (near >= 0) m[near] = pos; else { m.push(pos); opt.push(null); }
chopSetMarks(m, opt);
CH.sel = CH.marks.indexOf(Math.round(pos));
chopDraw();
}
@@ -3044,12 +3311,18 @@ function chopDraw() {
g.clearRect(0, 0, W, Hh);
if (!CH.x) { g.fillStyle = DIM; g.font = "12px sans-serif"; g.fillText(t("chopDrop"), 8, Hh / 2); return; }
const x = CH.x, v0 = CH.v0, span = CH.v1 - CH.v0, X = (p) => (p - v0) / span * W, mid = Hh / 2 + 6;
const { all: chops, use } = chopUsed();
chops.forEach((c, i) => { /* the chops: the selected one filled, unused ones hatched */
const a = X(c.start), b = X(c.end);
if (b < 0 || a > W) return;
const U = chopUsed(), { all: chops, use } = U;
const hatch = (a, b) => { /* what the slot does not get */
g.save(); g.beginPath(); g.rect(a, 12, b - a, Hh - 12); g.clip(); g.strokeStyle = LINE;
for (let q = Math.floor(a / 8) * 8 - 8; q < b; q += 8) { g.beginPath(); g.moveTo(q, Hh); g.lineTo(q + 8, 12); g.stroke(); }
g.restore();
};
if (chops.length && chops[0].start > 0) hatch(X(0), X(chops[0].start));
chops.forEach((c, i) => { /* the chops: the selected one filled, left-out parts hatched */
const a = X(c.start), b = X(c.end), f = X(c.full);
if (f < 0 || a > W) return;
if (i === CH.sel) { g.fillStyle = LINE; g.fillRect(a, 12, b - a, Hh - 12); }
if (!use.includes(c)) { g.strokeStyle = LINE; for (let q = Math.floor(a / 8) * 8; q < b; q += 8) { g.beginPath(); g.moveTo(q, Hh); g.lineTo(q + 8, 12); g.stroke(); } }
if (!use.includes(c)) hatch(a, f); else if (c.end < c.full) hatch(b, f);
});
g.fillStyle = FG;
for (let px = 0; px < W; px++) { /* the wave: min / max per pixel */
@@ -3064,9 +3337,15 @@ function chopDraw() {
if (px < -1 || px > W + 1) return;
g.fillStyle = FG;
g.fillRect(Math.round(px), 0, i === CH.sel ? 2 : 1, Hh);
const key = CH.mode === 1 ? "" : (i < CHOP.MAX ? " " + noteName(Math.min(127, CH.key0 + i)) : "");
g.fillText(String(i + 1) + key, px + 3, 10);
g.fillText(String(i + 1) + chopKeyName(U, i), px + 3, 10);
});
const sc = chops[CH.sel];
if (sc) { /* the selected chop's end: a handle at the bottom, drag it */
const px = Math.round(X(sc.end));
g.fillStyle = FG;
g.fillRect(px - 1, Hh - 30, 2, 30);
g.beginPath(); g.moveTo(px, Hh - 30); g.lineTo(px - 7, Hh - 38); g.lineTo(px - 7, Hh - 22); g.closePath(); g.fill();
}
if (CH.src && CH.src.whole && CH.ctx) { /* the playhead, as heard */
const p = X(chopHeard());
g.fillStyle = DIM;
@@ -3099,6 +3378,17 @@ function chopUI() {
u.meter = el("progress", { max: SMP.MAX_DATA * 2, value: 0 });
u.room = el("span", { class: "dim" });
u.list = el("div", { class: "chops" });
/* the selected chop: keep it or not, its length; and all of them at once */
u.selName = el("b", { class: "selname" });
u.keep = el("input", { type: "checkbox", onchange: () => chopKeep(CH.sel, u.keep.checked) });
u.len = el("input", { type: "range", class: "len", min: 10, max: 1000, step: 1, title: t("chopLen"),
oninput: () => { const c = chopChops()[CH.sel]; if (c) { const ms = +u.len.value, full = c.full - c.start; chopSetLen(CH.sel, ms >= Math.floor(full / SMP.RATE * 1000) ? 0 : ms * SMP.RATE / 1000); } } });
u.lenTxt = el("span", { class: "dim" });
u.selPlay = el("button", { onclick: () => chopAudition(CH.sel) }, "▶");
u.full = el("button", { onclick: () => chopSetLen(CH.sel, 0) }, t("chopFull"));
u.selRow = el("div", { class: "head selrow" }, u.selName, el("label", {}, u.keep, " " + t("chopKeep")),
el("span", { text: t("chopLen") }), u.len, u.lenTxt, u.selPlay, u.full);
u.fit = el("button", { onclick: chopFitAll }, t("chopFit"));
u.send = [0, 1, 2].map((k) => el("button", { ic: "symbol_upload", onclick: () => chopSend(k) }, `USR${k + 1}`));
const region = () => { /* first..last marker when there are two, else all */
const m = CH.marks;
@@ -3123,30 +3413,51 @@ function chopUI() {
el("button", { onclick: () => { if (CH.x) { const [a, b] = region(); chopSetMarks(chopEqual(a, b, +u.n.value)); } } }, t("chopEqual")), u.n),
el("div", { class: "head" }, el("span", { text: t("chopKey") }), u.key, u.mode,
el("span", { text: t("chopMax") }), u.max, u.meter, u.room),
el("div", { class: "head" }, el("button", { onclick: () => chopKeepAll(true) }, t("chopAll")),
el("button", { onclick: () => chopKeepAll(false) }, t("chopNone")), u.fit,
el("span", { class: "dim", text: t("chopKeepHint") })),
u.list, u.selRow,
el("div", { class: "head" }, el("span", { text: t("chopTo") }), ...u.send,
el("button", { ic: "symbol_download", onclick: chopZip }, t("chopZip"))),
u.list);
el("button", { ic: "symbol_download", onclick: chopZip }, t("chopZip"))));
/* the wave: click = select + listen, double-click = a marker, drag a marker, wheel = zoom */
const posAt = (e) => { const r = u.cv.getBoundingClientRect(); return CH.v0 + (e.clientX - r.left) / r.width * (CH.v1 - CH.v0); };
const markAt = (e) => {
const r = u.cv.getBoundingClientRect(), per = (CH.v1 - CH.v0) / r.width;
return CH.marks.findIndex((m) => Math.abs(m - posAt(e)) < 5 * per);
};
const endAt = (e) => { /* on the selected chop's end handle (the bottom of the wave)? */
const c = chopChops()[CH.sel];
if (!c) return false;
const r = u.cv.getBoundingClientRect(), per = (CH.v1 - CH.v0) / r.width;
return e.clientY - r.top > r.height - 40 && Math.abs(c.end - posAt(e)) < 7 * per;
};
u.cv.addEventListener("pointerdown", (e) => {
if (!CH.x) { file.click(); return; }
u.cv.focus();
if (endAt(e)) { CH.dragEnd = true; u.cv.setPointerCapture(e.pointerId); return; }
const k = markAt(e);
if (k >= 0) { CH.drag = k; CH.sel = k; u.cv.setPointerCapture(e.pointerId); chopDraw(); return; }
const p = posAt(e), i = chopChops().findIndex((c) => p >= c.start && p < c.end);
if (i >= 0) chopAudition(i);
});
u.cv.addEventListener("pointermove", (e) => {
if (CH.drag < 0) { u.cv.style.cursor = CH.x && markAt(e) >= 0 ? "ew-resize" : "default"; return; }
if (CH.dragEnd) { /* the selected chop's length; up to the next marker = full */
const c = chopChops()[CH.sel];
if (!c) return;
const n = Math.round(Math.max(0.01 * SMP.RATE, Math.min(c.full - c.start, posAt(e) - c.start)));
chopOpt(CH.sel).len = n >= c.full - c.start ? 0 : n;
chopDraw();
return;
}
if (CH.drag < 0) { u.cv.style.cursor = CH.x && (markAt(e) >= 0 || endAt(e)) ? "ew-resize" : "default"; return; }
const m = CH.marks, k = CH.drag, lo = k ? m[k - 1] + 1 : 0, hi = k + 1 < m.length ? m[k + 1] - 1 : CH.x.length - 1;
m[k] = Math.round(Math.max(lo, Math.min(hi, posAt(e))));
chopDraw();
});
u.cv.addEventListener("pointerup", () => { if (CH.drag >= 0) { CH.drag = -1; chopRender(); } });
u.cv.addEventListener("pointerup", () => {
if (CH.dragEnd) { CH.dragEnd = false; chopRender(); }
if (CH.drag >= 0) { CH.drag = -1; chopRender(); }
});
u.cv.addEventListener("dblclick", (e) => { if (CH.x) chopAdd(u.snap.checked ? chopSnap(CH.x, CH.nov, posAt(e), 0.02) : Math.round(posAt(e))); });
u.cv.addEventListener("wheel", (e) => {
if (!CH.x) return;
@@ -3168,13 +3479,17 @@ function chopUI() {
if (k === " ") { e.preventDefault(); if (CH.src && CH.src.whole) chopTap(e); else chopPlay(Math.round(CH.v0), CH.x.length, true); }
else if (k === "Enter" || k === "Escape") { e.preventDefault(); if (CH.src) chopStop(); else chopPlay(Math.round(CH.v0), CH.x.length, true); }
else if (/^[0-9]$/.test(k)) { e.preventDefault(); chopAudition(k === "0" ? 9 : +k - 1); }
else if ((k === "Delete" || k === "Backspace") && CH.sel >= 0) { e.preventDefault(); chopSetMarks(CH.marks.filter((_, i) => i !== CH.sel)); }
else if ((k === "Delete" || k === "Backspace") && CH.sel >= 0) {
e.preventDefault();
chopSetMarks(CH.marks.filter((_, i) => i !== CH.sel), CH.marks.map((_, i) => CH.opt[i]).filter((_, i) => i !== CH.sel));
}
else if ((k === "k" || k === "K") && CH.sel >= 0) { e.preventDefault(); chopKeep(CH.sel); }
else if ((k === "ArrowLeft" || k === "ArrowRight") && CH.sel >= 0) { /* nudge the selected marker: 2 ms, shift 20 ms */
e.preventDefault();
const m = CH.marks.slice();
m[CH.sel] += (k === "ArrowLeft" ? -1 : 1) * Math.round((e.shiftKey ? 0.02 : 0.002) * SMP.RATE);
const keep = CH.sel;
chopSetMarks(m);
chopSetMarks(m, CH.marks.map((_, i) => CH.opt[i]));
CH.sel = keep;
chopRender();
}
@@ -3189,17 +3504,36 @@ function chopUI() {
function chopRender() {
const u = CH.ui;
if (!u) return;
const { all, use, n } = chopUsed(), room = SMP.MAX_DATA * 2, over = n > room;
u.info.textContent = CH.x ? `${CH.name} · ${chSecs(CH.x.length)} · ${all.length} ${t("chopChops")}` : t("chopHelp");
const U = chopUsed(), { all, use, n } = U, room = SMP.MAX_DATA * 2, over = use.reduce((a, q) => a + ((q.end - q.start + 1) >> 1), 0) > SMP.MAX_DATA;
const kept = all.filter((c) => !c.off).length;
u.info.textContent = CH.x ? `${CH.name} · ${chSecs(CH.x.length)} · ${all.length} ${t("chopChops")}` +
(kept < all.length ? ` (${kept} ${t("chopKept")})` : "") : t("chopHelp");
u.meter.value = Math.min(room, n);
u.room.textContent = `${chSecs(n)} / ${chSecs(room)}` + (over ? " " + t("chopTooLong") : "") +
(CH.mode === 0 && all.length > CHOP.MAX ? " " + t("chopTooMany") : "");
u.room.textContent = `${chSecs(n)} / ${chSecs(room)}` + (over ? " " + t("chopTooLong") + " " + t("chopOverHint") : "") +
(CH.mode === 0 && kept > CHOP.MAX ? " " + t("chopTooMany") : "");
u.room.className = over ? "bad" : "dim";
u.fit.disabled = !over;
u.send.forEach((b) => { b.disabled = !use.length || over || smpBusy || !dev || !dev.smp; });
u.list.replaceChildren(...all.map((c, i) => el("button", {
class: "chip" + (i === CH.sel ? " on" : "") + (use.includes(c) ? "" : " off"),
title: `${chSecs(c.start)} · ${chSecs(c.end - c.start)}`, onclick: () => chopAudition(i),
}, `${i + 1}` + (CH.mode === 1 ? "" : i < CHOP.MAX ? " " + noteName(Math.min(127, CH.key0 + i)) : ""))));
u.list.replaceChildren(...all.map((c, i) => { /* a chip per chop: the box keeps it, the rest listens */
const box = el("input", { type: "checkbox", title: t("chopKeep"), onclick: (e) => { e.stopPropagation(); chopKeep(i, box.checked); } });
box.checked = !c.off;
return el("span", {
class: "chip" + (i === CH.sel ? " on" : "") + (use.includes(c) ? "" : " off"),
title: `${chSecs(c.start)} · ${chSecs(c.end - c.start)}` + (c.end < c.full ? ` / ${chSecs(c.full - c.start)}` : ""),
onclick: () => chopAudition(i),
}, box, `${i + 1}` + chopKeyName(U, i));
}));
const c = all[CH.sel]; /* the selected chop's row */
u.selRow.hidden = !c;
if (c) {
const full = c.full - c.start;
u.selName.textContent = `${t("chopSel")} ${CH.sel + 1}${chopKeyName(U, CH.sel)}`;
u.keep.checked = !c.off;
u.len.max = String(Math.max(10, Math.floor(full / SMP.RATE * 1000)));
u.len.value = String(Math.round((c.end - c.start) / SMP.RATE * 1000));
u.lenTxt.textContent = `${chSecs(c.end - c.start)} / ${chSecs(full)}`;
u.full.disabled = c.end >= c.full;
}
chopDraw();
}
@@ -3208,7 +3542,7 @@ async function chopSend(k) {
if (!CH.x || smpBusy) return;
const { use } = chopUsed();
if (!use.length) return;
const zones = chopZones(CH.x, chopChops(), CH.key0, CH.mode, Math.max(0, CH.sel));
const zones = chopZones(CH.x, chopChops(), CH.key0, CH.mode, Math.max(0, CH.sel)); /* (the kept ones) */
smpDraft[k].name = CH.name;
smpDraft[k].files = zones;
renderSamples();
@@ -3937,6 +4271,44 @@ function download(name, obj) {
}
const fileSlug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "patch";
const today = () => new Date().toISOString().slice(0, 10);
/* v6: backup / restore (the work: backupCapture / backupRestore above) */
function bkProgress(key) {
const pr = $("bk-prog");
pr.hidden = false;
return (d, n) => { pr.value = d / n; sayK(key, `${Math.round(100 * d / n)} %`); };
}
function bkReport(e) {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.code === "bkStop" ? "" : e.message);
else report(e);
}
$("bk-save").addEventListener("click", () => op(async () => {
try {
const arc = await backupCapture(rq, dev.info, bkProgress("bkSaving"));
download(`SLOOP-backup-${today()}.json`, arc);
sayK("bkSaved");
} catch (e) { bkReport(e); } finally { $("bk-prog").hidden = true; }
}));
$("bk-load").addEventListener("click", () => { if (dev) $("bk-file").click(); });
$("bk-file").addEventListener("change", async () => {
const f = $("bk-file").files[0];
$("bk-file").value = "";
if (!f || !dev) return;
let file;
try { file = JSON.parse(await f.text()); backupObjects(file); }
catch (e) { sayK("bkBad", e.message); return; }
if (!confirm(t("bkConfirm"))) return;
await op(async () => {
try {
selfLoad();
await backupRestore(rq, file, bkProgress("bkRestoring"));
dev.slotUsed = [null, null, null, null];
renderSlots();
try { await smpInfo(); renderSamples(); } catch (e) { /* shown by the next action */ }
await afterSoundChange("bkRestored");
} catch (e) { bkReport(e); } finally { $("bk-prog").hidden = true; }
});
});
$("libexp1").addEventListener("click", () => {
const p = lib.find((x) => x.id === libSel);
if (p) download(`felucca-patch-${fileSlug(p.name)}.json`, libraryFile("patch", [p], libCtx()));
+18 -4
View File
@@ -210,14 +210,28 @@ export class Updater {
return s2;
}
// resume: the device is already in update mode (loader) -> true when the write finished
async resume(image, onStep) {
// resume: the device is already in update mode (loader) -> true when the write finished. Only SLOOP's
// own loader is resumed, except for the return to the official firmware (opts.product: the official
// package, its identity checked once the FM-1 is back, after Felucca 1.0): that one is the official
// loader's own image, as M-UPGRADE would write it
async resume(image, onStep, opts = {}) {
const ota = await this.find(IS_OTA);
if (!ota) return false;
if (!OUR_LOADER(ota.id)) {
if (!OUR_LOADER(ota.id) && !opts.product) {
ota.link.close();
throw fail("foreign", `the FM-1 is in the update mode of another firmware (${ota.id.text}): finish that update with its own updater`, ota.id.text);
}
return (await this.write(ota, image, onStep || (() => {}))).finished;
const step = onStep || (() => {});
if (!(await this.write(ota, image, step)).finished) return false;
if (opts.product) {
step("reboot");
await sleep(3000);
const back = await this.waitFor((id) => !IS_OTA(id), 40000);
if (!back) throw fail("noreturn", "the FM-1 did not come back after the write: power-cycle it");
back.link.close();
if (back.id.text !== opts.product) throw fail("mismatch", `written, but the FM-1 reports ${back.id.text}`, back.id.text);
step("done", back.id.text);
}
return true;
}
}
+18
View File
@@ -24,3 +24,21 @@ export function logicalImage(fwsc) {
out.set(fwsc.subarray(BLOCKS * BLK), BLOCKS * KEEP);
return out;
}
// The official FM-1 V15 (M-VAVE Downloads -> PC Firmware -> FM-1 V15, FM-1.fwsc), for the return to the
// official firmware: only that exact file is accepted (its SHA-256 pins every byte: the loader, the app, the
// layout; the name of the file proves nothing). The digest is the one Felucca 1.0 pins.
export const STOCK_V15_SHA256 = "db1642b2b6fa5c2cccb11ffd13878068bb28601678d3644049f99dc40e7edb8a";
export const STOCK_V15_SIZE = 699956;
export const STOCK_V15_PRODUCT = "FM-1_015";
export async function sha256hex(bytes) {
const d = await crypto.subtle.digest("SHA-256", bytes);
return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, "0")).join("");
}
export async function validateStockPackage(bytes) {
if (bytes.length !== STOCK_V15_SIZE || await sha256hex(bytes) !== STOCK_V15_SHA256 || productOf(bytes) !== STOCK_V15_PRODUCT)
throw new Error("select the unmodified official FM-1 V15 file (FM-1.fwsc)");
return { product: STOCK_V15_PRODUCT, image: logicalImage(bytes) };
}
+98 -27
View File
@@ -42,6 +42,10 @@
pre { color: var(--dim); font-size: 11px; white-space: pre-wrap; margin-top: 12px; max-height: 160px; overflow: auto; }
hr { border: 0; border-top: 1px solid var(--line); margin: 28px 0 18px; }
.ed { display: inline-block; margin: 8px 0 0; padding: 10px 14px; background: var(--tile); text-decoration: none; }
details { margin: 22px 0 0; } summary { cursor: pointer; font-weight: 600; }
button#stock-go { font: 600 14px/1 inherit; font-family: inherit; background: var(--tile); color: var(--fg); border: 1px solid var(--line);
padding: 12px 16px; cursor: pointer; }
button#stock-go:disabled { color: var(--dim); cursor: default; }
@media (max-width: 420px) { .tiles { grid-template-columns: repeat(2, 1fr); } .logo svg { width: 170px; } }
</style>
</head>
@@ -50,11 +54,12 @@
<div class="top"><div class="logo"><!--LOGO--></div><button class="lang" id="lang"></button></div>
<div class="strip"><i></i><i></i><i></i><i></i></div>
<!--STUDIO_GUIDE-->
<!--BANNER-->
<h1>Firmware for the M-VAVE FM-1</h1>
<p class="lead">A groovebox you play live: four tracks — three synths and a drum machine — 9 synth engines, 54 sounds, 34 drum kits from 808 to techno, afro and ambient, your own samples, 16 punch-in effects. House, techno, hip-hop, drum &amp; bass, synthwave, lo-fi, ambient: make what you want. No factory patterns, nothing to load: everything you hear, you play.</p>
<p class="lead">A groovebox you play live: four tracks — three synths and a drum machine — 9 synth engines, 68 sounds, 37 drum kits from 808 to techno, amapiano and ambient, your own samples, 16 punch-in effects. House, techno, hip-hop, drum &amp; bass, synthwave, lo-fi, ambient: make what you want. No factory patterns, nothing to load: everything you hear, you play.</p>
<div class="tiles">
<div class="tile" style="--c: var(--blue)"><b>54</b><span>sounds, 9 engines, your samples</span></div>
<div class="tile" style="--c: var(--green)"><b>34</b><span>drum kits, 909 to afro</span></div>
<div class="tile" style="--c: var(--blue)"><b>68</b><span>sounds, 9 engines, your samples</span></div>
<div class="tile" style="--c: var(--green)"><b>37</b><span>drum kits, 909 to afro</span></div>
<div class="tile" style="--c: var(--yellow)"><b>16</b><span>punch-in fx: hold fx + key</span></div>
<div class="tile" style="--c: var(--orange)"><b>rec</b><span>no click: the loop follows you</span></div>
</div>
@@ -70,8 +75,17 @@
<p class="small" data-t="beta"></p>
<p class="small"><span data-t="brick"></span>
<a href="https://github.com/kurogedelic/FM-1-transporter" target="_blank" rel="noopener">FM-1-transporter</a></p>
<p class="small" data-t="back"></p>
<p class="small"><a href="https://www.m-vave.com/download" target="_blank" rel="noopener">www.m-vave.com/download</a></p>
<details>
<summary data-t="stockTitle"></summary>
<p class="small" data-t="stockHelp"></p>
<p class="small"><a href="https://www.m-vave.com/download" target="_blank" rel="noopener">www.m-vave.com/download</a></p>
<p class="small" data-t="stockBackup"></p>
<p><a class="ed" href="../editor/" data-t="stockEditor"></a></p>
<p class="small"><label><input id="stock-saved" type="checkbox"> <span data-t="stockSaved"></span></label></p>
<p class="small"><label><span data-t="stockFile"></span><br><input id="stock-file" type="file" accept=".fwsc"></label></p>
<p><button id="stock-go" disabled data-t="stockGo"></button></p>
<p class="small" data-t="back"></p>
</details>
<p class="small">SLOOP is based on Felucca by Leo Kuroshita (@kurogedelic), <a href="https://hugelton.com" target="_blank" rel="noopener">Hügelton Instruments</a>.
Hold OCT− alone while switching on for USB rescue.<br>
Font: Terminus (Dimitar Toshkov Zhekov, SIL OFL 1.1). Samples: Versilian Studios VSCO-2 Community Edition and VCSL (CC0 1.0), and the Hügelton Sample Pack (© Hügelton Instruments, not CC0).<br>
@@ -106,6 +120,15 @@ const TEXT = {
badpkg: "インストールするファイルが壊れています。ページを再読み込みしてください。",
leave: "書き込み中です。ページを閉じないでください。",
license: "GPL-3.0、無保証。ソース:",
stockTitle: "公式ファームウェア(V15)に戻す",
stockHelp: "M-VAVE のサイトから公式の FM-1 V15 をダウンロードし、中の FM-1.fwsc(変更していないもの)を選んでください。ファイルはこのブラウザの中で確認され、どこにも送られません。",
stockBackup: "公式ファームウェアは SLOOP の曲・プロジェクト・サンプルを開けません。先にエディタでバックアップを保存してください(Projects → Backup)。SLOOP を入れ直せば、エディタから復元できます。",
stockEditor: "エディタを開いてバックアップする", stockSaved: "バックアップをパソコンに保存しました",
stockFile: "公式の FM-1.fwsc", stockGo: "公式 V15 をインストール",
stockValid: "公式 V15 を確認しました", stockBad: "公式 V15 ではありません: ",
stockConfirm: "FM-1 に公式 V15 をインストールします。SLOOP の曲は公式ファームウェアでは開けません。バックアップは保存しましたか?",
stockFinish: "FM-1 は SLOOP の書き込みモードです。先に「インストール」で SLOOP の書き込みを終えてから、公式 V15 に戻してください。",
back: "M-VAVE のアップデーター M-UPGRADE(Downloads → PC Software)でも戻せます。FM-1 が見つからない場合は、MIDI を使う他のアプリとブラウザのタブを閉じてください。",
},
en: {
intro: "Connect the FM-1 by USB. (Works in Chrome or Edge.)",
@@ -131,6 +154,15 @@ const TEXT = {
badpkg: "The file to install is damaged. Reload the page.",
leave: "Writing. Do not close the page.",
license: "GPL-3.0, no warranty. Source:",
stockTitle: "Return to the official firmware (V15)",
stockHelp: "Download the official FM-1 V15 from M-VAVE and select the FM-1.fwsc inside it, unmodified. The file is checked in this browser; it is not sent anywhere.",
stockBackup: "The official firmware cannot open SLOOP's music, projects or samples. Save a backup with the editor first (Projects → Backup); reinstall SLOOP and restore it from the editor whenever you want them back.",
stockEditor: "Open the editor to back up", stockSaved: "I saved a backup on this computer",
stockFile: "The official FM-1.fwsc", stockGo: "Install the official V15",
stockValid: "Official V15 verified", stockBad: "Not the official V15: ",
stockConfirm: "Install the official V15 on the FM-1? The official firmware cannot open SLOOP's music. Did you save a backup?",
stockFinish: "The FM-1 is in SLOOP's update mode. Press Install to finish the SLOOP update first, then return to the official V15.",
back: "M-VAVE's own updater, M-UPGRADE (Downloads → PC Software), works too. If it does not find the FM-1, close every other app and browser tab that uses MIDI.",
},
};
let lang = (navigator.language || "en").toLowerCase().startsWith("ja") ? "ja" : "en";
@@ -150,7 +182,13 @@ const log = (t) => { $("log").textContent += t + "\n"; };
let image = null;
const meta = /*META*/;
let writing = false;
let writing = false, stock = null;
const lockAll = (on) => {
writing = on;
$("go").disabled = on || !image;
$("stock-go").disabled = on || !stock || !$("stock-saved").checked;
$("stock-file").disabled = on;
};
window.addEventListener("beforeunload", (e) => { if (writing) { e.preventDefault(); e.returnValue = t("leave"); } });
(async () => {
@@ -166,28 +204,34 @@ window.addEventListener("beforeunload", (e) => { if (writing) { e.preventDefault
}
image = logicalImage(pkg);
say(`SLOOP ${meta.version}`);
$("go").disabled = false;
lockAll(writing);
} catch (e) { sayK("loadfail", e.message); }
})();
const total = 74 + 1179; /* reads: step 1, step 2 (head + app area, SLOOP 2.0 loader) */
const step = (k, a) => {
log(`${k} ${a ?? ""}`);
if (k === "start") sayK("start");
if (k === "verify") { sayK("verify"); $("bar").value = Math.min(100, (a / total) * 100); }
if (k === "loader") sayK("loader");
if (k === "write") { sayK("write"); $("bar").value = Math.min(100, ((74 + a) / total) * 100); }
if (k === "reboot") sayK("reboot");
if (k === "done") { $("bar").value = 100; sayK("done"); }
};
const failed = (e) => {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.detail || "");
else sayK("error", e && e.message);
log(String(e && e.stack || e));
};
$("go").addEventListener("click", async () => {
$("go").disabled = true;
if (writing) return;
lockAll(true);
let midi;
try { midi = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { sayK("denied"); $("go").disabled = false; return; }
writing = true;
catch (e) { sayK("denied"); lockAll(false); return; }
try {
const up = new Updater(midi, log);
const total = 74 + 1179; /* reads: step 1, step 2 (head + app area, SLOOP 2.0 loader) */
const step = (k, a) => {
log(`${k} ${a ?? ""}`);
if (k === "start") sayK("start");
if (k === "verify") { sayK("verify"); $("bar").value = (a / total) * 100; }
if (k === "loader") sayK("loader");
if (k === "write") { sayK("write"); $("bar").value = ((74 + a) / total) * 100; }
if (k === "reboot") sayK("reboot");
if (k === "done") { $("bar").value = 100; sayK("done"); }
};
const ota = await up.find((id) => /^ota-/i.test(id.model));
if (ota) {
ota.link.close();
@@ -195,13 +239,40 @@ $("go").addEventListener("click", async () => {
} else {
await up.install(image, meta.product, step);
}
} catch (e) {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.detail || "");
else sayK("error", e && e.message);
log(String(e && e.stack || e));
}
writing = false;
$("go").disabled = false;
} catch (e) { failed(e); }
lockAll(false);
});
/* back to the official V15 (after Felucca 1.0): only the exact official file, a backup first (the editor),
through the same update path as M-UPGRADE; a device left in the official updater's mode is finished */
$("stock-saved").addEventListener("change", () => lockAll(writing));
$("stock-file").addEventListener("change", async () => {
const f = $("stock-file").files[0];
stock = null;
lockAll(writing);
if (!f) return;
try { stock = await validateStockPackage(new Uint8Array(await f.arrayBuffer())); sayK("stockValid"); }
catch (e) { sayK("stockBad", e.message); }
lockAll(writing);
});
$("stock-go").addEventListener("click", async () => {
if (writing || !stock || !$("stock-saved").checked || !confirm(t("stockConfirm"))) return;
lockAll(true);
let midi;
try { midi = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { sayK("denied"); lockAll(false); return; }
try {
const up = new Updater(midi, log);
const ota = await up.find((id) => /^ota-/i.test(id.model));
if (ota) {
ota.link.close();
if (OUR_LOADER(ota.id)) sayK("stockFinish"); /* SLOOP's loader: finish SLOOP first (Install) */
else sayK((await up.resume(stock.image, step, { product: stock.product })) ? "done" : "stopped");
} else {
await up.install(stock.image, stock.product, step);
}
} catch (e) { failed(e); }
lockAll(false);
});
</script>
</body>
+8 -2
View File
@@ -9,7 +9,8 @@
webapp/editor/index.html editor.html (+ fukiai.ttf, FUKIAI-LICENSE.txt)
src/ not touched
web/make_site.py build/felucca-X.Y.fwsc X.Y OUT_DIR
web/make_site.py build/felucca-X.Y.fwsc X.Y OUT_DIR [--beta]
(--beta: web/beta_banner.html at the top of the installer: the beta channel, docs/beta)
The package identity (FM-1_9xx) is read from the package; the device reports it
after the install.
@@ -64,6 +65,11 @@ def main(pkg, version, out):
shutil.copy(guide, out / guide.name)
guide_link = '<p lang="fr"><a href="../../' + guide.name + '">Guide rapide illustré (PDF, 4 pages)</a></p>'
html = html.replace("<!--STUDIO_GUIDE-->", guide_link)
banner = ""
if "--beta" in sys.argv: # the beta channel (docs/beta): what it is, what it implies
notes = HERE / "beta_banner.html"
banner = notes.read_text(encoding="utf-8") if notes.exists() else "<p><b>BETA</b></p>"
html = html.replace("<!--BANNER-->", banner)
for old in list(fw.glob("felucca-*.fwsc")) + list(fw.glob("sloop-*.fwsc")): # one package: the current one
old.unlink()
(inst / "index.html").write_text(html, encoding="utf-8")
@@ -80,7 +86,7 @@ def main(pkg, version, out):
if __name__ == "__main__":
args = [a for a in sys.argv[1:] if a != "--studio-guide"]
args = [a for a in sys.argv[1:] if a not in ("--studio-guide", "--beta")]
if len(args) != 3:
sys.exit(__doc__)
main(*args)
+82 -4
View File
@@ -31,9 +31,10 @@ const html = readFileSync(join(HERE, "editor.html"), "utf8");
const proto = html.slice(html.indexOf("/*PROTO-BEGIN*/"), html.indexOf("/*PROTO-END*/"));
const E = vm.runInNewContext(proto + `
;({ frame, unframe, parse, req, Link, parseWav, resample, normalize, rootFromName, buildSlot, makeMockDevice, CMD, SMP,
CHOP, chopNovelty, chopHits, chopSnap, chopGrid, chopEqual, chopList, chopZones, wavFile, zipStore, crc32,
CHOP, chopNovelty, chopHits, chopSnap, chopGrid, chopEqual, chopList, chopPick, chopFit, chopZones, wavFile, zipStore, crc32,
UP, bank, capturePatch, auditionPatch, startWatch, libraryFile, readLibraryFile, paramKeys, patternFromSteps, stepsFromPattern, upName,
mixer, GM_DRUM, drumName, parseNotes, fmtValue, F, DRUM_LANES, LV_NAMES, emptyDrum })`,
mixer, GM_DRUM, drumName, parseNotes, fmtValue, F, DRUM_LANES, LV_NAMES, emptyDrum,
backupCapture, backupRestore, backupObjects, b64enc, b64dec })`,
{ setTimeout, clearTimeout, setInterval, clearInterval, console, TextEncoder });
async function editorMock() {
@@ -437,18 +438,57 @@ async function editorTrackParam() {
o.done();
}
/* ------------------------------------- editor v6: backup / restore --- */
async function editorBackup() {
const C = E.CMD;
const { rq, done } = attachMock({});
const info = E.parse[C.INFO](await rq(E.req.info()));
ok(info.proto === 6, "backup: INFO protocol v6");
const ec = readFileSync(join(HERE, "../firmware/src/editor.c"), "utf8");
ok(/ED_BK_IDS\[\] = \{0, 1, 2, 3, 4, 5, 6, 7, 32, 33, 34\}/.test(ec), "backup: the object ids == editor.c ED_BK_IDS");
await rq(E.req.upStore(3, "BACKUP ME"));
await rq(E.req.project(1, 2), { timeout: 4000, retries: 0 });
const s = Int16Array.from({ length: 3000 }, (_, i) => Math.round(8000 * Math.sin(i / 7)));
const { hdr, data } = E.buildSlot("test", [{ s, root: 60 }]);
await rq(E.req.smpBegin(1), { timeout: 1000, retries: 0 });
for (let off = 0; off < data.length; off += 256) await rq(E.req.smpWrite(1, E.SMP.DATA_OFF + off, data.subarray(off, off + 256)), { timeout: 1000 });
await rq(E.req.smpEnd(1, hdr), { timeout: 2000, retries: 0 });
const A = await E.backupCapture(rq, info);
const obj = (id) => A.objects.find((o) => o.id === id);
ok(A.format === "sloop-backup" && A.objects.map((o) => o.id).join() === "0,1,2,3,4,5,6,7,32,33,34" && obj(33).len > 512
&& obj(4).len > 0 && obj(3).len === 0 && obj(32).len === 0, "backup: LIST + GET: 11 objects (project in C, sample in USR2, B empty)");
await rq(E.req.upErase(3));
await rq(E.req.smpErase(1), { timeout: 2500, retries: 0 });
await rq(E.req.set(0, 3, 5));
await rq(E.req.project(1, 1), { timeout: 4000, retries: 0 });
await E.backupRestore(rq, JSON.parse(JSON.stringify(A))); /* as written to disk and read back */
const B = await E.backupCapture(rq, info);
ok(js(B.objects) === js(A.objects), "backup: restore -> the same bytes again (presets, projects, samples, settings)");
const bad = JSON.parse(JSON.stringify(A));
bad.objects[2].data = E.b64enc(E.b64dec(bad.objects[2].data).map((x, i) => i === 3 ? x ^ 1 : x));
let caught = "";
try { E.backupObjects(bad); } catch (e) { caught = e.code; }
ok(caught === "bkBad", "backup: a damaged file is refused before anything is written");
done();
const old = attachMock({ noBackup: true });
const oi = E.parse[C.INFO](await old.rq(E.req.info()));
ok(oi.proto === 5, "backup: firmware without it says protocol 5 (the editor hides backup)");
old.done();
}
/* ------------------------------------- editor v5 (SLOOP 2.0): lanes, levels, ratchets --- */
async function editorV5() {
const C = E.CMD;
const { m, rq, ev, done } = attachMock({ watchMs: 1000 });
const info = E.parse[C.INFO](await rq(E.req.info()));
ok(info.proto === 5 && /SLOOP/.test(info.version) && info.pcount === 58 && info.gcount === 32 && info.pe0 === 50, "v5: INFO ends with the protocol version 5");
ok(info.proto === 6 && /SLOOP/.test(info.version) && info.pcount === 58 && info.gcount === 32 && info.pe0 === 50, "v5/v6: INFO ends with the protocol version (6: backup)");
/* the firmware says the same: ED_DRUM_STEP is command 33, INFO sends 5, P_CHORD / the master globals as the mock has them */
const ec = readFileSync(join(HERE, "../firmware/src/editor.c"), "utf8"), pc = readFileSync(join(HERE, "../firmware/src/params.c"), "utf8");
const en = (/enum \{ ED_INFO = 1,([^}]*)\}/.exec(ec) || [])[1] || "";
const names = ["ED_INFO", ...en.replace(/\/\*[^*]*\*\//g, "").split(",").map((x) => x.trim()).filter(Boolean)];
ok(names.indexOf("ED_DRUM_STEP") + 1 === C.DRUM_STEP && names.indexOf("ED_TRACK_CHANGED") + 1 === C.TRACK_CHANGED
&& /ed_b\(5\);\s*\/\* v5: the protocol version/.test(ec), "v5: command numbers and INFO == editor.c");
&& names.indexOf("ED_BK_LIST") + 1 === C.BK_LIST && names.indexOf("ED_BK_PUT") + 1 === C.BK_PUT
&& /ed_b\(6\);\s*\/\* v6: the protocol version/.test(ec), "v5/v6: command numbers and INFO == editor.c");
const enumNames = (id) => (new RegExp(`${id}\\[\\] = \\{([^}]*)\\}`).exec(pc) || [])[1].split(",").map((x) => x.trim().replace(/"/g, ""));
const chord = E.parse[C.DESC](await rq(E.req.desc(0, 49)));
const gd = [];
@@ -636,6 +676,30 @@ function chopTests() {
z = zipfile.ZipFile(sys.argv[1]); assert z.testzip() is None
print(",".join(i.filename + ":" + str(i.file_size) for i in z.infolist()))`, zp).toString().trim();
ok(r === zones.slice(0, 3).map((z) => `BREAK/${z.fname}:${44 + z.s.length * 2}`).join(), "chop: ZIP of the WAVs (Python reads it)");
/* keep / leave out, own lengths, fit: a recording longer than a slot */
const opt = [null, { off: true }, { len: 30 }];
const kl = E.chopList([10, 50, 400], 1000, 100, opt);
ok(kl.map((c) => `${c.start}-${c.end}${c.off ? "x" : ""}/${c.full}`).join() === "10-50/50,50-150x/400,400-430/1000"
&& E.chopList([10, 400], 1000, 0, [{ len: 9999 }])[0].end === 400,
"chop: options (left out, own length over the max, never past the next marker)");
const kz = E.chopZones(x, E.chopList(hits, N, 0, [{}, { off: true }, {}, { off: true }]), 60, 0);
ok(kz.length === 6 && kz.map((z) => z.root).join() === "60,61,62,63,64,65" && kz[1].fname === "CHOP03_C#4.wav" && kz[2].fname === "CHOP05_D4.wav",
"chop: left-out chops: the kept ones on consecutive keys, files keep their numbers");
const L = R * 20, long = new Float64Array(L);
for (let i = 0; i < L; i++) long[i] = Math.sin(i * 0.05) * 0.5;
const marks = E.chopEqual(0, L, 40), room = E.SMP.MAX_DATA * 2;
const all = E.chopList(marks, L), pick = E.chopPick(all);
ok(pick.length === 16 && pick[15].i === 15 && E.chopPick(all, 1, 7)[0].i === 7, "chop: 40 chops: the first 16 kept go to the slot; mode 1 the selected");
const lo = E.chopList(marks, L, 0, marks.map((_, i) => ({ off: i % 4 !== 0 }))); /* keep 10 of 40 (each 0.5 s) */
ok(E.chopPick(lo).length === 10 && E.chopFit(E.chopPick(lo), room) === Infinity, "chop: 20 s recording, 10 chops kept: they fit");
const many = E.chopPick(E.chopList(marks, L, 0, marks.map((_, i) => ({ off: i >= 16 })))), Lf = E.chopFit(many, room - many.length);
const fitted = many.map((c) => ({ ...c, end: Math.min(c.end, c.start + Lf) }));
let built = null;
try { built = E.buildSlot("LONG", E.chopZones(long, fitted, 60, 0)); } catch (e) { built = null; }
ok(Lf < R * 0.5 && Lf > R * 0.4 && built && built.data.length <= E.SMP.MAX_DATA && built.hdr[6] === 16,
`chop: Fit to slot: 16 x 0.5 s cut to ${(Lf / R).toFixed(3)} s each, the slot builds`);
ok(E.chopFit([{ start: 0, end: 100 }, { start: 0, end: 300 }], 250) === 150, "chop: fit keeps short chops whole, cuts the long ones");
}
/* ------------------------------------------------------- packages: JS == Python --- */
@@ -746,6 +810,19 @@ async function updater() {
stock.boot("ota-FM-1_015", "FM-1 Update");
const e3 = await new Updater(stock.access).resume(image).then(() => null, (x) => x);
ok(e3 && e3.code === "foreign" && e3.detail === "ota-FM-1_015" && stock.served === 0, "fm1ota.js: another firmware's loader is never resumed ('foreign')");
const back = new FakeFM1(image, { finalIdentity: "FM-1_015" }); /* the return to the official V15, interrupted */
back.boot("ota-FM-1_015", "FM-1 Update");
const st = [];
const r4 = await new Updater(back.access).resume(image, (k) => st.push(k), { product: "FM-1_015" });
ok(r4 === true && back.bad === 0 && st.at(-1) === "done", "fm1ota.js: return to official: its own loader resumed, V15 checked when back");
const wrong = new FakeFM1(image, { finalIdentity: "FM-1_900" });
wrong.boot("ota-FM-1_015", "FM-1 Update");
const e5 = await new Updater(wrong.access).resume(image, null, { product: "FM-1_015" }).then(() => null, (x) => x);
ok(e5 && e5.code === "mismatch", "fm1ota.js: return to official: another firmware coming back is not 'done'");
const pk = await import(join(HERE, "fm1pkg.js"));
const notStock = new Uint8Array(pk.STOCK_V15_SIZE);
const e6 = await pk.validateStockPackage(notStock).then(() => null, (x) => x);
ok(e6 && /official FM-1 V15/.test(e6.message), "fm1pkg.js: only the exact official V15 is accepted (SHA-256)");
}
await editorMock();
@@ -755,6 +832,7 @@ await editorTracks();
await editorMixer();
await editorTrackParam();
await editorV5();
await editorBackup();
editorTabs();
editorIcons();
samplesMatch();