From 7a3e8296c6054d4618416ffb76f79abfb2ffc809 Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Mon, 19 Oct 2026 23:03:48 -0700 Subject: [PATCH 1/4] Platform options: USB audio, TRS, clock --- LICENSING.md | 23 +- README.md | 30 +- firmware.json | 7 +- platform/clock.c | 121 +++++++ platform/fm1.c | 118 +++++-- platform/fm1.h | 57 ++- platform/hal/fm1_uart.h | 60 ++++ platform/hal/fm1_usb.h | 4 +- platform/loader/loader.c | 1 - platform/src/midi_uart.c | 69 ++++ platform/src/uac_fir.h | 90 ----- platform/src/usb.c | 729 ++++++++------------------------------- platform/web.c | 28 +- src/main.c | 39 ++- tools/build.py | 12 +- web/app.js | 3 +- web/style.css | 9 + web/worklet.js | 2 +- 18 files changed, 658 insertions(+), 744 deletions(-) create mode 100644 platform/clock.c create mode 100644 platform/hal/fm1_uart.h create mode 100644 platform/src/midi_uart.c delete mode 100644 platform/src/uac_fir.h diff --git a/LICENSING.md b/LICENSING.md index de5e234..b2ea342 100644 --- a/LICENSING.md +++ b/LICENSING.md @@ -2,18 +2,23 @@ GPL-3.0-only (`LICENSE`), as Felucca, SLOOP and Dinghy. Whoever gets a firmware built from this gets its source too. -| What | Who | -| -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| What | Who | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `platform/hal/`, `platform/loader/`, `platform/src/`, `platform/crt0.S`, `platform/app.ld`, `tools/fm1pkg_make.py`, `tools/lz4blk.py`, `web/fm1ota.js`, `web/fm1pkg.js`, the FM-1 parts of `tools/build.py` | Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments ([Felucca](https://github.com/hugelton/Felucca)), with the changes of [SLOOP](https://github.com/isod89/sloop-fm1) (isod89), as [Dinghy](https://github.com/zvenson/dinghy) (zvenson) and [X0X](https://github.com/charlesvestal/fm1-x0x) (Charles Vestal) carry them | -| `platform/fm1.c` | Dinghy's `platform.c` (zvenson), rewired to `fm1.h` | -| `platform/fm1.h`, `platform/common.c`, `platform/web.c`, `web/` (the page, the emulator), `fm1`, `Dockerfile`, `src/main.c` | foma | +| `platform/fm1.c` | Dinghy's `platform.c` (zvenson), rewired to `fm1.h` | +| `platform/fm1.h`, `platform/common.c`, `platform/clock.c`, `platform/web.c`, `web/` (the page, the emulator), `fm1`, `Dockerfile`, `src/main.c` | foma | + +The USB audio from a computer in `platform/src/usb.c` (`FOMA_USB_AUDIO`) is ported from +[felucca-bsp](https://github.com/hugelton/felucca-bsp) (commit 5758857, MPL-2.0, by Leo Kuroshita), whose license lets +it be used under GPL-3.0; foma's version uses integer math. The TRS MIDI input (`platform/src/midi_uart.c`, +`platform/hal/fm1_uart.h`) is Felucca's. ## Third-party material -| What | Licence | Where | -| --------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------- | -| Terminus font (ter-u16n), rendered into `platform/gen/felucca_font.h` | SIL OFL 1.1 | `platform/gen/Terminus-LICENSE.txt` | -| `platform/sdk/uboot.boot`, `cfg_tool.bin`, `eq_cfg_hw.bin` from JieLi's AC79NN_SDK_V1.2.1 | Apache-2.0 | | -| JieLi's toolchain, downloaded into the Docker image | JieLi's | | +| What | Licence | Where | +| ----------------------------------------------------------------------------------------- | ----------- | ----------------------------------------------- | +| Terminus font (ter-u16n), rendered into `platform/gen/felucca_font.h` | SIL OFL 1.1 | `platform/gen/Terminus-LICENSE.txt` | +| `platform/sdk/uboot.boot`, `cfg_tool.bin`, `eq_cfg_hw.bin` from JieLi's AC79NN_SDK_V1.2.1 | Apache-2.0 | | +| JieLi's toolchain, downloaded into the Docker image | JieLi's | | "M-VAVE" and "FM-1" belong to their owners; "Felucca" and "Hügelton Instruments" to Hügelton Instruments. This project is not made or endorsed by them. diff --git a/README.md b/README.md index c1e4c18..b95672b 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ as you save, install it on the FM-1 from the same page. That pulls the toolchain image ([konsumer/foma-toolchain](https://hub.docker.com/r/konsumer/foma-toolchain)) the first time, then builds your firmware and serves a page with: - **Emulator**: your code, compiled to WebAssembly, on a virtual FM-1 panel: the screen, keys, buttons, knobs, LEDs, - sound, MIDI in/out (Web MIDI), settings, `print()` to a console. Save a file and it reloads; a compile error shows on - the page. + sound, MIDI in/out (Web MIDI), MIDI clock, settings, `print()` to a console. Save a file and it reloads; a compile + error shows on the page. - **Install**: puts your build (or any FM-1 `.fwsc`) on the FM-1 over USB, from Chrome or Edge. - **Rescue**: the USB rescue, finishing a cut-off install, going back to the official firmware. @@ -55,7 +55,26 @@ Everything you can call is in [platform/fm1.h](platform/fm1.h): keys (`key_press MIDI (`midi_read`, `midi_send`), `settings_load` / `settings_save`, `millis`, and sound helpers (`sine`, `note_inc`, `random32`). -Name, version and package identity: [firmware.json](firmware.json). +Name, version, package identity and build options: [firmware.json](firmware.json). + +### Build options + +Some parts of the platform are optional. They're all on unless `"options"` in `firmware.json` turns them off, and +turning one off takes its code and memory out of the firmware: + +| Option | What it adds | Costs | +| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | +| `usb_audio` | A computer or tablet can pick the FM-1 as a 44.1 kHz stereo output. `audio_in()` gives `audio()` that sound: play it, process it, record it. | 10 KiB RAM | +| `trs_midi` | MIDI in on the 3.5 mm TRS jack (a TRS-to-DIN adapter for most gear), through `midi_read()`, which says where each message came from. | <1 KiB | +| `midi_clock` | One MIDI clock for `audio()`: its own tempo or the clock coming in, sent out over USB if you like. `clock_events()` gives each block's ticks, start and stop at the frame they fall on. | 1 KiB RAM | + +```json +{ "name": "MY SYNTH", "version": "0.1", "identity": "FM-1_95", "options": { "usb_audio": false } } +``` + +In your code, `#if FOMA_USB_AUDIO` (and `FOMA_TRS_MIDI`, `FOMA_MIDI_CLOCK`) tells you what's in. The FM-1 has no MIDI +out on the TRS jack, and its Bluetooth radio has no open driver, so neither is an option. The emulator follows MIDI +clock from Web MIDI; it has no USB audio input (`audio_in()` gives 0). ## The rules of the chip @@ -66,7 +85,7 @@ The FM-1 runs a JieLi AC791N. The emulator is forgiving, the chip is not; the bu - **No 64-bit division**, no C library (`printf`, `malloc`, `sin`). 64-bit multiplication is fine. - **A division by zero does not trap** on the FM-1 (it gives a wrong value); in the emulator it crashes. Test divisors. - **`audio()` has 5.8 ms per 256 frames**, less in practice. No screen, no flash, no waiting in it. Share with `loop()` - through `volatile` variables, one writer each. + through `volatile` variables, one writer each. `midi_send` works from both. - **`loop()` should return within a few ms**: the USB, the updater and the watchdog run between passes. - **Draw only what changed**: sending a full screen takes ~80 ms. - **Save settings when silent**: a flash erase stops the sound for ~50 ms. Never in a loop: flash wears out. @@ -132,7 +151,8 @@ platform/fm1.h the API platform/fm1.c the FM-1 side (boot, rescue, updater, USB, panel, screen, audio) platform/web.c the emulator side (the same API, for WebAssembly) platform/common.c shared: drawing, fonts, sound helpers -platform/hal, src, loader, gen, sdk the Felucca platform, vendored unchanged +platform/clock.c shared: the MIDI clock (midi_clock) +platform/hal, src, loader, gen, sdk the Felucca platform, vendored (src/usb.c trimmed to MIDI and usb_audio) tools/build.py the build (in Docker), with the checks web/ the page: emulator, installer, rescue ``` diff --git a/firmware.json b/firmware.json index 6d3b39c..f1e6946 100644 --- a/firmware.json +++ b/firmware.json @@ -1,5 +1,10 @@ { "name": "FOMA", "version": "0.1", - "identity": "FM-1_95" + "identity": "FM-1_95", + "options": { + "usb_audio": true, + "trs_midi": true, + "midi_clock": true + } } diff --git a/platform/clock.c b/platform/clock.c new file mode 100644 index 0000000..699ef83 --- /dev/null +++ b/platform/clock.c @@ -0,0 +1,121 @@ +/* foma: one MIDI clock for the app, 24 ticks a beat (FOMA_MIDI_CLOCK). It runs at the app's tempo, or follows the + * clock coming in over MIDI; either way audio() gets each block's ticks, start, continue and stop at the frame they + * fall on, and the clock can go out over USB MIDI. + * + * The platform defines CLOCK_MUL (its time stamps to frames: 44100 * 2^32 / their rate), passes clock_in() the + * clock and transport messages that come in with when they came, and calls clock_block() before each audio(). + * Followed ticks are placed by when they came between the last block and this one: the sound is a block late, but + * steady. clock_in() runs where MIDI comes in (an ISR on the FM-1), clock_block() where audio() runs. */ +#include "fm1.h" +#ifndef RING_PUBLISH +#define RING_PUBLISH() __asm__ volatile("" :: \ + : "memory") +#endif + +#define CK_Q 64u +static struct { + uint32_t t; + uint8_t st, src; +} ck_q[CK_Q]; +static volatile uint32_t ck_w, ck_r; +static volatile uint8_t ck_from, ck_out, ck_req; /* the app's (loop) */ +static volatile uint32_t ck_bpm100 = 12000, ck_measured; +static clock_event_t ck_ev[CLOCK_EVENTS]; +static int ck_n; +static uint32_t ck_next_q8; /* its own tempo: frames to the next tick, Q8 */ +static uint32_t ck_t, ck_frames, ck_last, ck_q4; /* followed: the last block's time; a tick's length (frames, Q4) */ +static uint8_t ck_on; /* followed ticks are coming */ + +static int clock_in(uint32_t st, uint32_t src, uint32_t t) { + if (ck_w - ck_r < CK_Q) { + ck_q[ck_w % CK_Q].t = t; + ck_q[ck_w % CK_Q].st = (uint8_t)st; + ck_q[ck_w % CK_Q].src = (uint8_t)src; + RING_PUBLISH(); + ck_w++; + } + return 1; +} + +static void ck_add(uint32_t at, int what) { + static const uint8_t ST[5] = {0, 0xF8, 0xFA, 0xFB, 0xFC}; + if (ck_n < CLOCK_EVENTS) { + ck_ev[ck_n].at = (uint16_t)at; + ck_ev[ck_n].what = (uint8_t)what; + ck_n++; + } + if (ck_out) { + midi_send(ST[what], 0, 0); + } +} + +static void ck_tick(uint32_t at) { /* a followed tick: its length, smoothed (a pause is not one) */ + uint32_t f = ck_frames + at, d = f - ck_last; + ck_last = f; + if (ck_on && d < 44100u && (!ck_q4 || d << 4 < ck_q4 * 3u)) { + ck_q4 = ck_q4 ? (uint32_t)((int32_t)ck_q4 + ((int32_t)(d << 4) - (int32_t)ck_q4) / 4) : d << 4; + } + ck_on = 1; + ck_add(at, CLOCK_TICK); +} + +static void clock_block(uint32_t n, uint32_t t) { + uint32_t r = ck_r, from = ck_from; + ck_n = 0; + if (from) { + while (r != ck_w) { + RING_PUBLISH(); + uint32_t st = ck_q[r % CK_Q].st, src = ck_q[r % CK_Q].src; + int32_t dt = (int32_t)(ck_q[r % CK_Q].t - ck_t); + uint32_t at = dt <= 0 ? 0 : (uint32_t)(((uint64_t)(uint32_t)dt * CLOCK_MUL) >> 32); + r++; + if (!(src & from)) { + continue; + } + at = at >= n ? n - 1 : at; + if (st == 0xF8) { + ck_tick(at); + } else { + ck_add(at, st == 0xFA ? CLOCK_START : st == 0xFB ? CLOCK_CONTINUE + : CLOCK_STOP); + } + } + if (ck_frames + n - ck_last > 44100u) { /* none for 1 s */ + ck_q4 = 0; + ck_on = 0; + } + ck_measured = ck_q4 ? 176400000u / ck_q4 : 0; /* 44100 * 60 / 24 * 100, Q4 */ + } else { + uint32_t req = ck_req, bpm = ck_bpm100 < 100u ? 100u : ck_bpm100, len = 2822400000u / bpm; /* 44100 * 60 / 24 * 100, Q8 */ + r = ck_w; /* (what came in is not followed) */ + ck_req = 0; + ck_on = 0; + if (req) { + ck_add(0, (int)req); + if (req != CLOCK_STOP) { + ck_next_q8 = 0; /* a tick on the start */ + } + } + while ((ck_next_q8 >> 8) < n) { + ck_add(ck_next_q8 >> 8, CLOCK_TICK); + ck_next_q8 += len; + } + ck_next_q8 -= n << 8; + } + RING_PUBLISH(); + ck_r = r; + ck_t = t; + ck_frames += n; +} + +void clock_follow(int from) { ck_from = (uint8_t)(from & MIDI_ANY); } +void clock_send(int on) { ck_out = (uint8_t) !!on; } +void clock_tempo(uint32_t bpm100) { ck_bpm100 = bpm100; } +void clock_start(void) { ck_req = CLOCK_START; } +void clock_continue(void) { ck_req = CLOCK_CONTINUE; } +void clock_stop(void) { ck_req = CLOCK_STOP; } +int clock_events(const clock_event_t **ev) { + *ev = ck_ev; + return ck_n; +} +uint32_t clock_bpm(void) { return ck_from ? ck_measured : ck_bpm100; } diff --git a/platform/fm1.c b/platform/fm1.c index e1c797e..dfa3753 100644 --- a/platform/fm1.c +++ b/platform/fm1.c @@ -47,13 +47,21 @@ static volatile uint32_t fm1_ms; /* milliseconds since power-on (TIMER5) */ #define HALF_FRAMES 256u /* I2S half buffer: 5.8 ms */ #define HALF_WORDS (HALF_FRAMES * 2u) #define FELUCCA_OTA 1 -#define FELUCCA_CDC 0 -#define FELUCCA_UAC 1 +#if FOMA_MIDI_CLOCK +#define CLOCK_MUL ((uint64_t)44100u * 4294967296u / (1000000u * FM1_TICKS_PER_US)) /* TIMER4 ticks -> frames */ +#include "clock.c" +#define MIDI_RT(status, source) clock_in(status, source, fm1_ticks()) /* clock and transport: the helper's */ +#endif #include "usb.c" +#if FOMA_TRS_MIDI +#include "midi_uart.c" +#endif -/* ---- flash: read anywhere; erase / program only the update's staging area and the settings sector */ +/* ---- flash: read anywhere; erase / program only the update's staging area and the settings sectors + * (Felucca's globals, 0xFC000..0xFF000: below them are the update records, above the MAC key) */ #define SETTINGS_AT 0x000FC000u -#define FL_RANGE_OK(off, n) (FL_IN(off, n, FL_OTA_LO, FL_OTA_HI) || FL_IN(off, n, SETTINGS_AT, SETTINGS_AT + 0x1000u)) +#define SETTINGS_END 0x000FF000u +#define FL_RANGE_OK(off, n) (FL_IN(off, n, FL_OTA_LO, FL_OTA_HI) || FL_IN(off, n, SETTINGS_AT, SETTINGS_END)) #include "fm1_flash.h" static uint8_t flash_ok; static int st_read(uint32_t off, void *dst, uint32_t n) { @@ -135,49 +143,56 @@ static void screen_flush(void) { fb_y1 = 0; } -/* ---- settings: [magic][length][crc32] then the bytes, in one 4 KiB sector */ +/* ---- settings: [magic][length][crc32] then the bytes, across up to three 4 KiB sectors */ #define SETTINGS_MAGIC 0x414D4F46u /* "FOMA" */ -static uint32_t crc32(const uint8_t *p, uint32_t n) { - uint32_t c = 0xFFFFFFFFu, k; +_Static_assert(SETTINGS_MAX + 12u <= SETTINGS_END - SETTINGS_AT, "the settings must fit their sectors"); +static uint32_t crc32(uint32_t c, const uint8_t *p, uint32_t n) { + uint32_t k; while (n--) { c ^= *p++; for (k = 0; k < 8u; k++) { c = c & 1u ? (c >> 1) ^ 0xEDB88320u : c >> 1; } } - return ~c; + return c; } int settings_load(void *p, uint32_t n) { - static uint8_t buf[256]; - uint32_t h[3]; - if (!flash_ok || n > sizeof buf || st_read(SETTINGS_AT, h, sizeof h) || h[0] != SETTINGS_MAGIC || h[1] != n) { + uint8_t buf[256]; /* the flash driver wants RAM */ + uint32_t h[3], c = 0xFFFFFFFFu; + if (!flash_ok || n > SETTINGS_MAX || st_read(SETTINGS_AT, h, sizeof h) || h[0] != SETTINGS_MAGIC || h[1] != n) { return -1; } - if (st_read(SETTINGS_AT + sizeof h, buf, n) || crc32(buf, n) != h[2]) { + for (uint32_t at = 0; at < n; at += sizeof buf) { /* check it all before p is touched */ + uint32_t k = n - at < sizeof buf ? n - at : sizeof buf; + if (st_read(SETTINGS_AT + sizeof h + at, buf, k)) { + return -1; + } + c = crc32(c, buf, k); + } + if (~c != h[2]) { return -1; } - memcpy(p, buf, n); - return 0; + return st_read(SETTINGS_AT + sizeof h, p, n) ? -1 : 0; } -int settings_save(const void *p, uint32_t n) { - static uint8_t buf[256]; /* the flash driver wants RAM */ +int settings_save(const void *p, uint32_t n) { /* p is in RAM (the flash driver wants it) */ uint32_t h[3] = {SETTINGS_MAGIC, n, 0}, took; int rc; - if (!flash_ok || n > sizeof buf) { + if (!flash_ok || n > SETTINGS_MAX) { return -1; } - memcpy(buf, p, n); - h[2] = crc32(buf, n); - if ((rc = fl_erase4k(SETTINGS_AT, &took)) != 0) { - return rc; + h[2] = ~crc32(0xFFFFFFFFu, p, n); + for (uint32_t at = SETTINGS_AT; at < SETTINGS_AT + sizeof h + n; at += 0x1000u) { /* only the sectors it needs */ + if ((rc = fl_erase4k(at, &took)) != 0) { + return rc; + } } - if ((rc = fl_write(SETTINGS_AT + sizeof h, buf, n)) != 0) { + if ((rc = fl_write(SETTINGS_AT + sizeof h, p, n)) != 0) { return rc; } return fl_write(SETTINGS_AT, (const uint8_t *)h, sizeof h); /* the header last: a cut save stays invalid */ } -/* ---- MIDI over USB: 4-byte USB-MIDI packets, cable 0 */ +/* ---- MIDI in from USB (cable 0) and the TRS jack (cable 1); out over USB, from loop() or audio() */ int midi_read(uint8_t *status, uint8_t *d1, uint8_t *d2) { uint32_t pk; if (mi_r == mi_w) { @@ -188,11 +203,12 @@ int midi_read(uint8_t *status, uint8_t *d1, uint8_t *d2) { *status = (uint8_t)(pk >> 8); *d1 = (uint8_t)(pk >> 16); *d2 = (uint8_t)(pk >> 24); - return 1; + return pk & 0x10u ? MIDI_TRS : MIDI_USB; } void midi_send(uint8_t status, uint8_t d1, uint8_t d2) { - uint32_t st = status; + uint32_t st = status, f = irq_save(); /* (loop() and audio() may both send) */ midi_out_event((st >> 4) | st << 8 | (uint32_t)(d1 & 0x7Fu) << 16 | (uint32_t)(d2 & 0x7Fu) << 24); + irq_restore(f); } /* ---- time */ @@ -234,6 +250,26 @@ void led_button(int b, int on) { fm1_led_key((uint32_t)b, on); } } +void led_backlight(int level) { + static const uint16_t NS[3] = {0, 1000, 4000}; /* the pulse a frame; a lit LED is ~95 us */ + static int8_t was = -1; + level = level < 0 ? 0 : level > 2 ? 2 + : level; + if (level == was) { + return; + } + if (was < 0) { /* once: every LED behind a key or button */ + for (uint32_t p = 0; p < FM1_NCOL; p++) { + for (uint32_t r = 1; r < 5u; r++) { + if (FM1_KEYMAP[r][p] >= 0) { + fm1_led_bg[p] |= (uint8_t)(1u << r); + } + } + } + } + was = (int8_t)level; + fm1_led_bg_ns = NS[level]; +} void print(const char *s) { (void)s; } /* ---- the timer: 10 kHz key scan, milliseconds, USB at 2 kHz. It outranks the audio ISR; nested in a @@ -256,14 +292,22 @@ void fm1_timer5_irq(void) { if (++sub == 10u) { sub = 0; } - if (in_audio) { + if (in_audio) { /* (the audio from the host keeps coming, and a clock on the TRS jack keeps its time) */ +#if FOMA_USB_AUDIO if (usb_due) { - uac_service(); + uo_service(); } +#endif +#if FOMA_TRS_MIDI + uart_midi_poll(); +#endif return; } if (owed) { usb_poll(); +#if FOMA_TRS_MIDI + uart_midi_poll(); +#endif } owed = 0; } @@ -272,6 +316,11 @@ extern void isr_timer5(void); /* ---- the sound: ALNK0 I2S, two halves; the app renders, MASTER scales, Q15 -> 24 bit (-6 dBFS ceiling) */ static int32_t abuf[2u * HALF_WORDS] __attribute__((aligned(4))); static volatile int32_t master_q12 = 2048; +#if FOMA_USB_AUDIO +static int32_t ain[HALF_WORDS]; /* this block of the host's audio (audio_in) */ +static int ain_on; +const int32_t *audio_in(void) { return ain_on ? ain : 0; } +#endif void fm1_alnk0_irq(void) { /* via isr_alnk0 (hal/fm1_isr.S) */ uint8_t p; @@ -280,20 +329,22 @@ void fm1_alnk0_irq(void) { /* via isr_alnk0 (hal/fm1_isr.S) */ fm1_audio_ack_aux(p); if (p & FM1_AUDIO_HALF) { int32_t *o = &abuf[fm1_audio_free_half() * HALF_WORDS]; - uint32_t i, b; + uint32_t i; for (i = 0; i < HALF_WORDS; i++) { o[i] = 0; } - uac_render_start(); +#if FOMA_USB_AUDIO + ain_on = usb_audio_take(ain, HALF_FRAMES); +#endif +#if FOMA_MIDI_CLOCK + clock_block(HALF_FRAMES, fm1_ticks()); +#endif audio(o, HALF_FRAMES); for (i = 0; i < HALF_WORDS; i++) { int32_t v = (o[i] * master_q12) >> 12; o[i] = v > 32767 ? 32767 : v < -32767 ? -32767 : v; } - for (b = 0; b < HALF_FRAMES; b += 32u) { - uac_tap(o + 2u * b, 32u); /* the computer records what the speaker plays */ - } for (i = 0; i < HALF_WORDS; i++) { o[i] <<= 7; } @@ -401,6 +452,9 @@ void fm1_cstart(void) { fm1_adc_init(); fm1_audio_init(abuf, HALF_WORDS, isr_alnk0, 3); /* (abuf is zero: .bss) */ usb_start(); +#if FOMA_TRS_MIDI + uart_midi_init(); +#endif fm1_timer5_start(isr_timer5, 4); fm1_guard_lock_top(); fm1_irq_enable_all(); diff --git a/platform/fm1.h b/platform/fm1.h index ecacb7e..888742b 100644 --- a/platform/fm1.h +++ b/platform/fm1.h @@ -11,6 +11,18 @@ #define FM1_H #include +/* ---- build options: firmware.json "options" turns them on or off (all on unless it says otherwise). What an + * option adds is only there when it is on: using it otherwise fails the build */ +#ifndef FOMA_USB_AUDIO +#define FOMA_USB_AUDIO 1 /* usb_audio: a computer or tablet plays into the FM-1 over USB: audio_in() */ +#endif +#ifndef FOMA_TRS_MIDI +#define FOMA_TRS_MIDI 1 /* trs_midi: MIDI in on the 3.5 mm jack too, through midi_read() */ +#endif +#ifndef FOMA_MIDI_CLOCK +#define FOMA_MIDI_CLOCK 1 /* midi_clock: one MIDI clock for audio(), its own or followed: clock_*() */ +#endif + void setup(void); void loop(void); void audio(int32_t *out, uint32_t frames); @@ -68,6 +80,7 @@ uint32_t master_knob(void); /* the MASTER knob 0..1023; it is also the volume */ /* ---- LEDs */ void led_key(int k, int on); void led_button(int b, int on); +void led_backlight(int level); /* every key and button glows dimly: 0 off, 1 low, 2 full */ /* ---- screen: 240 x 240, RGB565. Draw anywhere, any time in loop(); what changed is sent * after loop() returns. Sending is ~0.3 ms per row: draw only what changed. */ @@ -87,12 +100,50 @@ int text(int x, int y, const char *s, uint16_t color, int font); /* returns the int text_width(const char *s, int font); int text_height(int font); -/* ---- MIDI over USB (any channel; SysEx belongs to the updater) */ -int midi_read(uint8_t *status, uint8_t *d1, uint8_t *d2); /* 1: got one */ +/* ---- MIDI in over USB (and the TRS jack: trs_midi), out over USB (any channel; SysEx belongs to the updater). + * midi_read gives channel messages, and clock / start / continue / stop (0xF8 0xFA 0xFB 0xFC) unless the clock + * helper (midi_clock) takes them. midi_send works from loop() and audio() */ +enum { MIDI_USB = 1, + MIDI_TRS = 2, + MIDI_ANY = 3 }; +int midi_read(uint8_t *status, uint8_t *d1, uint8_t *d2); /* 0: none; else where it came from: MIDI_USB or MIDI_TRS */ void midi_send(uint8_t status, uint8_t d1, uint8_t d2); -/* ---- settings: up to 256 bytes that survive power-off. Saving stalls the sound for ~50 ms: +#if FOMA_MIDI_CLOCK +/* ---- MIDI clock (midi_clock): one clock for the app, 24 ticks a beat. It runs at clock_tempo(), or follows the + * clock coming in (clock_follow); either way, in audio(), clock_events() gives this block's ticks and start / + * continue / stop, in order, each at the frame it falls on. Count ticks to keep time: a 16th note is 6. + * clock_send(1) sends it out over USB MIDI too (a followed clock is passed on). Set it up from loop() */ +enum { CLOCK_TICK = 1, + CLOCK_START, + CLOCK_CONTINUE, + CLOCK_STOP }; +typedef struct { + uint16_t at; /* the frame in this block */ + uint8_t what; /* CLOCK_* */ +} clock_event_t; +#define CLOCK_EVENTS 32 /* at most this many a block */ +void clock_follow(int from); /* 0: its own tempo; MIDI_USB, MIDI_TRS or MIDI_ANY: the clock coming in */ +void clock_send(int on); /* 1: send it over USB MIDI */ +void clock_tempo(uint32_t bpm100); /* its own tempo, BPM x 100 (12000: 120 BPM) */ +void clock_start(void); /* its own start, continue, stop (followed: the other device's) */ +void clock_continue(void); +void clock_stop(void); +int clock_events(const clock_event_t **ev); /* audio() only: this block's events; returns how many */ +uint32_t clock_bpm(void); /* BPM x 100: its tempo, or the followed clock's (0: none coming) */ +#endif + +#if FOMA_USB_AUDIO +/* ---- audio from a computer or tablet over USB (usb_audio): the FM-1 is a 44.1 kHz stereo output it can pick. + * In audio(): this block's frames, L R L R ..., +-32767 (process it, record it, add it to out), or 0 when nothing + * plays. The platform doesn't play it itself */ +const int32_t *audio_in(void); +#endif + +/* ---- settings: up to SETTINGS_MAX bytes that survive power-off (three 4 KiB flash sectors, less a header). Saving stalls the sound for + * ~50 ms a sector: * save when nothing plays, never in a loop (flash wears out) */ +#define SETTINGS_MAX 12276u int settings_load(void *p, uint32_t n); /* 0: loaded; else p is untouched */ int settings_save(const void *p, uint32_t n); diff --git a/platform/hal/fm1_uart.h b/platform/hal/fm1_uart.h new file mode 100644 index 0000000..2323e0f --- /dev/null +++ b/platform/hal/fm1_uart.h @@ -0,0 +1,60 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments */ +/* FM-1 UART1 as MIDI IN: PH8 -> input + * channel 1 -> UART1 RX, 31250 baud, RX DMA into a ring, polled (no IRQ). + * The MIDI parser is midi_uart.c. RX verified on hardware. + * + * 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 + */ +#pragma once +#include +#include "fm1_cc.h" + +#define FM1_UT1_CON0 (*(volatile uint32_t *)0x12100u) +#define FM1_UT1_CON1 (*(volatile uint32_t *)0x12104u) +#define FM1_UT1_BAUD (*(volatile uint32_t *)0x12108u) +#define FM1_UT1_OTCNT (*(volatile uint32_t *)0x12110u) +#define FM1_UT1_RXSADR (*(volatile uint32_t *)0x1211Cu) +#define FM1_UT1_RXEADR (*(volatile uint32_t *)0x12120u) +#define FM1_UT1_RXCNT (*(volatile uint32_t *)0x12124u) +#define FM1_UT1_HRXCNT (*(volatile uint32_t *)0x12128u) +#define FM1_UM_CLK_CON1 (*(volatile uint32_t *)0x10010u) /* [11:10] UART clock: 1 = PLL48M */ +#define FM1_UM_IOMAP2 (*(volatile uint32_t *)0x51024u) /* input ch1 source [13:8] */ +#define FM1_UM_IOMAP3 (*(volatile uint32_t *)0x51028u) /* UT1: b7 fixed IO, [6:4] RX select */ +#define FM1_UM_PH_DIR (*(volatile uint32_t *)0x501C8u) +#define FM1_UM_PH_DIE (*(volatile uint32_t *)0x501CCu) +#define FM1_UM_PH_PU (*(volatile uint32_t *)0x501D0u) +#define FM1_UM_PH_PD (*(volatile uint32_t *)0x501D4u) + +FM1_INLINE void fm1_uart1_midi_init(volatile uint8_t *ring, uint32_t len) +{ + FM1_UT1_CON0 = 0x3400u; /* off, pendings cleared */ + FM1_UT1_CON1 = 0; + FM1_UM_CLK_CON1 = (FM1_UM_CLK_CON1 & ~(3u << 10)) | (1u << 10); + FM1_UM_IOMAP3 &= ~0x80u; + FM1_UM_IOMAP3 = (FM1_UM_IOMAP3 & ~0x70u) | (5u << 4); /* UT1 RX = input ch 1 */ + FM1_UM_IOMAP2 = (FM1_UM_IOMAP2 & ~0x3F00u) | (49u << 8);/* ch 1 = PH8 */ + FM1_UM_PH_PD &= ~(1u << 8); + FM1_UM_PH_DIE |= 1u << 8; + FM1_UM_PH_DIR |= 1u << 8; + FM1_UM_PH_PU |= 1u << 8; + FM1_UT1_RXSADR = (uint32_t)(uintptr_t)ring; + FM1_UT1_RXEADR = (uint32_t)(uintptr_t)ring + len; + FM1_UT1_RXCNT = len; + FM1_UT1_BAUD = 48000000u / 31250u / 4u - 1u; /* 383 */ + FM1_UT1_OTCNT = 60000u; + __asm__ volatile("csync" ::: "memory"); + FM1_UT1_CON0 = 0x40u | 0x80u | 0x1000u | 0x400u; /* RXDMA, RDC, clear R/OT; no IEs */ + __asm__ volatile("csync" ::: "memory"); + FM1_UT1_CON0 |= 1u; /* UTEN last */ +} + +FM1_INLINE uint32_t fm1_uart1_rx_take(void) +{ + FM1_UT1_CON0 |= 0x80u; /* RDC: latch the count */ + __asm__ volatile("csync" ::: "memory"); + FM1_UT1_CON0 |= 0x1400u; /* clear RPND / OTPND */ + return FM1_UT1_HRXCNT & 0xFFFFu; +} diff --git a/platform/hal/fm1_usb.h b/platform/hal/fm1_usb.h index 392c768..b6ec770 100644 --- a/platform/hal/fm1_usb.h +++ b/platform/hal/fm1_usb.h @@ -12,7 +12,7 @@ * 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); + * EP4 (own slots): fm1_usb_ep4_txbuf, fm1_usb_ep4_send (csync first), fm1_usb_ep4_rxbuf; * 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 @@ -98,6 +98,8 @@ FM1_INLINE void fm1_usb_ep_send(uint32_t ep, void *p, uint32_t 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; } +/* EP4 OUT (the USB audio output, isochronous): its DMA address (SDK usb_set_dma_raddr, ep 4) (after felucca-bsp) */ +FM1_INLINE void fm1_usb_ep4_rxbuf(void *p) { FM1_USB_EP4_RADR = (uint32_t)(uintptr_t)p; } FM1_INLINE void fm1_usb_ep4_send(void *p, uint32_t n) { __asm__ volatile("csync" ::: "memory"); diff --git a/platform/loader/loader.c b/platform/loader/loader.c index ad1ffed..837a775 100644 --- a/platform/loader/loader.c +++ b/platform/loader/loader.c @@ -8,7 +8,6 @@ * Single compilation unit. */ #include #define FELUCCA_LOADER 1 -#define FELUCCA_CDC 0 #define FELUCCA_OTA 1 #define FELUCCA_OTA_DRYRUN 0 #define FELUCCA_USB_PID 0x0002 diff --git a/platform/src/midi_uart.c b/platform/src/midi_uart.c new file mode 100644 index 0000000..616660a --- /dev/null +++ b/platform/src/midi_uart.c @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments */ +/* MIDI IN on the TRS jack: PH8 -> input channel 1 -> UART1 RX, 31250 baud, RX DMA into a 128-byte ring, + * polled from the TIMER5 ISR (no UART IRQ), in the same place as usb_poll (it shares the MIDI ring). + * Channel messages go into midi_in_q next to USB's, as USB-MIDI packets on cable 1; clock / start / continue / + * stop to MIDI_RT (or the ring, as usb.c); other realtime, system common and SysEx are ignored (no SysEx->UBOOT + * from TRS). FOMA_TRS_MIDI=0 leaves it out. + * From Felucca's midi_uart.c. */ +#include "fm1_uart.h" + +#define UM_RING 128u +static volatile uint8_t um_ring[UM_RING] __attribute__((aligned(16))); +static struct { + uint32_t rd, pend; + uint8_t st, need, got, d0, sysex; +} um; + +static void uart_midi_init(void) { /* before TIMER5 starts: PORTH RMW */ + fm1_uart1_midi_init(um_ring, UM_RING); +} + +static void um_put(uint32_t pkt) { + if (mi_w - mi_r < MQ) { + midi_in_q[mi_w % MQ] = pkt | 0x10u; /* cable 1: TRS */ + RING_PUBLISH(); + mi_w++; + } +} + +static void um_byte(uint32_t b) { + if (b >= 0xF8u) { + if ((b == 0xF8u || b == 0xFAu || b == 0xFBu || b == 0xFCu) && !MIDI_RT(b, 2)) { + um_put(0xFu | b << 8); + } + return; /* realtime keeps running status */ + } + if (b & 0x80u) { + um.sysex = b == 0xF0u; + um.st = b < 0xF0u ? (uint8_t)b : 0; /* system common / SysEx cancel running status */ + um.need = (b & 0xE0u) == 0xC0u ? 1u : 2u; /* Cx Dx: 1 data byte, else 2 */ + um.got = 0; + return; + } + if (um.sysex || !um.st) { + return; + } + if (um.need == 2u && !um.got) { + um.d0 = (uint8_t)b; + um.got = 1; + return; + } + uint32_t d1 = um.need == 2u ? um.d0 : b, d2 = um.need == 2u ? b : 0u; + um.got = 0; + um_put((uint32_t)(um.st >> 4) | (uint32_t)um.st << 8 | d1 << 16 | d2 << 24); +} + +static void uart_midi_poll(void) { + um.pend += fm1_uart1_rx_take(); + if (um.pend > UM_RING) { /* lost bytes: wait for a whole new status */ + um.rd = (um.rd + um.pend - UM_RING) & (UM_RING - 1u); + um.pend = UM_RING; + um.st = um.got = um.sysex = 0; + } + while (um.pend) { + um_byte(um_ring[um.rd]); + um.rd = (um.rd + 1u) & (UM_RING - 1u); + um.pend--; + } +} diff --git a/platform/src/uac_fir.h b/platform/src/uac_fir.h deleted file mode 100644 index 7e86c6b..0000000 --- a/platform/src/uac_fir.h +++ /dev/null @@ -1,90 +0,0 @@ -/* SPDX-License-Identifier: GPL-3.0-only */ -/* generated by tools/gen_uac_fir.py: do not edit. The 44.1 -> 48 kHz polyphase FIR of the USB audio input - * (usb.c): L 160, M 147, 12 taps per phase, Kaiser beta 7.5, cut-off 20000 Hz, Q15; phases 0..79 - * (phase 159 - p = phase p backwards), taps oldest input first. After Felucca 1.1.5 (24 taps, Q30). */ -#define UAC_FIR_L 160u -#define UAC_FIR_M 147u -#define UAC_FIR_N 12u -#define UAC_FIR_Q 15 -static const int16_t UAC_FIR[80][12] = { - {98, -410, 1042, -1899, 2633, 29711, 2815, -1962, 1064, -417, 99, -6}, - {97, -404, 1020, -1836, 2453, 29708, 2998, -2025, 1086, -423, 101, -7}, - {95, -397, 997, -1773, 2275, 29702, 3183, -2088, 1108, -429, 102, -7}, - {94, -391, 975, -1710, 2099, 29692, 3370, -2151, 1130, -436, 103, -7}, - {93, -384, 952, -1648, 1924, 29678, 3559, -2214, 1152, -442, 105, -7}, - {91, -377, 930, -1585, 1752, 29661, 3749, -2277, 1173, -448, 106, -7}, - {90, -371, 907, -1523, 1581, 29642, 3941, -2339, 1194, -454, 107, -7}, - {88, -364, 884, -1461, 1413, 29619, 4135, -2402, 1216, -460, 108, -8}, - {87, -357, 862, -1399, 1246, 29591, 4330, -2465, 1237, -465, 109, -8}, - {85, -350, 839, -1337, 1081, 29562, 4526, -2527, 1258, -471, 110, -8}, - {84, -344, 816, -1275, 919, 29528, 4725, -2590, 1278, -477, 112, -8}, - {83, -337, 793, -1214, 758, 29490, 4925, -2652, 1299, -482, 113, -8}, - {81, -330, 770, -1153, 599, 29452, 5126, -2714, 1319, -488, 114, -8}, - {80, -323, 748, -1092, 443, 29406, 5328, -2775, 1339, -493, 115, -8}, - {78, -316, 725, -1032, 288, 29361, 5533, -2837, 1359, -498, 116, -9}, - {77, -309, 702, -972, 135, 29312, 5738, -2898, 1378, -503, 117, -9}, - {75, -302, 679, -912, -15, 29258, 5945, -2958, 1397, -508, 118, -9}, - {74, -295, 657, -853, -163, 29202, 6153, -3019, 1416, -513, 118, -9}, - {72, -288, 634, -794, -309, 29143, 6362, -3079, 1435, -518, 119, -9}, - {71, -281, 612, -735, -454, 29079, 6573, -3139, 1453, -522, 120, -9}, - {69, -274, 589, -677, -595, 29013, 6785, -3198, 1471, -527, 121, -9}, - {68, -267, 567, -619, -735, 28943, 6998, -3257, 1489, -531, 122, -10}, - {66, -260, 544, -562, -873, 28872, 7212, -3315, 1507, -535, 122, -10}, - {65, -253, 522, -505, -1008, 28794, 7428, -3373, 1524, -539, 123, -10}, - {63, -246, 500, -448, -1141, 28716, 7644, -3431, 1541, -543, 123, -10}, - {62, -239, 478, -393, -1273, 28634, 7862, -3487, 1557, -547, 124, -10}, - {60, -233, 456, -337, -1401, 28549, 8080, -3544, 1573, -550, 125, -10}, - {59, -226, 434, -282, -1528, 28461, 8299, -3600, 1589, -553, 125, -10}, - {57, -219, 412, -228, -1652, 28371, 8520, -3655, 1604, -557, 125, -10}, - {56, -212, 391, -174, -1774, 28274, 8741, -3709, 1619, -560, 126, -10}, - {55, -205, 369, -121, -1894, 28177, 8963, -3763, 1634, -563, 126, -10}, - {53, -198, 348, -68, -2012, 28076, 9186, -3816, 1648, -565, 126, -10}, - {52, -192, 327, -16, -2127, 27972, 9410, -3868, 1661, -568, 127, -10}, - {50, -185, 306, 36, -2241, 27867, 9634, -3920, 1675, -570, 127, -11}, - {49, -178, 285, 87, -2351, 27756, 9860, -3971, 1687, -572, 127, -11}, - {47, -172, 264, 137, -2460, 27646, 10085, -4021, 1700, -574, 127, -11}, - {46, -165, 244, 187, -2566, 27528, 10312, -4070, 1712, -576, 127, -11}, - {45, -159, 223, 236, -2671, 27413, 10539, -4119, 1723, -578, 127, -11}, - {43, -152, 203, 285, -2772, 27290, 10766, -4166, 1734, -579, 127, -11}, - {42, -146, 183, 333, -2872, 27167, 10995, -4213, 1744, -580, 126, -11}, - {41, -139, 163, 380, -2969, 27040, 11223, -4259, 1754, -581, 126, -11}, - {39, -133, 144, 427, -3064, 26909, 11452, -4303, 1764, -582, 126, -11}, - {38, -127, 124, 472, -3157, 26777, 11681, -4347, 1773, -582, 126, -10}, - {37, -120, 105, 518, -3247, 26641, 11911, -4390, 1781, -583, 125, -10}, - {35, -114, 86, 562, -3335, 26504, 12141, -4432, 1789, -583, 125, -10}, - {34, -108, 67, 606, -3421, 26364, 12371, -4472, 1796, -583, 124, -10}, - {33, -102, 49, 649, -3505, 26220, 12602, -4512, 1803, -582, 123, -10}, - {32, -96, 31, 691, -3586, 26075, 12832, -4551, 1809, -582, 123, -10}, - {30, -90, 13, 733, -3665, 25927, 13063, -4588, 1814, -581, 122, -10}, - {29, -84, -5, 774, -3742, 25776, 13294, -4624, 1819, -580, 121, -10}, - {28, -79, -23, 814, -3817, 25624, 13525, -4659, 1824, -579, 120, -10}, - {27, -73, -40, 853, -3889, 25468, 13755, -4693, 1828, -577, 119, -10}, - {26, -67, -57, 892, -3959, 25308, 13986, -4726, 1831, -575, 118, -9}, - {25, -62, -74, 930, -4027, 25148, 14217, -4757, 1833, -573, 117, -9}, - {23, -56, -91, 967, -4093, 24987, 14447, -4787, 1835, -571, 116, -9}, - {22, -51, -107, 1004, -4156, 24822, 14678, -4816, 1836, -569, 114, -9}, - {21, -45, -123, 1039, -4217, 24653, 14908, -4843, 1837, -566, 113, -9}, - {20, -40, -139, 1074, -4276, 24482, 15138, -4869, 1837, -563, 112, -8}, - {19, -35, -155, 1108, -4333, 24313, 15367, -4894, 1836, -560, 110, -8}, - {18, -30, -170, 1141, -4388, 24138, 15596, -4917, 1835, -556, 109, -8}, - {17, -25, -185, 1174, -4440, 23961, 15825, -4939, 1833, -552, 107, -8}, - {16, -20, -200, 1206, -4490, 23782, 16053, -4959, 1830, -548, 105, -7}, - {15, -15, -215, 1237, -4538, 23602, 16281, -4978, 1827, -544, 103, -7}, - {14, -10, -229, 1267, -4584, 23418, 16509, -4995, 1823, -539, 101, -7}, - {13, -5, -243, 1296, -4628, 23234, 16735, -5011, 1818, -534, 99, -6}, - {12, 0, -256, 1325, -4670, 23047, 16961, -5026, 1813, -529, 97, -6}, - {11, 4, -270, 1353, -4709, 22859, 17187, -5038, 1806, -524, 95, -6}, - {11, 9, -283, 1380, -4747, 22666, 17411, -5049, 1800, -518, 93, -5}, - {10, 13, -296, 1406, -4782, 22475, 17635, -5059, 1792, -512, 91, -5}, - {9, 17, -308, 1431, -4816, 22282, 17858, -5067, 1784, -506, 88, -4}, - {8, 22, -321, 1456, -4847, 22085, 18081, -5073, 1774, -499, 86, -4}, - {7, 26, -333, 1480, -4876, 21886, 18302, -5077, 1765, -492, 83, -3}, - {6, 30, -344, 1503, -4903, 21688, 18522, -5080, 1754, -485, 80, -3}, - {6, 34, -356, 1525, -4929, 21486, 18742, -5081, 1743, -478, 78, -2}, - {5, 38, -367, 1546, -4952, 21286, 18960, -5081, 1730, -470, 75, -2}, - {4, 41, -378, 1567, -4973, 21081, 19177, -5078, 1718, -462, 72, -1}, - {4, 45, -388, 1587, -4992, 20875, 19393, -5074, 1704, -454, 69, -1}, - {3, 49, -399, 1606, -5010, 20668, 19609, -5068, 1690, -446, 66, 0}, - {2, 52, -409, 1624, -5025, 20463, 19822, -5060, 1674, -437, 62, 0}, - {2, 56, -418, 1642, -5039, 20250, 20035, -5050, 1658, -428, 59, 1}, -}; diff --git a/platform/src/usb.c b/platform/src/usb.c index 0061db8..92fb3c9 100644 --- a/platform/src/usb.c +++ b/platform/src/usb.c @@ -3,35 +3,23 @@ /* USB full-speed device on USB0: a class-compliant USB-MIDI interface. * All SIE traffic happens in usb_poll(), called from the TIMER5 ISR at 2 kHz, * so INDEX is never shared and no USB IRQ is needed. MIDI in goes to a ring - * the audio ISR drains; MIDI out comes from a ring the audio ISR fills. + * loop() drains; MIDI out comes from a ring midi_send() fills. * 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. - * 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. - * SLOOP 2.5, after Felucca 1.1.5: FELUCCA_UAC_48K=1 (the default with FELUCCA_UAC) offers 48 kHz too, for - * phones and apps that only take 48 kHz: the host picks the rate with SET_CUR (two discrete rates in the one alt - * setting). The engines stay at 44.1 kHz; at 48 kHz uac_tap48 resamples (a polyphase FIR 160 / 147, uac_fir.h: - * 12 taps a phase, Q15, Felucca's 24 x Q30 made smaller) into the ring. 44.1 kHz, the rate until a host asks - * for another, sends the samples as before, bit for bit. */ + * Clock / start / continue / stop go to MIDI_RT(status, source) when the platform defines it (the clock helper), + * else into the ring like the rest. + * FOMA_USB_AUDIO=1, after felucca-bsp (5758857, MPL-2.0, same author): a USB audio output, so a computer or a + * tablet plays into the FM-1 (16-bit stereo, 44.1 kHz, EP4 OUT isochronous adaptive). uo_service takes each packet + * into a ring (TIMER5, nested in the render too); usb_audio_take, once a render, gives the app a block of it, + * resampled to the I2S clock (~44,117.6 Hz) by linear interpolation, the read rate steered by the ring's fill so + * it neither runs dry nor overflows. Integers only here (felucca-bsp's uses floats). The update loader leaves it + * off: MIDI only. (foma: Felucca's USB audio input to the computer, its 48 kHz option and the CDC console are gone.) */ #include "../hal/fm1_usb.h" /* registers; relative, so the loader and the host tests find it too */ -#ifndef FELUCCA_CDC -#define FELUCCA_CDC 0 +#ifndef FOMA_USB_AUDIO +#define FOMA_USB_AUDIO 0 #endif -#ifndef FELUCCA_UAC -#define FELUCCA_UAC 0 -#endif -#ifndef FELUCCA_UAC_48K -#define FELUCCA_UAC_48K 1 -#endif -#if !FELUCCA_UAC -#undef FELUCCA_UAC_48K -#define FELUCCA_UAC_48K 0 +#ifndef MIDI_RT +#define MIDI_RT(status, source) 0 /* 0: not taken, into the ring */ #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, @@ -42,86 +30,25 @@ enum { S_FADDR = 0, S_POWER = 1, S_INTRTX1 = 2, S_INTRTX2 = 3, S_INTRRX1 = 4, S_ static uint8_t ep0buf[64 + 4] __attribute__((aligned(4))); static uint8_t ep1tx[64] __attribute__((aligned(4))); static uint8_t ep1rx[64 + 4] __attribute__((aligned(4))); -#if FELUCCA_CDC -static uint8_t ep2tx[8] __attribute__((aligned(4))); -static uint8_t ep3tx[64] __attribute__((aligned(4))); -static uint8_t ep3rx[64 + 4] __attribute__((aligned(4))); -/* serial rings: in = host -> console (ISR writes), out = console -> host (ISR reads) */ -#define CI_N 256u -#define CO_N 2048u -static uint8_t cdc_in[CI_N], cdc_out[CO_N]; -static volatile uint32_t ci_w, ci_r, co_w, co_r; -static struct { - uint8_t line[7]; /* line coding: just stored and echoed back */ - volatile uint8_t dtr; /* host has the port open */ - uint8_t e0_rx; /* SET_LINE_CODING data stage pending */ - uint8_t rx_pend; /* EP3 OUT packet seen, not yet taken (the ring was full) */ - uint32_t rx_pkts, tx_pkts; -} 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 +#if FOMA_USB_AUDIO +/* USB audio from the host: the packets in a ring (16-bit L | R << 16), read by usb_audio_take at the I2S clock */ #define UAC_RATE 44100u -#if FELUCCA_UAC_48K -/* 48 kHz: the same times in 48 kHz frames (x 160 / 147); a render of HALF_FRAMES gives 139..140 frames */ -#define UA_PRIME48 113u -#define UA_LO48 87u -#define UA_HI48 139u -#define UA_REND48 ((HALF_FRAMES * 160u + 146u) / 147u) -#define UA_MAXF 49u /* frames in the largest packet: 48 + 1 */ -_Static_assert(UA_HI48 + UA_REND48 + UA_MAXF < UA_N, "the ring holds the band, a render and a packet (48 kHz)"); -#else -#define UA_MAXF 46u /* frames in the largest packet */ -#endif -#define UAC_MAXP (UA_MAXF * 4u) -_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))); +#define UO_N 2048u /* frames; a power of two */ +#define UO_MAXF 49u /* frames in the largest packet the host may send (44.1: 44 or 45) */ +#define UO_MAXP (UO_MAXF * 4u) +#define UO_TGT (2u * HALF_FRAMES) /* the fill a render aims to start at: ~11.6 ms with 256-frame halves */ +_Static_assert(UO_TGT + 4u * HALF_FRAMES < UO_N, "the ring holds the target, renders and packets"); +static uint32_t uo_ring[UO_N]; +static volatile uint32_t uo_w, uo_r; +static uint32_t ep4rx[UO_MAXF + 1u] __attribute__((aligned(4))); static struct { - volatile uint8_t alt; /* streaming interface setting: 1 = the host records */ - volatile uint8_t r48; /* the host's rate (SET_CUR): 1 = 48 kHz, 0 = 44.1 (bus reset) */ - uint8_t ring48; /* the rate the ring was primed for (the render's; a change re-primes) */ - 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 */ - uint32_t rate_sets; /* SET_CUR sampling frequency requests */ -} uac; -#if FELUCCA_UAC_48K -#include "uac_fir.h" -/* the resampler's input history: the last 16 frames, written twice so a window of UAC_FIR_N never wraps */ -#define RS_H 16u -_Static_assert(RS_H >= UAC_FIR_N && (RS_H & (RS_H - 1u)) == 0, "the history holds a window"); -static struct { - int16_t l[2u * RS_H], r[2u * RS_H]; /* r right after l (the FIR loop reads both from one pointer) */ - uint32_t w; /* input frames written */ - uint32_t ph; /* the next output's phase, 0..159 */ -} rs; -#endif + volatile uint8_t alt; /* the streaming interface: 1 = the host plays */ + uint8_t go; /* primed: usb_audio_take reads the ring */ + uint32_t pos; /* the read position's fraction, Q16 */ + int32_t err; /* the fill's distance from UO_TGT, smoothed (frames, Q8) */ + uint32_t pkts, frames, underruns, overruns, starts; +} uo; #endif static struct { @@ -155,7 +82,7 @@ static uint32_t sx_out_q[SXQ]; static volatile uint32_t so_w, so_r; #endif -/* MIDI rings: 4-byte USB-MIDI event packets */ +/* MIDI rings: 4-byte USB-MIDI event packets. In: the cable nibble is where it came from (0 USB, 1 the TRS jack) */ #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; @@ -169,34 +96,26 @@ 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, +0.20 more with 48 kHz (2.5) (hosts cache descriptors - * per version) */ -#define CDC_IF (2 + FELUCCA_UAC) +/* interfaces: 0 audio control, 1 MIDI streaming, 2 audio streaming (FOMA_USB_AUDIO). + * bcdDevice: 3.00 MIDI, 3.40 with the audio from the host (hosts cache descriptors per version; Felucca used 3.10 + * .. 3.60 for its own sets) */ #define UAC_AS_IF 2u -#define CFG_LEN (101 + 74 * FELUCCA_CDC + 74 * FELUCCA_UAC + 3 * FELUCCA_UAC_48K) -#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 + 0x10 * (FELUCCA_UAC + FELUCCA_UAC_48K), 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 +#define CFG_LEN (101 + 74 * FOMA_USB_AUDIO) +#define USB_NIF (2 + FOMA_USB_AUDIO) +#define BCD_LO (0x40 * FOMA_USB_AUDIO) #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 + 0x10 * (FELUCCA_UAC + FELUCCA_UAC_48K), 0x03, + FELUCCA_USB_PID >> 8, 0x00 + BCD_LO, 0x03, 1, 2, 0, 1}; 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 +#if FOMA_USB_AUDIO 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 */ + 12, 0x24, 2, 1, 0x01, 0x01, 0, 2, 0x03, 0x00, 0, 0, /* input terminal 1: USB streaming, 2 ch (L R) */ + 9, 0x24, 3, 2, 0x01, 0x03, 0, 1, 0, /* output terminal 2: speaker, from 1 */ #else 9, 0x24, 1, 0x00, 0x01, 9, 0, 1, 1, #endif @@ -210,60 +129,17 @@ static const uint8_t CFG_DESC[] = { 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 */ +#if FOMA_USB_AUDIO + 9, 4, UAC_AS_IF, 0, 0, 1, 2, 0, 0, /* IF2 the stream, 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 */ -#if FELUCCA_UAC_48K - 14, 0x24, 2, 1, 2, 2, 16, 2, 0x44, 0xAC, 0x00, 0x80, 0xBB, 0x00, /* type I: 2 ch, 16 bit, 44100 / 48000 */ -#else + 7, 0x24, 1, 1, 1, 0x01, 0x00, /* AS general: terminal 1, 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 */ -#endif - 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, 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, CDC_IF + 1, /* call management: the data IF */ - 4, 0x24, 0x02, 0x02, /* ACM: line coding + state */ - 5, 0x24, 0x06, CDC_IF, CDC_IF + 1, /* union */ - 7, 5, 0x82, 3, 8, 0, 16, /* EP2 IN interrupt (never sent) */ - 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 */ + /* type I: 2 ch, 16 bit, 44100 */ + 9, 5, 0x04, 0x09, UO_MAXP & 0xFF, UO_MAXP >> 8, 1, 0, 0, /* EP4 OUT isochronous adaptive, 1 ms */ + 7, 0x25, 1, 0x00, 0, 0, 0, /* CS endpoint: no controls */ #endif }; typedef char cfg_len_ok[sizeof CFG_DESC == CFG_LEN ? 1 : -1]; -#if FELUCCA_CDC -/* SLOOP 2.4, after Felucca 1.0.3 (#67): menu USB SERIAL. ON presents the serial console as before (the - * descriptors above, byte for byte); OFF, the default, presents the device as a FELUCCA_CDC=0 build does: class 0, - * no IAD, audio + MIDI only (the same bytes: tests/uac_test.c compares them). With the console, macOS 13-15 let - * Apple's CDC composite driver take the device and the USB audio input never appears. The console is a developer - * tool; the editor, the installer and the soft key use USB-MIDI. Read once, before usb_start (main.c: the settings - * are loaded first), so the host sees one device from the start */ -static uint8_t usb_cdc_on; -static const uint8_t DEV_DESC_PLAIN[18] = {18, 1, 0x10, 0x01, 0, 0, 0, 64, 0x09, 0x12, 0x01, 0x00, - 0x00 + 0x10 * (FELUCCA_UAC + FELUCCA_UAC_48K), 0x03, 1, 2, 0, 1}; -#define CFG_PLAIN_LEN (CFG_LEN - 74) /* without the audio IAD (8) and the CDC block (66) */ -static uint8_t cfg_plain[CFG_PLAIN_LEN]; -static const uint8_t *cfg_plain_get(void) -{ - if (!cfg_plain[0]) { - memcpy(cfg_plain, CFG_DESC, 9); - cfg_plain[2] = CFG_PLAIN_LEN & 0xFF; - cfg_plain[3] = CFG_PLAIN_LEN >> 8; - cfg_plain[4] = USB_NIF - 2; - memcpy(cfg_plain + 9, CFG_DESC + 17, CFG_PLAIN_LEN - 9); - } - return cfg_plain; -} -static int usb_cdc_now(void) { return usb_cdc_on; } /* (the menu: what this start presents) */ -#else -static int usb_cdc_now(void) { return 0; } -#endif 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}; @@ -280,20 +156,10 @@ static int get_desc(uint32_t wvalue, const uint8_t **d, uint16_t *l) case 1: *d = DEV_DESC; *l = sizeof DEV_DESC; -#if FELUCCA_CDC - if (!usb_cdc_on) - *d = DEV_DESC_PLAIN; -#endif return 1; case 2: *d = CFG_DESC; *l = sizeof CFG_DESC; -#if FELUCCA_CDC - if (!usb_cdc_on) { - *d = cfg_plain_get(); - *l = CFG_PLAIN_LEN; - } -#endif return 1; case 3: switch (wvalue & 0xFFu) { @@ -348,48 +214,21 @@ 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 */ +#if FOMA_USB_AUDIO +static void uo_ep4_reset(void) /* EP4 OUT: isochronous, nothing pending */ { - 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; - } + sie_wr(S_INDEX, 4); + sie_wr(S_RXCSR1, 0x90); /* ClrDataTog + FlushFIFO */ + sie_wr(S_RXCSR2, 0x40); /* ISO */ } -#endif - -#if FELUCCA_UAC -/* SET_CUR sampling frequency (any time: before or after SET_INTERFACE; a bus reset or a new configuration go - * back to 44.1). 48 kHz when built with it and asked for (the nearer of the two), else 44.1. A change restarts - * the stream: silence packets until the next render primes the ring at the new rate. */ -static void uac_rate_set(uint32_t hz) +static void uo_stream(uint32_t alt) /* SET_INTERFACE, configuration, bus reset */ { - uint8_t r48 = (uint8_t)(FELUCCA_UAC_48K && hz >= (UAC_RATE + 48000u) / 2u); - if (r48 == uac.r48) - return; - uac.go = 0; + uo.go = 0; RING_PUBLISH(); - uac.r48 = r48; - uac.acc = 0; - uac.pkts = uac.frames = 0; + uo.alt = (uint8_t)alt; + if (alt) + uo.starts++; } #endif @@ -406,32 +245,13 @@ static void ep1_config(void) sie_wr(S_RXCSR2, 0); sie_wr(S_INTRRX1E, 0x02); fm1_usb_ep_enable(1u << 1); -#if FELUCCA_CDC - fm1_usb_ep_txbuf(2, ep2tx); - sie_wr(S_INDEX, 2); - sie_wr(S_TXMAXP, 0xFF); - sie_wr(S_TXCSR1, 0x48); - sie_wr(S_TXCSR2, 0); - fm1_usb_ep_txbuf(3, ep3tx); - fm1_usb_ep_rxbuf(3, ep3rx); - sie_wr(S_INDEX, 3); - sie_wr(S_TXMAXP, 0xFF); - sie_wr(S_TXCSR1, 0x48); - sie_wr(S_TXCSR2, 0); - sie_wr(S_RXMAXP, 0xFF); - sie_wr(S_RXCSR1, 0x90); - sie_wr(S_RXCSR2, 0); - sie_wr(S_INTRRX1E, 0x0A); - 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); +#if FOMA_USB_AUDIO + fm1_usb_ep4_rxbuf(ep4rx); sie_wr(S_INDEX, 4); - sie_wr(S_TXMAXP, 0xFF); - uac_ep4_reset(); + sie_wr(S_RXMAXP, 0xFF); + uo_ep4_reset(); + uo_stream(0); fm1_usb_ep_enable(1u << 4); - uac_stream(0); #endif } @@ -481,23 +301,12 @@ static void ep0_service(void) if (csr & 0x04u) { /* SentStall */ sie_wr(S_CSR0, 0); usb.e0_tx = 0; -#if FELUCCA_CDC - cdc.e0_rx = 0; -#endif -#if FELUCCA_UAC - uac.e0_rx = 0; -#endif + usb.e0_tx = 0; return; } if (csr & 0x10u) { /* SetupEnd: the host abandoned the transfer */ sie_wr(S_CSR0, 0x80); 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) { if (!(csr & 0x02u)) @@ -507,24 +316,6 @@ static void ep0_service(void) if (!(csr & 0x01u)) return; fm1_usb_rx_sync(); -#if FELUCCA_CDC - if (cdc.e0_rx) { /* SET_LINE_CODING data stage */ - uint32_t n = sie_rd(S_COUNT0); - for (i = 0; i < 7u && i < n; i++) - cdc.line[i] = ep0buf[i]; - cdc.e0_rx = 0; - goto ack; - } -#endif -#if FELUCCA_UAC - if (uac.e0_rx) { /* SET_CUR sampling frequency: 3 bytes, Hz */ - uac.rate_sets++; - if (sie_rd(S_COUNT0) >= 3u) - uac_rate_set(ep0buf[0] | (uint32_t)ep0buf[1] << 8 | (uint32_t)ep0buf[2] << 16); - uac.e0_rx = 0; - goto ack; - } -#endif for (i = 0; i < 8u; i++) s[i] = ep0buf[i]; usb.setups++; @@ -554,10 +345,9 @@ static void ep0_service(void) ep1_config(); else sie_wr(S_INTRRX1E, 0); -#if FELUCCA_UAC +#if FOMA_USB_AUDIO if (usb.config != 1u) - uac_stream(0); - uac_rate_set(UAC_RATE); /* a new configuration starts at 44.1 */ + uo_stream(0); #endif goto ack; case 0x8008: @@ -569,10 +359,10 @@ static void ep0_service(void) e0_send(zero2, 2, wlength); return; case 0x010B: /* SET_INTERFACE: alt 0 (alt 1 for the audio stream) */ -#if FELUCCA_UAC +#if FOMA_USB_AUDIO if (s[4] == UAC_AS_IF && wvalue <= 1u && usb.config) { - uac_ep4_reset(); - uac_stream(wvalue); + uo_ep4_reset(); + uo_stream(wvalue); goto ack; } #endif @@ -580,10 +370,10 @@ static void ep0_service(void) goto ack; goto stall; case 0x810A: -#if FELUCCA_UAC +#if FOMA_USB_AUDIO if (s[4] == UAC_AS_IF) { static uint8_t alt; - alt = uac.alt; + alt = uo.alt; e0_send(&alt, 1, wlength); return; } @@ -591,13 +381,9 @@ static void ep0_service(void) e0_send(zero2, 1, wlength); return; case 0x0201: { /* CLEAR_FEATURE(ENDPOINT_HALT): data toggle reset */ -#if FELUCCA_CDC - uint32_t ep = s[4] & 0x0Fu, last = usb_cdc_on ? 3u : 1u; /* (USB SERIAL OFF: EP2 / EP3 are not described) */ -#else uint32_t ep = s[4] & 0x0Fu, last = 1u; -#endif -#if FELUCCA_UAC - if (wvalue == 0 && s[4] == 0x84u) +#if FOMA_USB_AUDIO + if (wvalue == 0 && s[4] == 0x04u) goto ack; /* isochronous: no halt, no toggle */ #endif if (wvalue != 0 || ep > last) @@ -611,54 +397,6 @@ static void ep0_service(void) } goto ack; } -#if FELUCCA_CDC - case 0x2120: /* SET_LINE_CODING: 7 bytes follow */ - if (wlength) { - cdc.e0_rx = 1; - sie_wr(S_INDEX, 0); - sie_wr(S_CSR0, 0x40); /* ServicedRxPktRdy, no DataEnd yet */ - return; - } - goto ack; - case 0xA121: /* GET_LINE_CODING */ - e0_send(cdc.line, 7, wlength); - return; - case 0x2122: /* SET_CONTROL_LINE_STATE */ - cdc.dtr = s[2] & 1u; - 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 rate / the range */ - case 0xA282: - case 0xA283: { - static const uint8_t RATE[3] = {UAC_RATE & 0xFF, (UAC_RATE >> 8) & 0xFF, UAC_RATE >> 16}; -#if FELUCCA_UAC_48K - static const uint8_t RATE48[3] = {48000u & 0xFF, (48000u >> 8) & 0xFF, 48000u >> 16}; -#endif - if (s[4] != 0x84u || s[3] != 1u) - goto stall; -#if FELUCCA_UAC_48K - if (s[1] == 0x83u || (s[1] == 0x81u && uac.r48)) { - e0_send(RATE48, 3, wlength); - return; - } -#endif - e0_send(RATE, 3, wlength); - return; - } -#endif default: goto stall; } @@ -744,7 +482,7 @@ static void midi_in_event(uint32_t pkt) #endif } if (cin == 0xFu && (st == 0xF8u || st == 0xFAu || st == 0xFBu || st == 0xFCu)) { /* clock, transport */ - if (mi_w - mi_r < MQ) { + if (!MIDI_RT(st, 1) && mi_w - mi_r < MQ) { midi_in_q[mi_w % MQ] = 0xFu | st << 8; RING_PUBLISH(); mi_w++; @@ -754,7 +492,7 @@ static void midi_in_event(uint32_t pkt) 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; + midi_in_q[mi_w % MQ] = pkt & ~0xF0u; /* cable 0: USB */ RING_PUBLISH(); mi_w++; } @@ -917,260 +655,80 @@ static void ep1_tx(void) usb.tx_pkts++; } -#if FELUCCA_CDC -static void ep3_rx(void) /* leaves the packet (NAK) while the ring is full */ +#if FOMA_USB_AUDIO +/* TIMER5, 2 kHz, also nested in the render: an EP4 OUT packet into the ring */ +static void uo_service(void) { - uint32_t csr, n, i; - sie_wr(S_INDEX, 3); + uint32_t csr, n, i, w; + if (!usb.up || !usb.config || !uo.alt) + return; + sie_wr(S_INDEX, 4); csr = sie_rd(S_RXCSR1) | (sie_rd(S_RXCSR2) << 8); - if (!(csr & 1u)) { - cdc.rx_pend = 0; + if (!(csr & 1u)) return; - } - n = sie_rd(S_RXCOUNT1) | (sie_rd(S_RXCOUNT2) << 8); - if (n > 64u) - n = 64u; - if (CI_N - (ci_w - ci_r) < n) - return; /* rx_pend stays: retried next poll */ - cdc.rx_pend = 0; + n = (sie_rd(S_RXCOUNT1) | (sie_rd(S_RXCOUNT2) << 8)) / 4u; + if (n > UO_MAXF) + n = UO_MAXF; fm1_usb_rx_sync(); - for (i = 0; i < n; i++) - cdc_in[(ci_w + i) % CI_N] = ep3rx[i]; - RING_PUBLISH(); - ci_w += n; - cdc.rx_pkts++; + w = uo_w; + if (UO_N - (w - uo_r) < n) { + uo.overruns++; /* nobody plays it (or the rates part): drop */ + } else { + for (i = 0; i < n; i++) + uo_ring[(w + i) & (UO_N - 1u)] = ep4rx[i]; + RING_PUBLISH(); + uo_w = w + n; + } + uo.pkts++; + uo.frames += n; csr = (csr & ~0x164u) | 0x10u; sie_wr(S_RXCSR1, csr & 0xFFu); sie_wr(S_RXCSR2, csr >> 8); } -static void ep3_tx(void) /* <= 63 bytes per packet: never needs a ZLP */ -{ - uint32_t csr, n = 0; - if (co_w == co_r) - return; - sie_wr(S_INDEX, 3); - csr = sie_rd(S_TXCSR1); - if (csr & 0x01u) - return; - if (csr & 0x80u) - sie_wr(S_TXCSR1, csr & ~0x80u); - while (co_r != co_w && n < 63u) - ep3tx[n++] = cdc_out[co_r++ % CO_N]; - fm1_usb_ep_send(3, ep3tx, n); - sie_wr(S_TXCSR1, sie_rd(S_TXCSR1) | 0x01u); - cdc.tx_pkts++; -} -#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 */ +/* the audio ISR, once a render: n frames (Q15, L R) of what the host plays, resampled from the ring, into d. + * The read step is 44.1 / 44.1176 kHz (Q16), steered by how far the fill at a render's start is from UO_TGT + * (smoothed; +-2/65536 a frame of error, at most +-400). 0: nothing plays (d untouched) */ +static __attribute__((noinline)) int usb_audio_take(int32_t *d, uint32_t n) { - 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; + uint32_t r = uo_r, fill = uo_w - r, i, pos = uo.pos, step; + int32_t adj; + if (!uo.alt || !usb.config) { + uo.go = 0; + return 0; } - if (!uac.go || uac.ring48 != uac.r48) { /* (re)start: silence ahead, then this render */ - uint32_t r = ua_r, i, prime = UA_PRIME; - uac.go = 0; -#if FELUCCA_UAC_48K - uac.ring48 = uac.r48; - if (uac.ring48) { /* the resampler starts from silence */ - prime = UA_PRIME48; - for (i = 0; i < 2u * RS_H; i++) - rs.l[i] = rs.r[i] = 0; - rs.w = rs.ph = 0; - } -#endif - for (i = 0; i < prime; i++) - ua_ring[(r + i) & (UA_N - 1u)] = 0; + if (!uo.go) { + if (fill < UO_TGT) + return 0; /* priming */ + r = uo_w - UO_TGT; /* start at the target: the excess is old */ + pos = 0; + uo.err = 0; + uo.go = 1; + fill = UO_TGT; + } + uo.err += (((int32_t)fill - (int32_t)UO_TGT) * 256 - uo.err) / 16; + adj = uo.err / 128; /* 2 (Q16) per frame of error */ + adj = adj > 400 ? 400 : adj < -400 ? -400 : adj; + step = (uint32_t)(65510 + adj); /* 65536 x 44100 / 44117.6 */ + if (fill < ((n * step) >> 16) + 2u) { /* (n * step < 2^32: n is a half, 256) */ + uo.underruns++; /* ran dry: prime again */ + uo.go = 0; RING_PUBLISH(); - ua_w = r + prime; - uac.fill_min = 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; -} - -#if FELUCCA_UAC_48K -/* 44.1 -> 48 kHz (x 160 / 147), one block: each input frame enters the history, then the 1 or 2 output - * frames whose newest input it is: phase ph, the window of UAC_FIR_N frames ending at it, the taps of phase - * ph (or of 159 - ph backwards: the prototype is symmetric), Q15 into 32-bit sums (the taps' absolute sum - * stays under 2.0: no overflow) */ -static __attribute__((noinline)) void uac_tap48(const int32_t *out, uint32_t n) -{ - uint32_t w = ua_w, i, j, k = 0, h = rs.w, ph = rs.ph; - if (UA_N - (w - ua_r) < n + n / 8u + 2u) { /* nobody reads: drop the block (<= n * 160 / 147 + 1) */ - uac.overruns++; - return; - } - for (i = 0; i < n; i++) { - uint32_t s = h & (RS_H - 1u); - int16_t l = (int16_t)uac_s16(out[2u * i]), r = (int16_t)uac_s16(out[2u * i + 1u]); - rs.l[s] = rs.l[s + RS_H] = l; - rs.r[s] = rs.r[s + RS_H] = r; - h++; - s = (h - UAC_FIR_N) & (RS_H - 1u); /* the window: oldest .. this frame */ - do { - const int16_t *x = &rs.l[s]; /* R: x[2 * RS_H] */ - int32_t al = 1 << (UAC_FIR_Q - 1), ar = 1 << (UAC_FIR_Q - 1); - if (ph < UAC_FIR_L / 2u) { - const int16_t *c = UAC_FIR[ph]; - for (j = UAC_FIR_N; j; j--, x++) { - int32_t t = *c++; - al += t * x[0]; - ar += t * x[2u * RS_H]; - } - } else { - const int16_t *c = &UAC_FIR[UAC_FIR_L - 1u - ph][UAC_FIR_N - 1u]; - for (j = UAC_FIR_N; j; j--, x++) { - int32_t t = *c--; - al += t * x[0]; - ar += t * x[2u * RS_H]; - } - } - ua_ring[(w + k++) & (UA_N - 1u)] = (uint32_t)(uint16_t)uac_s16(al >> UAC_FIR_Q) | - (uint32_t)(uint16_t)uac_s16(ar >> UAC_FIR_Q) << 16; - ph += UAC_FIR_M; - } while (ph < UAC_FIR_L); - ph -= UAC_FIR_L; - } - rs.w = h; - rs.ph = ph; - RING_PUBLISH(); - ua_w = w + k; -} -#endif - -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 FELUCCA_UAC_48K - if (uac.ring48) { - uac_tap48(out, n); - return; - } -#endif - 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; + uo_r = uo_w; + return 0; } -#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, lo = UA_LO, hi = UA_HI; -#if FELUCCA_UAC_48K - if (uac.r48) { /* 48 frames a ms, no pattern */ - n = 48u; - lo = UA_LO48; - hi = UA_HI48; - } else -#endif - { - uac.acc += UAC_RATE % 1000u; - if (uac.acc >= 1000u) { - uac.acc -= 1000u; - n++; - } - } - if (!uac.go || uac.ring48 != uac.r48) { /* not primed (at this rate) yet */ - for (i = 0; i < n; i++) - d[i] = 0; - return n; - } - if (uac.fill_min > hi) { - n++; - uac.adj_up++; - } else if (uac.fill_min < 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; + for (i = 0; i < n; i++) { + uint32_t k = pos >> 16, a = uo_ring[(r + k) & (UO_N - 1u)], b = uo_ring[(r + k + 1u) & (UO_N - 1u)]; + int32_t fr = (int32_t)((pos & 0xFFFFu) >> 2), al = (int16_t)a, ar = (int16_t)(a >> 16); /* Q14 */ + d[2u * i] = al + ((((int16_t)b - al) * fr) >> 14); + d[2u * i + 1u] = ar + ((((int16_t)(b >> 16) - ar) * fr) >> 14); + pos += step; } - 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) */ + uo_r = r + (pos >> 16); + uo.pos = pos & 0xFFFFu; + return 1; } #endif @@ -1230,15 +788,8 @@ static void usb_poll(void) /* TIMER5 ISR, 2 kHz */ 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); - uac_rate_set(UAC_RATE); +#if FOMA_USB_AUDIO + uo_stream(0); #endif fm1_usb_ep0_buf(ep0buf); sie_wr(S_INTRUSBE, 0x07); @@ -1253,18 +804,8 @@ static void usb_poll(void) /* TIMER5 ISR, 2 kHz */ ep1_rx(); if (usb.config) ep1_tx(); -#if FELUCCA_CDC - if (usb.config) { - if (ir & 0x08u) - cdc.rx_pend = 1; - if (cdc.rx_pend) /* not every poll: 3 SIE round trips each */ - ep3_rx(); - if (cdc.dtr) - ep3_tx(); - } -#endif -#if FELUCCA_UAC - uac_service(); +#if FOMA_USB_AUDIO + uo_service(); #endif } diff --git a/platform/web.c b/platform/web.c index cf36d87..3a02d35 100644 --- a/platform/web.c +++ b/platform/web.c @@ -24,6 +24,13 @@ typedef struct { /* as gfx.c */ #define HALF_FRAMES 256u static uint32_t now_ms, now_us, fb_gen; +#if FOMA_MIDI_CLOCK +#define CLOCK_MUL ((uint64_t)44100u * 4294967296u / 1000000u) /* now_us -> frames */ +#include "clock.c" +#endif +#if FOMA_USB_AUDIO +const int32_t *audio_in(void) { return 0; } /* (the emulator has no audio from a computer yet) */ +#endif uint32_t millis(void) { return now_ms; } uint32_t micros(void) { return now_us; } @@ -31,7 +38,7 @@ uint32_t micros(void) { return now_us; } /* ---- the panel: the page sets what is held; loop() sees it as the FM-1 shows it */ static uint32_t web_k, web_b, web_master_v = 700; static int32_t web_e[ENC_COUNT]; -static uint32_t in_keys, in_kp, in_kr, in_btn, in_bp, in_br, led_k, led_b; +static uint32_t in_keys, in_kp, in_kr, in_btn, in_bp, in_br, led_k, led_b, led_bg; static int32_t in_enc[ENC_COUNT]; static uint32_t taps_k, taps_b; /* presses shorter than a millisecond still count */ @@ -57,6 +64,8 @@ EXPORT(web_led_keys) uint32_t web_led_keys(void) { return led_k; } EXPORT(web_led_buttons) uint32_t web_led_buttons(void) { return led_b; } +EXPORT(web_led_backlight) +uint32_t web_led_backlight(void) { return led_bg; } static void input_snapshot(void) { int e; @@ -92,6 +101,8 @@ void led_button(int b, int on) { led_b = on ? led_b | 1u << b : led_b & ~(1u << b); } } +void led_backlight(int level) { led_bg = level < 0 ? 0u : level > 2 ? 2u + : (uint32_t)level; } /* ---- the screen: the page reads fb when fb_gen moves */ EXPORT(web_fb) @@ -111,6 +122,12 @@ static void screen_flush(void) { static uint32_t mq_in[MQ], mq_out[MQ], mi_w, mi_r, mo_w, mo_r; EXPORT(web_midi_in) void web_midi_in(uint32_t st, uint32_t d1, uint32_t d2) { +#if FOMA_MIDI_CLOCK + if (st >= 0xF8u) { + clock_in(st, MIDI_USB, now_us); + return; + } +#endif if (mi_w - mi_r < MQ) { mq_in[mi_w++ % MQ] = (st & 0xFFu) | (d1 & 0x7Fu) << 8 | (d2 & 0x7Fu) << 16; } @@ -128,7 +145,7 @@ int midi_read(uint8_t *status, uint8_t *d1, uint8_t *d2) { *status = (uint8_t)m; *d1 = (uint8_t)(m >> 8); *d2 = (uint8_t)(m >> 16); - return 1; + return MIDI_USB; /* (the page's MIDI in stands for USB) */ } void midi_send(uint8_t status, uint8_t d1, uint8_t d2) { if (mo_w - mo_r < MQ) { @@ -137,7 +154,7 @@ void midi_send(uint8_t status, uint8_t d1, uint8_t d2) { } /* ---- settings: the page keeps them (localStorage) and gives them back before boot */ -static uint8_t store[256]; +static uint8_t store[SETTINGS_MAX]; static int32_t store_len = -1; static uint32_t store_gen; EXPORT(web_store) @@ -145,7 +162,7 @@ uint8_t *web_store(void) { return store; } EXPORT(web_store_len) int32_t web_store_len(void) { return store_len; } EXPORT(web_store_set_len) -void web_store_set_len(int32_t n) { store_len = n > 256 ? 256 : n; } +void web_store_set_len(int32_t n) { store_len = n > (int32_t)SETTINGS_MAX ? (int32_t)SETTINGS_MAX : n; } EXPORT(web_store_gen) uint32_t web_store_gen(void) { return store_gen; } int settings_load(void *p, uint32_t n) { @@ -208,6 +225,9 @@ static void tick(void) { for (i = 0; i < 2u * HALF_FRAMES; i++) { blk[i] = 0; } +#if FOMA_MIDI_CLOCK + clock_block(HALF_FRAMES, now_us); +#endif audio(blk, HALF_FRAMES); for (i = 0; i < HALF_FRAMES; i++) { uint32_t r = (ring_w++ % RING) * 2u, c; diff --git a/src/main.c b/src/main.c index 1b06ea5..2117ca1 100644 --- a/src/main.c +++ b/src/main.c @@ -4,7 +4,9 @@ * OCT- OCT+ the octave (kept in flash) * PRESETS the waveform: sine, triangle, saw, square * KNOB1..4 a value each, 0..127, on the screen (yours to use) - * USB-MIDI notes in play too + * USB-MIDI notes in play too (and the TRS jack's) + * PLAY starts / stops a 120 BPM MIDI clock, sent over USB-MIDI; its light blinks on the beat + * USB audio a computer playing to the FM-1 comes out of it * * What you can call: platform/fm1.h. The rules (no float, keep audio() short): README.md. */ #include "fm1.h" @@ -42,7 +44,30 @@ static int32_t osc(uint32_t ph) { } } +static volatile uint8_t beat; /* written by audio(): the clock's beat is on */ + void audio(int32_t *out, uint32_t frames) { +#if FOMA_MIDI_CLOCK + static uint8_t tick, running; + const clock_event_t *ev; + for (int n = clock_events(&ev), i = 0; i < n; i++) { /* 24 ticks a beat: the light is on for the first 6 */ + if (ev[i].what == CLOCK_START) { + running = 1, tick = 0; + } else if (ev[i].what == CLOCK_STOP) { + running = 0; + } else if (ev[i].what == CLOCK_TICK && running) { + beat = tick < 6; + tick = (uint8_t)((tick + 1) % 24); + } + } + beat &= running; +#endif +#if FOMA_USB_AUDIO + const int32_t *in = audio_in(); /* the computer's sound, as it comes */ + for (uint32_t i = 0; in && i < 2 * frames; i++) { + out[i] += in[i]; + } +#endif for (int v = 0; v < VOICES; v++) { int32_t amp = voice[v].amp, gate = voice[v].gate; uint32_t ph = voice[v].phase, inc = voice[v].inc; @@ -160,6 +185,10 @@ void setup(void) { for (int k = 0; k < 4; k++) { draw_knob(k); } +#if FOMA_MIDI_CLOCK + clock_tempo(12000); + clock_send(1); +#endif print("hello from setup()"); } @@ -209,6 +238,14 @@ void loop(void) { draw_knob(k); } } +#if FOMA_MIDI_CLOCK + static uint8_t playing; + if (button_pressed(BTN_PLAY)) { + playing = !playing; + playing ? clock_start() : clock_stop(); + } + led_button(BTN_PLAY, beat); +#endif led_button(BTN_OCT_DOWN, saved.octave < 0); led_button(BTN_OCT_UP, saved.octave > 0); diff --git a/tools/build.py b/tools/build.py index 7de03d4..a6cf026 100644 --- a/tools/build.py +++ b/tools/build.py @@ -79,6 +79,10 @@ def tc_all(*cmds): return list(ex.map(lambda c: tc(*c), cmds)) +# firmware.json "options": the platform's parts you can leave out (all in unless set false), as FOMA_* in fm1.h +OPTIONS = {"usb_audio": "FOMA_USB_AUDIO", "trs_midi": "FOMA_TRS_MIDI", "midi_clock": "FOMA_MIDI_CLOCK"} + + def sources(): return sorted(SRC.glob("**/*.c")) @@ -94,6 +98,11 @@ def config(): if not re.fullmatch(r"FM-1_\d{3}", c["product"]): raise BuildError('firmware.json: "identity" must be FM-1_ and two digits (the third is your minor version)') c["file"] = re.sub(r"[^a-z0-9.-]+", "-", c["name"].lower()).strip("-") or "firmware" + opts = c.get("options", {}) + bad = sorted(set(opts) - set(OPTIONS)) + if bad: + raise BuildError(f"firmware.json: unknown option {', '.join(bad)} (there are: {', '.join(OPTIONS)})") + c["defines"] = [f"-D{OPTIONS[k]}={int(bool(opts.get(k, True)))}" for k in OPTIONS] return c @@ -115,6 +124,7 @@ def build_wasm(cfg): *INCLUDES, f'-DAPP_NAME="{cfg["name"]}"', f'-DAPP_VER="{cfg["version"]}"', + *cfg["defines"], "-Wl,--no-entry", "-Wl,-z,stack-size=1048576", "-o", @@ -184,7 +194,7 @@ def build_loader(): def build_app(cfg): FW.mkdir(parents=True, exist_ok=True) - flags = [*CFLAGS, *INCLUDES, f'-DAPP_NAME="{cfg["name"]}"', f'-DAPP_VER="{cfg["version"]}"', f'-DFELUCCA_ID="{cfg["product"]}"'] + flags = [*CFLAGS, *INCLUDES, f'-DAPP_NAME="{cfg["name"]}"', f'-DAPP_VER="{cfg["version"]}"', f'-DFELUCCA_ID="{cfg["product"]}"', *cfg["defines"]] objs, cmds = [], [] for s in [PLAT / "crt0.S", PLAT / "hal/fm1_vec.S", PLAT / "hal/fm1_isr.S"]: objs.append(FW / (s.stem + ".o")) diff --git a/web/app.js b/web/app.js index 11bd7bd..2623026 100644 --- a/web/app.js +++ b/web/app.js @@ -338,6 +338,7 @@ function onFrame(m) { if (m.fb) drawScreen(m.fb) keys.forEach((el, i) => el.classList.toggle('lit', !!(m.keys & (1 << i)))) buttons.forEach((el, i) => el.classList.toggle('lit', !!(m.buttons & (1 << i)))) + for (const el of [...keys, ...buttons]) el.dataset.backlight = m.backlight || 0 if (m.store) saveStore(m.store) if (m.log) for (const l of m.log.replace(/\n$/, '').split('\n')) say(l) if (m.midi && midiOut) for (const p of m.midi) midiOut.send(midiBytes(p)) @@ -422,7 +423,7 @@ $('midiin').addEventListener('change', async () => { const a = await midiPorts() if (midiIn) midiIn.onmidimessage = null midiIn = a && a.inputs.get($('midiin').value) - if (midiIn) midiIn.onmidimessage = (e) => e.data[0] < 0xf0 && send({ type: 'midi', data: Array.from(e.data) }) + if (midiIn) midiIn.onmidimessage = (e) => (e.data[0] < 0xf0 || [0xf8, 0xfa, 0xfb, 0xfc].includes(e.data[0])) && send({ type: 'midi', data: Array.from(e.data) }) }) $('midiout').addEventListener('change', async () => { const a = await midiPorts() diff --git a/web/style.css b/web/style.css index d0d42bf..d4b4160 100644 --- a/web/style.css +++ b/web/style.css @@ -307,6 +307,15 @@ pre { background: var(--lit); box-shadow: 0 0 1.4cqw var(--lit); } +/* LIGHTS (GLOBAL page): every key and button glows a little */ +.key[data-backlight='1']:not(.lit), +.btn[data-backlight='1']:not(.lit) { + box-shadow: 0 0 0.6cqw color-mix(in srgb, var(--lit) 35%, transparent); +} +.key[data-backlight='2']:not(.lit), +.btn[data-backlight='2']:not(.lit) { + box-shadow: 0 0 1cqw color-mix(in srgb, var(--lit) 70%, transparent); +} .key:focus-visible, .btn:focus-visible, .knob:focus-visible { diff --git a/web/worklet.js b/web/worklet.js index 6581a3d..7a4cdaa 100644 --- a/web/worklet.js +++ b/web/worklet.js @@ -51,7 +51,7 @@ class FM1 extends AudioWorkletProcessor { publish() { const ex = this.ex - const msg = { type: 'frame', ms: ex.web_now(), keys: ex.web_led_keys() >>> 0, buttons: ex.web_led_buttons() >>> 0 } + const msg = { type: 'frame', ms: ex.web_now(), keys: ex.web_led_keys() >>> 0, buttons: ex.web_led_buttons() >>> 0, backlight: ex.web_led_backlight ? ex.web_led_backlight() : 0 } const transfer = [] const gen = ex.web_fb_gen() if (gen !== this.sentFb) { From cc6b76c9d2cce24e39a0dd155809a2f42a8a7274 Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Mon, 19 Oct 2026 23:46:15 -0700 Subject: [PATCH 2/4] Correct the Bluetooth note --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b95672b..2863a4b 100644 --- a/README.md +++ b/README.md @@ -72,8 +72,9 @@ turning one off takes its code and memory out of the firmware: { "name": "MY SYNTH", "version": "0.1", "identity": "FM-1_95", "options": { "usb_audio": false } } ``` -In your code, `#if FOMA_USB_AUDIO` (and `FOMA_TRS_MIDI`, `FOMA_MIDI_CLOCK`) tells you what's in. The FM-1 has no MIDI -out on the TRS jack, and its Bluetooth radio has no open driver, so neither is an option. The emulator follows MIDI +In your code, `#if FOMA_USB_AUDIO` (and `FOMA_TRS_MIDI`, `FOMA_MIDI_CLOCK`) tells you what's in. The FM-1 has no MIDI out on the TRS jack, so that can't be an option. Bluetooth (audio and BLE MIDI) is possible in +principle: JieLi's AC79 SDK has a Bluetooth stack for this chip, but only as prebuilt libraries that need JieLi's OS +underneath, so it isn't here (yet). The emulator follows MIDI clock from Web MIDI; it has no USB audio input (`audio_in()` gives 0). ## The rules of the chip From 67e11a24b8860dce67f81712e806cdabb291587d Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Mon, 19 Oct 2026 23:59:38 -0700 Subject: [PATCH 3/4] Clock start/stop while following --- platform/clock.c | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/platform/clock.c b/platform/clock.c index 699ef83..6cd7499 100644 --- a/platform/clock.c +++ b/platform/clock.c @@ -60,8 +60,15 @@ static void ck_tick(uint32_t at) { /* a followed tick: its length, smoothed (a p } static void clock_block(uint32_t n, uint32_t t) { - uint32_t r = ck_r, from = ck_from; + uint32_t r = ck_r, from = ck_from, req = ck_req; ck_n = 0; + ck_req = 0; + if (req) { /* the app's own start / continue / stop, first (following too) */ + ck_add(0, (int)req); + if (req != CLOCK_STOP) { + ck_next_q8 = 0; /* (its own tempo: a tick on the start) */ + } + } if (from) { while (r != ck_w) { RING_PUBLISH(); @@ -86,16 +93,9 @@ static void clock_block(uint32_t n, uint32_t t) { } ck_measured = ck_q4 ? 176400000u / ck_q4 : 0; /* 44100 * 60 / 24 * 100, Q4 */ } else { - uint32_t req = ck_req, bpm = ck_bpm100 < 100u ? 100u : ck_bpm100, len = 2822400000u / bpm; /* 44100 * 60 / 24 * 100, Q8 */ - r = ck_w; /* (what came in is not followed) */ - ck_req = 0; + uint32_t bpm = ck_bpm100 < 100u ? 100u : ck_bpm100, len = 2822400000u / bpm; /* 44100 * 60 / 24 * 100, Q8 */ + r = ck_w; /* (what came in is not followed) */ ck_on = 0; - if (req) { - ck_add(0, (int)req); - if (req != CLOCK_STOP) { - ck_next_q8 = 0; /* a tick on the start */ - } - } while ((ck_next_q8 >> 8) < n) { ck_add(ck_next_q8 >> 8, CLOCK_TICK); ck_next_q8 += len; From 849cb869cbfd9a08f59804f1c82aeda144eaa8d1 Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Mon, 19 Oct 2026 23:59:56 -0700 Subject: [PATCH 4/4] Clock start/stop comment --- platform/fm1.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/fm1.h b/platform/fm1.h index 888742b..be2eabd 100644 --- a/platform/fm1.h +++ b/platform/fm1.h @@ -126,7 +126,7 @@ typedef struct { void clock_follow(int from); /* 0: its own tempo; MIDI_USB, MIDI_TRS or MIDI_ANY: the clock coming in */ void clock_send(int on); /* 1: send it over USB MIDI */ void clock_tempo(uint32_t bpm100); /* its own tempo, BPM x 100 (12000: 120 BPM) */ -void clock_start(void); /* its own start, continue, stop (followed: the other device's) */ +void clock_start(void); /* start, continue, stop from the app (following: the other device's too) */ void clock_continue(void); void clock_stop(void); int clock_events(const clock_event_t **ev); /* audio() only: this block's events; returns how many */