diff --git a/BUILDING.md b/BUILDING.md index 52ed373..3c3af5e 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -88,6 +88,33 @@ valgrind is installed (exact, about 45 s more); without either it is timed, a ro After an intended change of the sound, `GOLDEN_UPDATE=1 sh tests/run_tests.sh` rewrites the hashes; `BUDGET_UPDATE=1` does the same for the cost files. +## Browser audio preview + +The browser preview uses the firmware's DSP and sequencer with RAM-backed user samples. +It requires Python 3, a host C compiler, Node.js for tests, and Emscripten (`brew install emscripten` on macOS). +It does not need the JieLi toolchain, AC79 SDK, Docker, or an FM-1. + +```sh +python3 tools/build_preview.py +tests/run_preview_tests.sh +``` + +The build produces `build/preview/sloop-preview.wasm`. The tests compare all twelve engines sample by sample +against the same adapter compiled for the host and verify sequencing, live mixer changes, stop, and user samples. +`web/make_site.py` includes the preview and caches it for the site app when the WASM build is present: + +```sh +# Use a release package downloaded from isod89/sloop-fm1, or your own firmware build. +python3 web/make_site.py build/releases/sloop-2.6.fwsc 2.6 build/site +python3 -m http.server 8766 --bind 127.0.0.1 --directory build/site +``` + +Open `http://localhost:8766/webapp/editor/?mock=1`, **Connect**, then **Play loop** to hear all four tracks. +**Show preview** opens the piano/pads, volume and editable sequence; **Hide preview** folds them while +playback continues. The piano keys and labeled computer keys audition the selected track. +The audio controls are available only in simulated mode. The physical-device editor continues to use Web MIDI. +The standalone downloaded HTML editor does not include the WASM asset. + ## Install On Windows, `INSTALL-SLOOP.bat` builds and opens the web installer (Chrome or Edge). The diff --git a/README.md b/README.md index 586f53f..51b3ff3 100644 --- a/README.md +++ b/README.md @@ -377,6 +377,36 @@ On USB the FM-1 is also an **audio input named "Felucca"**: 44.1 or 48 kHz (2.5: 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. +**Local audio preview.** Build the browser audio engine with `python3 tools/build_preview.py` +(Emscripten required; see [BUILDING.md](BUILDING.md#browser-audio-preview)), generate and serve the local site, +then open `http://localhost:8766/webapp/editor/?mock=1`. Press **Connect** and **Play loop** +to hear the current four-track loop. Presets, sound parameters, tempo, mixer, steps, locks, FM6 patches and +uploaded samples feed the actual firmware DSP compiled to WebAssembly, running in an AudioWorklet at 44.1 kHz. +The preview starts collapsed so the sound editor stays visible. Its compact bar keeps **Play loop** and +**Stop**, plus the selected sound and its live step/note. **Show preview** opens the piano/pads, volume +and sequence; **Hide preview** folds them again while the loop keeps playing. Sound parameters remain +editable during playback in either view. +Click the notes or play **A W S E D F T G Y H U J K**; **Space** toggles the sequencer, **Stop** releases all notes, +and **Volume** adjusts browser output. **Current sequence** shows all four patterns with the actual audio +engine's playing step highlighted, independently following each track's length and division. Patterns over +16 steps follow automatically. Click a synth step to enable or disable it: re-enabling keeps its previous +notes, velocity, levels and ratchets. Double-click a synth step to open a piano picker: click a key, +use **− / +** to browse octaves, then **Apply** to change the pitch (or **Cancel** to keep it). +**Listen on click** auditions the draft through that track's instrument without saving it to the sequence. +For chords, select a member above the piano and change its pitch. An empty +step uses the new note chosen beside its track or by playing its piano. Drum rows show individual percussion sounds: click a cell to toggle +that hit while keeping the other sounds on the same step. Drums start as a compact overview of hits per +step; **Show drum grid** (or clicking an overview step) expands the editable sound rows, and **Hide drum +grid** collapses them without changing the pattern or interrupting playback. Common and programmed sounds stay visible; +**Show all 16 sounds** reveals the rest. Edits reach the playing loop through the editor protocol. +**Follow playback** and the page arrows control which 16 steps are shown; paging pauses under the pointer +or keyboard focus so a click keeps its target. **Full editor** opens the detailed sequencer (including +chords and ties). **Hide keys/pads** saves space. +The simulated device stays still until you edit it; its changes are kept +only for the current page session. This mode makes no MIDI requests and does not connect to or update an FM-1. +It previews the current project loop; the saved Song section order and hardware recording are not emulated. +Audio preview requires the served site, rather than the downloaded single-file editor. + **Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file for a computer, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup. **As an app, also on Android (2.6).** Open the [online editor](https://isod89.github.io/sloop-fm1/webapp/editor/) or the installer once with internet, then *Install the app* (under Connect, or on the installer page; or Chrome's menu → *Install app* / *Add to Home screen*). From then on the SLOOP app opens the editor without internet, and its link to the installer works offline too (with the firmware it installs). It stays the online site kept by the browser, so it uses the same sound library as the online editor, and it takes each new SLOOP version by itself the next time it opens online. On Android, use the app rather than the downloaded file: Chrome on Android does not allow MIDI in a downloaded file. diff --git a/firmware/host/preview.c b/firmware/host/preview.c new file mode 100644 index 0000000..1314f4c --- /dev/null +++ b/firmware/host/preview.c @@ -0,0 +1,165 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +/* Browser audio adapter. The DSP and clock below are the firmware sources; + * hardware inputs and user flash are replaced by RAM, never by Web MIDI. */ +#include +#include +#define memset felucca_memset +#define memcpy felucca_memcpy +#define memcmp felucca_memcmp +#include "../src/libc.c" +#undef memset +#undef memcpy +#undef memcmp +#include "felucca_tables.h" +static uint8_t user_flash[4][0x14000]; +#define SMP_USER_XIP(k) (user_flash[(k) & 3u]) +static struct { volatile uint32_t notes, buttons; } fm1_in; +static void fm1_irq_off(void) {} +static void fm1_irq_on(void) {} +#include "../src/core.h" +#include "../src/engines.c" +#include "../src/drums.c" +#include "../src/params.c" +#include "../src/voice.c" +#include "../src/slicer.c" +#include "../src/fx.c" +static void fm1_delay_ms(uint32_t ms) { (void)ms; } +#include "../src/usb.c" +#include "../src/midi_uart.c" +#include "../src/seq.c" + +static uint8_t transfer[SMP_USER_SIZE]; +static int32_t block[CTL * 2]; +static float output[CTL * 2]; + +void preview_init(void) +{ + uint32_t i, k; + memset(user_flash, 0xFF, sizeof user_flash); + for (i = 0; i < G_COUNT; i++) song.g[i] = GP[i].def; + song.g[G_SYNC] = 0; + song.master_q12 = 4096; + for (k = 0; k < NTRK; k++) { + for (i = 0; i < P_COUNT; i++) trk[k].p[i] = TP[i].def; + steps_clear(&trk[k]); + } + dsu_defaults(); + fm6_init(); +} +uint8_t *preview_buffer(void) { return transfer; } +uint32_t preview_frames(void) { return CTL; } +uint32_t preview_rate(void) { return FS; } +void preview_track(uint32_t k, uint32_t engine, uint32_t preset) +{ + if (k >= NPART || engine >= NENGINES) return; + track_t *t = &trk[k]; + if (t->eng_req != engine || t->preset != preset) sound_change(t); + t->eng_req = (uint8_t)engine; + t->preset = (uint8_t)preset; +} +void preview_param(uint32_t k, uint32_t id, int32_t value) +{ + if (k >= NTRK || id >= P_COUNT) return; + track_t *t = &trk[k]; + const param_desc_t *d = is_drum(t) && id == P_E0 ? &DRUM_KIT_DESC + : id >= P_E0 ? &ENGINES[t->eng_req % NENGINES]->edit[id - P_E0] : &TP[id]; + t->p[id] = (int16_t)clamp(value, d->min, d->max); + /* An edit made while a lock is active changes its base too. */ + for (uint32_t i = 0; i < t->lk_n; i++) + if (t->lk_param[i] == id) t->lk_base[i] = t->p[id]; +} +void preview_global(uint32_t id, int32_t value) +{ + if (id < G_COUNT && id != G_SYNC) song.g[id] = (int16_t)clamp(value, GP[id].min, GP[id].max); +} +void preview_select(uint32_t k, uint32_t solo) +{ + song.sel = (uint8_t)(k % NTRK); + song.solo = (uint8_t)(solo & 15u); +} +void preview_step(uint32_t k, uint32_t i) +{ + if (k >= NTRK || i >= NSTEP) return; + if (k == TRK_DRUM) memcpy(&trk[k].dstep[i], transfer, sizeof(dstep_t)); + else { + step_t *s = &trk[k].step[i]; + memcpy(s, transfer, sizeof *s); + s->n = (uint8_t)clamp(s->n, 0, 4); s->time %= 3u; + for (uint32_t j = 0; j < 4; j++) s->note[j] &= 127u; + s->vel &= 127u; s->flags &= 3u; + } + trk[k].micro[i] = (int8_t)clamp((int8_t)transfer[10], MICRO_MIN, MICRO_MAX); + uint32_t shift = (i & 3u) * 2u; + trk[k].fill[i / 4] = (uint8_t)((trk[k].fill[i / 4] & ~(3u << shift)) | ((transfer[11] & 3u) << shift)); +} +void preview_locks(uint32_t k, uint32_t count) +{ + if (k >= NTRK) return; + track_t *t = &trk[k]; + locks_restore(t); + for (uint32_t j = 0; j < NLOCK; j++) t->lock[j].step = LOCK_FREE; + for (uint32_t j = 0; j < count && j < NLOCK; j++) { + const uint8_t *v = transfer + j * 4; + int16_t value = (int16_t)(v[2] | (v[3] << 8)); + lock_set(t, v[0], v[1], value); + } +} +void preview_fm6(uint32_t k) +{ + if (k < NPART) { + uint8_t voice[FP_SIZE + 1u]; + fm6_unpack(transfer, voice); + fm6_set_patch(k, voice); + fm6_slot[k] = (uint8_t)trk[k].p[P_E7]; + } +} +void preview_sample(uint32_t k) +{ + if (k >= SMP_USER_SLOTS) return; + memcpy(user_flash[k], transfer, SMP_USER_SIZE); + smp_user_scan(k); +} +void preview_kit(uint32_t k) +{ + if (k >= DSU_N) return; + memcpy(&dsu.k[k], transfer, sizeof(dsu_kit_t)); + dsu.k[k].crush &= 127u; + for (uint32_t l = 0; l < DS_LANES; l++) dsu_fix_sound(&dsu.k[k].s[l]); +} +void preview_hit(uint32_t kit, uint32_t lane, uint32_t velocity) +{ + if (kit >= DSU_N || lane >= DRUM_LANES) return; + int16_t old = TDRUM->p[P_E0]; + TDRUM->p[P_E0] = (int16_t)(DRUM_SYN + kit); + drum_on(LANE_NOTE[lane], (uint8_t)clamp(velocity, 1, 127)); + TDRUM->p[P_E0] = old; +} +void preview_note(uint32_t k, uint32_t note, uint32_t on) +{ + if (k >= NTRK || note > 127) return; + if (on) input_on(&trk[k], note, 100); + else input_off(&trk[k], note); +} +void preview_play(uint32_t on) { transport_req = on ? 1 : 2; } +int32_t preview_position(uint32_t k) +{ + if (k >= NTRK || !song.playing || trk[k].seq_abs == SEQ_NONE) return -1; + return trk[k].seq_idx; +} +void preview_panic(void) +{ + transport_req = 2; + panic_req = 15; + /* ARP HOLD must also release when the browser loses focus. */ + for (uint32_t k = 0; k < NPART; k++) { + trk[k].nheld = trk[k].arp_phys = trk[k].latched = 0; + trk[k].arp_note = 0; + } +} +float *preview_render(void) +{ + fm6_poll(); + mix_block(block, CTL); + for (uint32_t i = 0; i < CTL * 2; i++) output[i] = clamp(block[i], -32768, 32767) / 32768.0f; + return output; +} diff --git a/tests/preview_native.c b/tests/preview_native.c new file mode 100644 index 0000000..2330a40 --- /dev/null +++ b/tests/preview_native.c @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +/* Same browser adapter on the host, for sample-by-sample WASM comparisons. */ +#include +#define __attribute__(x) +#include "../firmware/host/preview.c" +int main(void) +{ + int32_t config[4 + P_COUNT + G_COUNT]; + if (fread(config, sizeof config, 1, stdin) != 1) return 1; + preview_init(); + preview_render(); /* the adapter obtains its initial output buffer before syncing */ + preview_track(0, config[0], config[1]); + for (uint32_t i = 0; i < P_COUNT; i++) preview_param(0, i, config[4 + i]); + for (uint32_t i = 0; i < G_COUNT; i++) preview_global(i, config[4 + P_COUNT + i]); + if (fread(transfer, FM6_PACKED, 1, stdin) != 1) return 1; + preview_fm6(0); + preview_note(0, config[2], 1); + for (uint32_t i = 0; i < (uint32_t)config[3]; i += CTL) { + if (i == (uint32_t)config[3] / 2u) preview_note(0, config[2], 0); + if (fwrite(preview_render(), sizeof output, 1, stdout) != 1) return 1; + } + return 0; +} diff --git a/tests/preview_test.mjs b/tests/preview_test.mjs new file mode 100644 index 0000000..af31488 --- /dev/null +++ b/tests/preview_test.mjs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Real firmware audio: WASM vs the native C adapter, plus playback/edit/stop. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import vm from 'node:vm'; +import { FirmwareAudio } from '../web/preview-worklet.js'; + +const html = readFileSync('web/editor.html', 'utf8'); +const proto = html.slice(html.indexOf('/*PROTO-BEGIN*/'), html.indexOf('/*PROTO-END*/')); +const E = vm.runInNewContext(proto + ';({makeMockDevice, previewSnapshot, previewToggleStep, previewSetStepNotes, previewToggleDrum, CMD, req, frame, unframe, FM6, buildSlot})', + { setTimeout, clearTimeout, setInterval, clearInterval, console, TextEncoder, TextDecoder, Blob, Response, DecompressionStream }); +const module = await WebAssembly.compile(readFileSync('build/preview/sloop-preview.wasm')); +assert.equal(WebAssembly.Module.imports(module).length, 0, 'DSP must have no hardware or runtime imports'); +function device(options = {}) { return E.makeMockDevice({ auto: false, ...options }); } +function render(dsp, frames = 8192) { + const l = new Float32Array(frames), r = new Float32Array(frames); + dsp.render(l, r); + assert([...l, ...r].every((v) => Number.isFinite(v) && Math.abs(v) <= 1), 'finite, bounded audio'); + return { l, r, energy: l.reduce((s, x) => s + Math.abs(x), 0) + r.reduce((s, x) => s + Math.abs(x), 0) }; +} +async function request(m, [cmd, a]) { + const inp = [...m.access.inputs.values()][0], out = [...m.access.outputs.values()][0]; + return new Promise((resolve) => { inp.onmidimessage = ({data}) => resolve(E.unframe(data)); out.send(E.frame(cmd, a)); }); +} +for (let engine = 0; engine < 12; engine++) { + const m = device(); + await request(m, E.req.set(1, 20, engine)); + await request(m, E.req.preset(engine, 0)); + const state = E.previewSnapshot(m.state); + state.tracks[0].p[17] = 0; // direct note, no arp in this comparison + const dsp = new FirmwareAudio(module); dsp.sync(state); + const t = state.tracks[0], frames = 8192; + const cfg = Int32Array.from([engine, t.preset, 60, frames, ...t.p, ...state.g]); + const raw = execFileSync('build/host/preview_native', { input: Buffer.concat([Buffer.from(cfg.buffer), Buffer.from(t.fm6)]) }); + const native = new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); + dsp.w.preview_note(0, 60, 1); + const a = render(dsp, frames/2); + dsp.w.preview_note(0, 60, 0); + const b = render(dsp, frames/2); + const left = [...a.l, ...b.l], right = [...a.r, ...b.r]; + assert(a.energy + b.energy > 0.01, `engine ${engine} must sound`); + let delta = 0; + for (let i = 0; i < frames; i++) delta = Math.max(delta, Math.abs(left[i] - native[i*2]), Math.abs(right[i] - native[i*2+1])); + + assert(delta <= 1/32768, `engine ${engine}: native/WASM delta ${delta}`); + console.log(`engine ${engine}: native/WASM match (${delta})`); + m.stop(); +} +{ + const m = device(), dsp = new FirmwareAudio(module); + dsp.sync(E.previewSnapshot(m.state, true)); dsp.w.preview_play(1); + const initial = render(dsp, 44160); assert(initial.energy > 1); + // Mixer changes must affect audio while the sequence runs. + m.state.tracks.forEach(t => t.p[40] = 1); + dsp.sync(E.previewSnapshot(m.state)); render(dsp, 8192); + const muted = render(dsp, 44160); assert(muted.energy < initial.energy * 0.1); + m.state.tracks.forEach(t => t.p[40] = 0); + dsp.sync(E.previewSnapshot(m.state)); assert(render(dsp, 44160).energy > muted.energy * 2); + dsp.w.preview_panic(); render(dsp, 44160 * 4); + assert(render(dsp, 44160).energy < 0.001, 'Stop must release all notes and tails'); + // Custom ADPCM samples use RAM flash, never the hardware XIP address. + const sample = Int16Array.from({length: 4096}, (_, i) => Math.round(10000 * Math.sin(i / 16))); + const {hdr, data} = E.buildSlot('LOCAL', [{s: sample, root: 60}]); + const flash = m.state.smp[0].flash; flash.set(hdr); flash.set(data, 512); + m.state.tracks[0].engine = 4; m.state.tracks[0].p[63] = 8; m.state.tracks[0].p[17] = 0; + dsp.sync(E.previewSnapshot(m.state, true)); render(dsp, 8192); + dsp.w.preview_note(0, 60, 1); assert(render(dsp).energy > 0.01, 'uploaded sample must be audible'); + m.stop(); + console.log('sequence, live mute/unmute, stop, and uploaded samples: passed'); +} +{ + let changes = 0; + const m = device({onChange: () => { changes++; dsp.sync(E.previewSnapshot(m.state)); }}); + const dsp = new FirmwareAudio(module); dsp.sync(E.previewSnapshot(m.state)); + dsp.w.preview_play(1); const before = render(dsp, 44160); + for (let i = 0; i < 4; i++) await request(m, E.req.trackMix(i, 100, 1)); + render(dsp, 44160 * 3); + assert.equal(changes, 4); + assert(render(dsp, 44160).energy < before.energy * 0.01, 'editor protocol edits must reach the audible mixer'); + m.stop(); console.log('editor protocol -> audio thread live edits: passed'); +} +{ + // The UI follows firmware step indices, including independent DIV/LEN and nudges. + const m = device(), dsp = new FirmwareAudio(module); + const state = E.previewSnapshot(m.state); + state.g[0] = 120; state.g[1] = 0; + const lengths = [16, 7, 32, 5], divisions = [2, 1, 3, 2], denominators = [4, 2, 8, 4]; + state.tracks.forEach((t, k) => { t.p[29] = lengths[k]; t.p[30] = divisions[k]; t.p[31] = 0; t.micro.fill(0); }); + dsp.sync(state); + assert.deepEqual(dsp.transport().positions, [-1, -1, -1, -1]); + assert.equal(dsp.w.preview_position(99), -1); + dsp.w.preview_play(1); + let reachedSecondPage = false; + for (let blocks = 1; blocks <= 24; blocks++) { + render(dsp, 4096); + const lastBlock = blocks * 4096 - dsp.frames; + const expected = lengths.map((len, k) => Math.floor(lastBlock * 120 * denominators[k] / (44100 * 60)) % len); + assert.deepEqual(dsp.transport().positions, expected, 'playhead must use the clock producing the audio'); + reachedSecondPage ||= expected[2] >= 16; + } + assert(reachedSecondPage, 'long patterns must reach their second page'); + dsp.w.preview_panic(); render(dsp, dsp.frames); + assert.deepEqual(dsp.transport().positions, [-1, -1, -1, -1], 'stopped transport has no active steps'); + dsp.w.preview_play(1); render(dsp, dsp.frames); + assert.deepEqual(dsp.transport().positions, [0, 0, 0, 0], 'restart begins at the first step'); + dsp.w.preview_panic(); render(dsp, dsp.frames); + const nudged = structuredClone(state); + nudged.tracks[0].micro[0] = 16; dsp.sync(nudged); + dsp.w.preview_play(1); render(dsp, 512); + assert.equal(dsp.transport().positions[0], -1, 'a delayed first step has not fired yet'); + render(dsp, 1024); + assert.equal(dsp.transport().positions[0], 0, 'the playhead moves when the nudged step fires'); + m.stop(); console.log('audio playhead: independent lengths/divisions, paging, stop/restart, and micro timing passed'); +} +{ + const m = device({onChange: () => dsp.sync(E.previewSnapshot(m.state))}); + const dsp = new FirmwareAudio(module); dsp.sync(E.previewSnapshot(m.state)); + // A click on another track must not change selection or overwrite a chord elsewhere. + const original = JSON.stringify(m.state.tracks[0].step); + const step = m.state.tracks[1].step[0]; + const added = E.previewToggleStep(step, 67); + assert.equal(step.n, 0, 'toggle does not mutate the source'); + await request(m, E.req.trackStep(1, 0, added)); + assert.equal(m.state.sel, 0); + assert.equal(m.state.tracks[1].step[0].notes[0], 67); + assert.equal(JSON.stringify(m.state.tracks[0].step), original); + // Isolate the edited track: a new note must be audible, then removed through the same protocol. + for (const k of [0, 2, 3]) await request(m, E.req.trackMix(k, 100, 1)); + dsp.w.preview_play(1); assert(render(dsp, 44160).energy > 0.01, 'inline note sounds in the loop'); + await request(m, E.req.trackStep(1, 0, E.previewToggleStep(m.state.tracks[1].step[0], 67))); + dsp.w.preview_panic(); render(dsp, 44160 * 4); dsp.w.preview_play(1); + assert(render(dsp, 44160).energy < 0.001, 'removed note leaves a silent loop'); + await request(m, E.req.trackStep(1, 0, E.previewToggleStep(m.state.tracks[1].step[0], 60))); + assert.equal(m.state.tracks[1].step[0].notes[0], 67, 'reactivation restores G4 instead of the default C4'); + assert.equal(m.state.tracks[1].step[0].time, 0); + dsp.w.preview_panic(); render(dsp, 44160 * 4); dsp.w.preview_play(1); + assert(render(dsp, 44160).energy > 0.01, 'restored note is audible'); + const chord = { n: 3, notes: [45, 52, 57, 0], time: 0, flags: 3, vel: 84, lvl: 57, rat: 36 }; + assert.equal(E.previewToggleStep({...chord, time: 1}, 60).time, 2, 'a tie with stored pitches is disabled rather than retriggered'); + await request(m, E.req.trackStep(0, 0, chord)); + await request(m, E.req.trackStep(0, 0, E.previewToggleStep(m.state.tracks[0].step[0], 60))); + assert.equal(m.state.tracks[0].step[0].time, 2); + await request(m, E.req.trackStep(0, 0, E.previewToggleStep(m.state.tracks[0].step[0], 60))); + assert.equal(JSON.stringify(m.state.tracks[0].step[0]), JSON.stringify(chord), 'toggle preserves chords, velocity, flags, levels and ratchets'); + const edited = E.previewSetStepNotes(m.state.tracks[0].step[0], [48, 55, 60]); + await request(m, E.req.trackStep(0, 0, edited)); + assert.equal(m.state.tracks[0].step[0].notes.join(','), '48,55,60,0'); + assert.equal(m.state.tracks[0].step[0].vel, 84); + assert.equal(m.state.tracks[0].step[0].lvl, 57); + assert.equal(chord.notes[0], 45, 'editing does not mutate the original chord'); + // Toggling one lane preserves the other 15 lanes, including their levels and ratchets. + const dr = {on: (1 << 2) | (1 << 4), lvl: new Array(16).fill(0), rat: new Array(16).fill(0)}; + dr.lvl[2] = 3; dr.rat[2] = 2; dr.lvl[4] = 1; + await request(m, E.req.drumStep(0, dr)); + const before = JSON.stringify(m.state.tracks[3].dstep[0]); + await request(m, E.req.drumStep(0, E.previewToggleDrum(m.state.tracks[3].dstep[0], 0))); + const after = m.state.tracks[3].dstep[0]; + assert(after.on & 1); assert.equal(after.lvl[2], 3); assert.equal(after.rat[2], 2); assert.equal(after.lvl[4], 1); + await request(m, E.req.drumStep(0, E.previewToggleDrum(after, 0))); + assert.equal(JSON.stringify(m.state.tracks[3].dstep[0]), before, 'two drum clicks restore the same step'); + assert.equal(m.state.sel, 0); + m.stop(); console.log('inline edits: add/remove audible notes, independent tracks, and preserved drum lanes passed'); +} +console.log('preview audio tests passed'); diff --git a/tests/run_preview_tests.sh b/tests/run_preview_tests.sh new file mode 100755 index 0000000..b394bcb --- /dev/null +++ b/tests/run_preview_tests.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-only +# Run after python3 tools/build_preview.py; no FM-1 or JieLi SDK required. +set -eu +cd "$(dirname "$0")/.." +[ -f build/preview/sloop-preview.wasm ] || { echo 'Run python3 tools/build_preview.py first'; exit 1; } +mkdir -p build/host +"${CC:-cc}" -O2 -fwrapv -fno-strict-aliasing -w -Ibuild/gen -Ifirmware/src tests/preview_native.c -o build/host/preview_native +node tests/preview_test.mjs diff --git a/tools/build_preview.py b/tools/build_preview.py new file mode 100644 index 0000000..aa00be1 --- /dev/null +++ b/tools/build_preview.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Compile the real SLOOP DSP/clock for browser preview (requires emcc). + +python3 tools/build_preview.py +Then web/make_site.py includes the generated audio assets in the local site. +No JieLi SDK, Docker, or connected FM-1 is required. +""" +from pathlib import Path +import shutil +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] +GEN = ROOT / 'build/gen' +OUT = ROOT / 'build/preview' + + +def main(): + if not shutil.which('emcc'): + sys.exit('Install Emscripten first (macOS: brew install emscripten).') + GEN.mkdir(parents=True, exist_ok=True) + OUT.mkdir(parents=True, exist_ok=True) + for script, header in [('gen_tables.py', 'felucca_tables.h'), ('gen_samples.py', 'felucca_samples.h'), + ('gen_drumkits.py', 'felucca_drumkits.h'), ('gen_fm6_patches.py', 'felucca_fm6.h')]: + subprocess.run([sys.executable, str(ROOT / 'tools' / script), str(GEN / header)], cwd=ROOT, check=True) + exports = ['init', 'buffer', 'frames', 'rate', 'track', 'param', 'global', 'select', 'step', 'locks', + 'fm6', 'sample', 'kit', 'hit', 'note', 'play', 'position', 'panic', 'render'] + subprocess.run(['emcc', str(ROOT / 'firmware/host/preview.c'), '-O2', '-fwrapv', '-fno-strict-aliasing', + '-Wno-unused-function', '-Wno-int-to-pointer-cast', '-I' + str(GEN), '-I' + str(ROOT / 'firmware/src'), + '--no-entry', '-sSTANDALONE_WASM=1', '-sFILESYSTEM=0', '-sINITIAL_MEMORY=16777216', + '-sSTACK_SIZE=131072', '-sEXPORTED_FUNCTIONS=' + str(['_preview_' + n for n in exports]), + '-o', str(OUT / 'sloop-preview.wasm')], cwd=ROOT, check=True) + for name in ['preview.js', 'preview-worklet.js']: + shutil.copy(ROOT / 'web' / name, OUT / name) + print('Browser audio built:', OUT / 'sloop-preview.wasm') + + +if __name__ == '__main__': + main() diff --git a/web/editor.html b/web/editor.html index 5c27624..25c7d55 100644 --- a/web/editor.html +++ b/web/editor.html @@ -107,6 +107,141 @@ #version { color: var(--fg2); overflow-wrap: anywhere; } #live, #mock { color: var(--dim); } #connect { width: 100%; } + .preview { border-bottom: 1px solid var(--line); padding: 16px 0; margin-bottom: 16px; } + .preview > * { max-width: 848px; } + .preview-toolbar, .preview-instrument, .preview-footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; } + .preview-transport, .preview-volume, .preview-output, .preview-octaves { display: flex; align-items: center; gap: 8px; } + .preview-transport { flex-wrap: wrap; } + .preview-transport button { min-height: 36px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; } + .preview svg { width: 16px; height: 16px; flex: none; fill: currentColor; } + .preview-summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fg2); } + #preview-disclosure { color: var(--dim); background: none; padding: 4px 0; text-transform: none; } + #preview-disclosure:hover { color: var(--fg); } + .preview[data-expanded="false"] .preview-toolbar { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 12px; } + #preview-enable { color: var(--fg2); background: none; border: 1px solid var(--s3); } + #preview-enable[aria-pressed="true"] { border-color: var(--trk); color: var(--fg); } + #preview-enable:disabled { color: var(--dim); border-color: var(--line); } + #preview-play { min-width: 112px; color: var(--trk); border: 1px solid var(--trk); } + #preview-play:disabled { color: var(--dim); border-color: var(--line); } + #preview-play[aria-pressed="true"] { background: var(--trk); color: #000; } + .preview-volume { flex-wrap: wrap; } + .preview-volume label { display: flex; align-items: center; gap: 8px; } + #preview-volume { width: 112px; } + #preview-volume-value { min-width: 4ch; text-align: right; color: var(--fg); } + .preview-output { color: var(--dim); border-left: 1px solid var(--line); padding-left: 12px; } + #preview-meter { appearance: none; width: 64px; height: 8px; border: 0; background: var(--s2); } + #preview-meter::-webkit-meter-bar { border: 0; border-radius: 0; background: var(--s2); height: 8px; } + #preview-meter::-webkit-meter-optimum-value { background: var(--t2); } + #preview-meter::-moz-meter-bar { background: var(--t2); } + .preview-instrument { margin: 12px 0 8px; } + .preview-instrument-actions { display: flex; align-items: center; gap: 12px; } + #preview-fold { background: none; padding: 4px 0; color: var(--dim); text-decoration: underline; } + #preview-fold:hover { color: var(--fg); } + #preview-sound { color: var(--dim); margin-left: 8px; } + #preview-instrument { color: var(--fg); } + #preview-octave { min-width: 5ch; text-align: center; } + .preview-octaves button { width: 32px; height: 32px; padding: 0; } + .preview-keys { position: relative; width: 100%; } + .preview-keys button { touch-action: none; user-select: none; text-transform: none; padding: 8px; } + .preview-keys kbd { font: inherit; color: var(--dim); } + .preview-keys.piano { display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); gap: 2px; height: 96px; } + .piano .white-key { height: 96px; display: flex; flex-direction: column; justify-content: flex-end; gap: 4px; align-items: center; background: var(--fg2); color: var(--bg); border-bottom: 3px solid var(--dim); } + .piano .white-key:hover:not(:disabled) { background: var(--fg); } + .piano .white-key kbd { color: var(--s3); } + .piano .black-key { position: absolute; z-index: 1; left: calc(var(--key) * 12.5% - 3.75%); width: 7.5%; height: 56px; display: flex; flex-direction: column; align-items: center; justify-content: space-between; background: var(--s1); color: var(--fg); border: 1px solid var(--s3); border-bottom-width: 3px; padding: 4px; } + .preview-keys.pads { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; max-width: 480px; } + .pads button { min-width: 0; height: 48px; display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 8px; border: 1px solid var(--s3); white-space: normal; text-align: left; line-height: 16px; } + .pads button kbd { border: 1px solid var(--s3); min-width: 20px; text-align: center; } + .preview-keys button[aria-pressed="true"], .preview-keys button[aria-pressed="true"]:hover { background: var(--trk); color: #000; border-color: var(--trk); } + .preview-keys button[aria-pressed="true"] kbd { color: #000; } + .preview-keys button:disabled { background: var(--s2); color: var(--dim); border-color: var(--line); } + .preview-footer { margin-top: 12px; color: var(--dim); align-items: baseline; } + .preview-footer .preview-help { white-space: nowrap; } + #preview-status[data-error="true"] { color: var(--red); } + .preview-footer kbd { font: inherit; color: var(--fg2); border: 1px solid var(--s3); padding: 0 4px; } + .preview-sequence { grid-column: 1 / 3; margin-top: 12px; border-top: 1px solid var(--line); padding-top: 8px; } + .preview-seq-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin-bottom: 8px; } + .preview-seq-head > span { margin-right: auto; } + .preview-seq-head label { color: var(--dim); } + #preview-edit { background: none; color: var(--dim); text-decoration: underline; padding: 0; } + #preview-edit:hover { color: var(--fg); } + .preview-seq-row { display: grid; grid-template-columns: 128px minmax(0, 1fr); gap: 8px; margin-top: 4px; } + .preview-seq-label { min-width: 0; } + .preview-seq-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-bottom: 4px; } + .preview-seq-tools select { width: 64px; min-width: 0; padding: 0 4px; height: 24px; } + .preview-seq-tools button { padding: 0; width: 24px; height: 24px; } + .preview-seq-pages { color: var(--dim); font-size: 12px; white-space: nowrap; } + .preview-seq-row > .preview-seq-steps { align-self: center; } + .preview-seq-drums { margin-top: 8px; border-top: 1px solid var(--line); padding-top: 4px; } + .preview-seq-drumhead { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; } + .preview-seq-drumhead > .seq-all-drums { padding: 0; background: none; color: var(--dim); text-decoration: underline; margin-left: auto; } + .seq-drum-toggle { padding: 0; max-width: 100%; white-space: normal; background: none; color: var(--c); text-align: left; text-transform: none; } + .seq-drum-toggle:hover:not(:disabled) { background: none; color: var(--fg); } + .seq-drum-toggle:focus-visible { outline: 1px solid var(--c); outline-offset: 2px; } + .seq-drum-brief.on { color: var(--c); } + .preview-seq-lane { color: var(--fg2); align-self: center; padding-left: 24px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .preview-seq-numbers { color: var(--dim); text-align: center; font-size: 12px; } + .preview-seq-track { display: flex; align-items: center; gap: 4px; padding: 0; min-width: 0; width: 100%; height: 28px; color: var(--c); background: none; text-align: left; text-transform: none; } + .preview-seq-track[aria-pressed="true"] { background: var(--s2); } + .preview-seq-track .seq-name { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: var(--fg2); } + .preview-seq-track .seq-no { width: 24px; flex: none; text-align: center; } + .preview-seq-track .seq-position { flex: none; margin-left: auto; color: var(--dim); padding-right: 4px; font-size: 12px; white-space: nowrap; } + .preview-seq-steps { display: grid; grid-template-columns: repeat(16, minmax(0, 1fr)); gap: 2px; } + .preview-seq-cell { display: flex; align-items: center; justify-content: center; height: 28px; padding: 0; border: 1px solid var(--line); background: var(--s1); color: var(--dim); overflow: hidden; } + .preview-seq-cell:hover:not(:disabled) { border-color: var(--c); background: var(--s3); } + .preview-seq-cell:focus-visible { outline: 2px solid var(--c); outline-offset: 1px; } + .preview-seq-cell.on { background: var(--s2); color: var(--c); border-color: var(--s3); } + .preview-seq-cell.bar-start { border-left-color: var(--s3); } + .preview-seq-cell.is-current { color: var(--c); border-color: var(--c); } + .preview-seq-cell.on.is-current { background: var(--c); color: #000; } + .preview-seq-cell.unused { visibility: hidden; } + .preview-seq-row.is-muted .preview-seq-steps { opacity: .4; } + .preview-seq-cell .seq-hit { display: none; width: 4px; height: 12px; background: currentColor; } + .preview-seq-legend { color: var(--dim); margin: 6px 0 0; } + #preview-note-dialog { font: inherit; color: var(--fg); background: var(--bg); border: 1px solid var(--s3); padding: 20px; width: 520px; max-width: calc(100vw - 32px); } + #preview-note-dialog::backdrop { background: var(--bg); opacity: .7; } + #preview-note-title { font-size: 16px; line-height: 24px; margin: 0 0 16px; color: var(--c); } + .preview-note-chord { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 12px; } + .preview-note-chord button { padding: 4px 8px; } + .preview-note-chord button[aria-pressed="true"] { color: var(--bg); background: var(--c); } + .preview-note-picker-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; } + #preview-note-value { color: var(--c); } + .preview-note-octave { display: flex; align-items: center; gap: 8px; } + .preview-note-octave button { padding: 0; width: 32px; height: 32px; } + .preview-note-piano.preview-keys.piano { grid-template-columns: repeat(7, minmax(0, 1fr)); height: 120px; } + .preview-note-piano .white-key { height: 120px; } + .preview-note-piano .black-key { left: calc(var(--key) * 14.285714% - 4.3%); width: 8.6%; height: 72px; padding: 4px 0; } + .preview-note-listen { display: flex; align-items: center; gap: 8px; color: var(--dim); margin-top: 12px; } + .preview-note-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 20px; } + @media (min-width: 1100px) { + .preview[data-instrument="drums"][data-expanded="true"] { display: grid; grid-template-columns: minmax(0, 480px) minmax(0, 344px); column-gap: 24px; } + .preview[data-instrument="drums"][data-expanded="true"] .preview-instrument { grid-column: 1; grid-row: 1; margin-top: 0; } + .preview[data-instrument="drums"][data-expanded="true"] .preview-keys { grid-column: 1; grid-row: 2; } + .preview[data-instrument="drums"][data-expanded="true"] .preview-toolbar { grid-column: 2; grid-row: 1 / 3; flex-direction: column; align-items: flex-start; justify-content: flex-start; gap: 16px; } + .preview[data-instrument="drums"][data-expanded="true"] .preview-volume { flex-direction: column; align-items: flex-start; gap: 12px; } + .preview[data-instrument="drums"][data-expanded="true"] .preview-output { border: 0; padding-left: 0; } + .preview[data-instrument="drums"][data-expanded="true"] .preview-footer { grid-column: 1 / 3; } + } + @media (max-width: 1150px) { + .preview-volume { width: 100%; justify-content: space-between; } + } + @media (max-width: 680px) { + .preview[data-expanded="false"] .preview-toolbar { grid-template-columns: 1fr auto; gap: 8px; } + .preview[data-expanded="false"] .preview-summary { grid-column: 1 / 3; grid-row: 2; } + .preview-toolbar { align-items: flex-start; } + .preview-volume { width: 100%; justify-content: space-between; } + .preview-keys.pads { grid-template-columns: repeat(4, minmax(0, 1fr)); } + .pads button { height: 64px; display: flex; flex-direction: column; align-items: flex-start; justify-content: space-between; gap: 4px; } + .preview-footer { gap: 4px; } + .preview-seq-row { grid-template-columns: 72px minmax(0, 1fr); gap: 4px; } + .preview-seq-tools { flex-wrap: wrap; } + .preview-seq-tools select { width: 72px; } + .preview-seq-lane { padding-left: 0; font-size: 12px; } + .preview-seq-track { gap: 0; } + .preview-seq-track .seq-name { display: none; } + .preview-seq-note { display: none; } + .preview-seq-cell.on .seq-hit { display: block; } + } .devcard .links { display: flex; justify-content: space-between; gap: 8px; } .lang { background: none; color: var(--dim); padding: 0; text-decoration: underline; text-transform: none; } .lang:hover:not(:disabled) { background: none; color: var(--fg); } @@ -482,6 +617,42 @@ +