diff --git a/changelog/2026-11-30-digitakt-ii-fx-slot.md b/changelog/2026-11-30-digitakt-ii-fx-slot.md new file mode 100644 index 0000000000..9d3c5b9d31 --- /dev/null +++ b/changelog/2026-11-30-digitakt-ii-fx-slot.md @@ -0,0 +1 @@ +SDK, Digitakt II base: effect modules get a shared slot. Up to eight effects run side by side on the sound chip as track inserts before the stock sends, through the new `core_fx` table, and one FX page in the Mixer, after COMP, lights each effect's tracks with the TRIG keys and sets its values with knobs A-H; the project saves them. `ev_audio_frame` subscribers now only read the transfer, and the build refuses a module that writes it. diff --git a/docs/verification/2026-11-25-digitakt-ii-fx-slot.md b/docs/verification/2026-11-25-digitakt-ii-fx-slot.md old mode 100755 new mode 100644 index f9c743bc6d..6d9d0ab0bc --- a/docs/verification/2026-11-25-digitakt-ii-fx-slot.md +++ b/docs/verification/2026-11-25-digitakt-ii-fx-slot.md @@ -103,3 +103,13 @@ Only Sidechain Comp (`digitakt-ii/dt2-sidechain`, the developer's own module, no 1. Builder tests with the owner's OS (`MODWERK_DT2_STOCK`): no effect leaves section 7 stock. Two test effects build through the same base code bytes, with only slots and records differing. A set over the budget, a ninth effect, or code outside a package's own allocation is refused. 2. Emulator, coupled ColdFire and sound chip. First, before the rest of the FX page code: ten Mixer pages (stock, FX and four module pages) navigate both ways and draw. The stock OS has only been seen with nine; if it has a fixed limit, the FX page needs another home and the design changes. Then, generated 220 Hz tone on T1 as in the earlier records: the dispatcher with no track lit gives PCM byte-identical to stock. A test effect halving T1 gives -6.02 dB on T1 only. Sidechain Comp through the slot matches its 18 November results. The FX page draws, takes TRIG and knob input, and survives a project save and reload. 3. Unit, OS 1.17, exact image named by SHA-256: boot and playback with nothing lit, the test effect on one track and not another, Sidechain Comp's existing checks, settings after Save Project, reload and a power cycle, and a cycle count with all slots busy. + +## Results of the base code (29-30 November 2026) + +A private test effect, FX Probe (one value, GAIN 0-127, scaling its lit tracks by GAIN/128, cost 4,000), stood in for a real effect. It never enters the repository. + +- **Builder:** 79 builder, preflight and assembler tests pass with the owner's OS. Two effects build with the same dispatcher and mailbox bytes as one; a ninth effect, a record without routines, routines without a record, two effects in one module and a set over 60,000 are refused. +- **Emulator, ten Mixer pages:** with the FX page and four test module pages, FUNC + MOD steps through all ten and wraps to COMP, and each draws. The FX page keeps its place after COMP. +- **Emulator, sound:** 220 Hz tone on T1 and T2. FX Probe on T1 at 64: T1 x0.5000 (-6.02 dB), T2 sample-identical to stock. Lit through the FX page (TRIG 1, knob A): T1 x0.4998 and T2 x0.9996 of stock, within about 0.004 dB; not sample-exact, most likely from alignment between the two runs, not proven. The busiest stock moment (all sixteen TRIG keys, FX knobs up) measured 342,016 busy instructions a block before the slot; the probe on one track added about 6,000 in the emulator. +- **Unit, OS 1.17, image `3a3a37c22cb65d13764d238f7dd3c73aff6cd1492b0f5f76d959fa619ca10164`** (base `22a85ada`, FX Probe `153b44f7`), run by Claptom-music on 30 November 2026, all passed: playback unchanged with nothing lit; FUNC + MOD shows the FX page after COMP with FX PROBE and GAIN 64; TRIG 1 lights T1, which then plays at about half volume while T2 is unchanged; knob A follows from silent to full; TRIG 1 again restores T1; T1's light and GAIN survive Save Project and a power cycle; the stock reverb and delay sends take the quieter T1; FUNC + MOD steps through every Mixer page back to COMP. +- **Not done yet:** Sidechain Comp through the slot (it still uses its own path and moves in its own change), the no-track-lit byte comparison against stock, and a cycle count on the unit with all eight slots busy, which sets the budget again before the base ships. diff --git a/scripts/build-elemod-packages.mjs b/scripts/build-elemod-packages.mjs index d0da445860..bd5544a064 100644 --- a/scripts/build-elemod-packages.mjs +++ b/scripts/build-elemod-packages.mjs @@ -149,15 +149,24 @@ for (const machine of machines.filter(item => item.sdk?.platform === 'elemod')) for (const target of sites.flatMap(site => 'target' in site ? [site.target] : (site.relocs ?? []).map(reloc => reloc.target))) if (!Object.hasOwn(module.symbols, target) && !module.imports.includes(target)) module.imports.push(target) module.imports.sort() if (build.sharc) { - // A Digitakt II machine module's sound-chip player, assembled from its source; the site composes it into section 7. - if (machine.id !== 'digitakt-ii') throw new Error('Only Digitakt II modules carry a sound-chip player: ' + document.id) + // A Digitakt II module's sound-chip part (a machine's player or an effect's routines), assembled from its source; the + // site composes it into section 7. + if (machine.id !== 'digitakt-ii') throw new Error('Only Digitakt II modules carry a sound-chip part: ' + document.id) const program = assembleSharc(await readFile(await resolveModuleFile(folder, build.sharc.source), 'utf8')) const players = build.sharc.players.map(player => { const entry = program.symbols.get(player.entry) if (entry === undefined) throw new Error(document.id + ': no label ' + player.entry + ' in ' + build.sharc.source) return { type: player.type, entry } }) - module.build = { ...module.build, dt2_sharc: { version: 2, allocations: program.blocks.map(block => ({ address: block.address, data: Buffer.from(block.bytes).toString('base64'), code: block.code })), players } } + const label = name => { + const at = program.symbols.get(name) + if (at === undefined) throw new Error(document.id + ': no label ' + name + ' in ' + build.sharc.source) + return at + } + // An effect's routines for the base's effect slot (docs/verification/2026-11-25-digitakt-ii-fx-slot.md). + const fx = build.sharc.fx && { ...(build.sharc.fx.listen ? { listen: label(build.sharc.fx.listen) } : {}), + ...(build.sharc.fx.process ? { process: label(build.sharc.fx.process) } : {}), cost: build.sharc.fx.cost } + module.build = { ...module.build, dt2_sharc: { version: 2, allocations: program.blocks.map(block => ({ address: block.address, data: Buffer.from(block.bytes).toString('base64'), code: block.code })), players, ...(fx ? { fx } : {}) } } } parseElemod(module) const plan = { schemaVersion: 1, machine: machine.id, id: document.id, version: document.version, release, module, sites, derive: build.derive, diff --git a/sdk/digitakt-ii/core-profile/interface.json b/sdk/digitakt-ii/core-profile/interface.json index 85c2d956f2..3adafe6bfd 100644 --- a/sdk/digitakt-ii/core-profile/interface.json +++ b/sdk/digitakt-ii/core-profile/interface.json @@ -80,7 +80,7 @@ "handler": "void f(unsigned int data_bytes, const void *data, unsigned int frame_bytes, const void *reply)", "order": "lower subscription order first; linker breaks ties by module ID and contribution order", "room": 4, - "purpose": "The arguments are the original stock transfer arguments and are borrowed for this call. A subscriber may update its own preallocated state and its explicitly reserved DSP frame-tail data words only. Preserve stock data, command words and reply storage. Do not allocate, block or retain the pointers." + "purpose": "The arguments are the original stock transfer arguments and are borrowed for this call. A subscriber may read them and update its own preallocated state only: it writes no word of the transfer, whose tail is the base's (machine wire and effect mailbox). A module sends data to the sound chip through core_fx_set; the preflight refuses a module that names the transfer's queue pointer (0x400cd48c). Do not allocate, block or retain the pointers." } ], "tables": [ @@ -163,6 +163,13 @@ "entry": 4, "room": 4, "purpose": "Null-terminated pointers to struct dt2_machine records (mk2/machines.h): track machines added after the seven stock types, each with its own machine type 7-10 (claimed as machine:, saved with kits), the stock type it stands for, its names and its five knob names on the stand-in's parameters. The base lists them in the machine menu, keeps them through kit load, shows their knob names while a page shows that machine and, when the module's package carries a build.sharc player, sends their voices to it on the sound chip through that type's registry slot; without one they play as the stock type they stand for." + }, + { + "name": "core_fx", + "since": "1.1", + "entry": 4, + "room": 8, + "purpose": "Null-terminated pointers to struct dt2_fx records (mk2/fx.h): the effects on the sound chip, one per module, in the order band of their kind (10-39 tone and drive, 40-69 time, 70-99 dynamics). An entry's place in the table is its slot. At the pre-send render site, before the stock sends, the base calls each slot's listen routine, then each process routine, of the module's package build.sharc.fx, with I4 at the slot's sixteen settings words (0-14 the effect's, 15 its track mask), and skips a slot whose mask is 0. The base's FX page in the Mixer, after COMP, lists every effect without DT2_FX_OWN_PAGE: the TRIG keys light its tracks and knobs A-H set its values. The base saves the values and tracks with the project, by tag. The builder refuses a ninth effect and a set whose declared costs pass 60,000 instructions a block." } ], "exports": [ @@ -213,6 +220,24 @@ "prototype": "volatile uint32_t core_machine_sample_views (mk2/machines.h)", "purpose": "Counts the SRC page's sample view as it draws: it changes in every frame composed while the second page shows and in no other, so an ev_draw handler that sees it changed since its last call may draw over the sample view of the current track. Read-only." }, + { + "name": "core_fx_slot", + "since": "1.1", + "prototype": "int core_fx_slot(const struct dt2_fx *fx) (mk2/fx.h)", + "purpose": "The slot of an effect's own record in core_fx, or -1 when it is not there." + }, + { + "name": "core_fx_set", + "since": "1.1", + "prototype": "void core_fx_set(unsigned int slot, unsigned int index, uint32_t value) (mk2/fx.h)", + "purpose": "Sets settings word index (0-14, or DT2_FX_TRACKS for the track mask) of the module's own slot on the sound chip, from the UI task. The base sends changes first, then every word in turn in the transfer's tail, so the sound chip catches up after a load. The FX page sets the values and the mask of the effects it shows; an effect with DT2_FX_OWN_PAGE sets its own." + }, + { + "name": "core_fx_get", + "since": "1.1", + "prototype": "uint32_t core_fx_get(unsigned int slot, unsigned int index) (mk2/fx.h)", + "purpose": "The value core_fx_set last set for that word (0 before any). Read-only." + }, { "name": "core_store_conflicts", "since": "1.1", diff --git a/sdk/machines/digitakt-ii/README.md b/sdk/machines/digitakt-ii/README.md index 0278a6cb79..b920042327 100644 --- a/sdk/machines/digitakt-ii/README.md +++ b/sdk/machines/digitakt-ii/README.md @@ -41,9 +41,9 @@ By the core's documentation (emulator-tested, not hardware-tested), both data ar **Linked voices are the base's.** SETTINGS > VOICES lets a lead track play its notes on the tracks after it, for every machine, stock or added ([VOICES.md](elekloader/modwerk/VOICES.md)). A machine module that wants polyphony relies on it and never allocates voices across tracks itself; a voice track plays its lead's machine, and the machine wire gives it the lead's type. -The Digitakt II core does not start DTIM0 and exposes no audio-render hook yet ([proposal and emulator measurements](../../../docs/verification/2026-11-10-digitakt-ii-pre-send-render.md)). Audio is rendered by the separate SHARC DSP; these hooks are not sample-accurate. +The Digitakt II core does not start DTIM0 and exposes no audio-render hook; the base's effect slot below is the way in ([proposal and emulator measurements](../../../docs/verification/2026-11-10-digitakt-ii-pre-send-render.md)). Audio is rendered by the separate SHARC DSP; these hooks are not sample-accurate. The [guarded render probe](../../../docs/verification/2026-11-14-digitakt-ii-render-probe.md) records the local OS 1.17 build and dispatcher test. -**Effects wait for the base's effect slot.** An effect module (delay, reverb, drive) does not patch the render site: the [effect slot proposal](../../../docs/verification/2026-11-25-digitakt-ii-fx-slot.md) gives every effect, Sidechain Comp included, a slot in the base table `core_fx` with track inserts before the stock sends and one shared FX page in the Mixer. The owner approved its design on 26 November 2026; the base code follows. +**Effects take a slot in the base's `core_fx`.** An effect module (delay, reverb, drive) never patches the render site or writes the transfer to the sound chip. It contributes a `struct dt2_fx` record (`mk2/fx.h`) to `core_fx` and names its sound-chip routines and worst-case cost in `build.sharc.fx` (`{ "listen": "label", "process": "label", "cost": 4000 }`). The base calls them as track inserts before the stock sends, and its FX page (Mixer, after COMP) lights tracks and sets up to eight values for every effect ([design](../../../docs/verification/2026-11-25-digitakt-ii-fx-slot.md)). A routine starts with `I4` at its slot's sixteen settings words (word 15 is the track mask, bit t for track t + 1) and processes track t's 32 left and 32 right floats at `0x252df8 + 0x100 * t`. It may change R0-R15, I0-I2, I4, M4-M6 and L0-L2, keeps every other register, and returns with `RTS`. Effects, machine players and filters share one budget of 60,000 instructions a block, each counted over the stock work it replaces. **Filters wait for the base's filter types.** A filter module does not patch the per-voice filter on the sound chip: the [filter-type proposal](../../../docs/verification/2026-11-25-digitakt-ii-filter-types.md) lists module filters after the stock types on the FLTR page (base table `core_filters`), each standing in for a stock type's knobs and movement. The owner approved its design on 25 November 2026; the base code follows. The proposed Mixer and frame interfaces are declared in [core-profile/interface.json](../../digitakt-ii/core-profile/interface.json). @@ -51,7 +51,8 @@ The proposed Mixer and frame interfaces are declared in [core-profile/interface. | Interface | Timing, order and room | Arguments and permitted writes | | --- | --- | --- | | `core_mixer_pages` | The UI reads the collection when building the Mixer cycle and draws the active registered page. Up to four entries follow COMP, lowest contribution order first. Ties use module ID and contribution order. | Each entry points to a native page descriptor and `void draw(void *view, void *bitmap)`. Draw into the supplied bitmap and update module-owned state. The borrowed view and stock navigation state are read-only. | -| `ev_audio_frame` | ColdFire calls up to four handlers immediately before the stock DSP transfer. Lower subscription order runs first. Ties use module ID and contribution order. | `void f(unsigned int data_bytes, const void *data, unsigned int frame_bytes, const void *reply)` receives the stock transfer arguments. Write only module-owned state and explicitly reserved DSP frame-tail data words. Preserve stock data, commands and reply storage. The pointers are valid for the call. Keep the callback allocation-free and nonblocking. | +| `core_fx` | Up to eight effects; an effect's slot is its place in the table, lowest contribution order first (10-39 tone and drive, 40-69 time, 70-99 dynamics). The sound chip runs every listen routine, then every process routine, at the pre-send render site, and skips a slot with no track lit. | A `struct dt2_fx` record: tag, name, flags and up to eight values `{name, max, initial}`. Call `core_fx_set(slot, index, value)` and `core_fx_get` from the UI task. `DT2_FX_OWN_PAGE` keeps an effect off the FX page so it can draw its own pages. The base saves values and tracks with the project. | +| `ev_audio_frame` | ColdFire calls up to four handlers immediately before the stock DSP transfer. Lower subscription order runs first. Ties use module ID and contribution order. | `void f(unsigned int data_bytes, const void *data, unsigned int frame_bytes, const void *reply)` receives the stock transfer arguments. Read them and write only module-owned state: the transfer's tail is the base's, so send data to the sound chip through `core_fx_set`. The preflight refuses a module that names the transfer's queue pointer. The pointers are valid for the call. Keep the callback allocation-free and nonblocking. | Find a screen from the frame the OS has just drawn, not from UI object pointers: digikit fills some that stay 0 on the unit (the view controller's page set at `+0x9c` on OS 1.17), so a mod that follows them works in the emulator and never on hardware. [Track Names](../../digitakt-ii/modules/track-names/) recognises the mixer this way. diff --git a/sdk/machines/digitakt-ii/elekloader/base.json b/sdk/machines/digitakt-ii/elekloader/base.json index cf361633d5..b8b7329786 100644 --- a/sdk/machines/digitakt-ii/elekloader/base.json +++ b/sdk/machines/digitakt-ii/elekloader/base.json @@ -45,6 +45,8 @@ "../modwerk/project-archive.c", "../modwerk/project-kitdata.c", "../modwerk/mixer.c", + "../modwerk/fx-page.c", + "../modwerk/fx.c", "../modwerk/mixer-entry.s", "../modwerk/machines.c", "../modwerk/machine-knobs.c", @@ -59,6 +61,21 @@ "event": "ev_settings", "fn": "core_voice_settings", "order": 10 + }, + { + "event": "ev_draw", + "fn": "core_fx_page_after_draw", + "order": 10 + }, + { + "event": "ev_enc", + "fn": "core_fx_page_enc", + "order": 10 + }, + { + "event": "ev_key", + "fn": "core_fx_page_key", + "order": 10 } ], "contribute": [ @@ -74,6 +91,19 @@ 0 ] ] + }, + { + "to": "core_project_archive", + "order": 20, + "data": "00000000", + "relocs": [ + [ + 0, + "abs32", + "sym:core_fx_archive", + 0 + ] + ] } ], "defsym": { @@ -339,7 +369,8 @@ "core_mixer_pages": 4, "ev_audio_frame": 4, "core_project_archive": 4, - "core_machines": 4 + "core_machines": 4, + "core_fx": 4 } }, "dev": { diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/fx-page.c b/sdk/machines/digitakt-ii/elekloader/modwerk/fx-page.c new file mode 100755 index 0000000000..b38d7723ae --- /dev/null +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/fx-page.c @@ -0,0 +1,194 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* The base's FX page in the Mixer (OS 1.17): page DT2_MIXER_FX_PAGE, after COMP and before the modules' pages, shown + * while core_fx holds an effect that has no page of its own (docs/verification/2026-11-25-digitakt-ii-fx-slot.md). + * It takes none of core_mixer_pages' entries. + * + * On the page: UP and DOWN choose the effect, a TRIG key switches it on or off for that track, knobs A-H set its values + * (twelve encoder counts a step, as Sidechain's page). Each change goes to the sound chip through core_fx_set, and the + * project saves it (fx.c). Key and knob events reach the stock OS unchanged while the page is not on screen. */ +#include +#include +#include +#include + +#define MIXER_PAGE_FRAME 0x4006b0b0u /* draws the Mixer page's frame and level strip, as for the stock pages */ +#define KEY_EVENT_DOWN 0x40114a28u /* (event): low byte 1 for a key-down event (Mute Latch's MLK_EV_DOWN) */ +#define EVENT_CODE 12u /* u32 in a key event: the panel key; in an encoder event: the knob, 1-8 */ +#define EVENT_DELTA 16u /* s32 in an encoder event: the counts turned */ +#define KEY_UP 11u +#define KEY_DOWN 14u +#define KEY_TRIG1 25u /* TRIG 1-16: 25-40 */ +#define COUNTS_PER_STEP 12 + +extern const struct dt2_fx *const core_fx[]; +unsigned int core_fx_count(void); + +static const struct { + const char *name; + const char *title; + uint32_t knobs[9]; +} fx_descriptor = {"FX", "Effects", {[8] = 0x9f}}; + +static unsigned int selected; /* a position among the effects the page shows */ +static int8_t pending[DT2_FX_VALUES]; +static uint8_t drawn, active; /* drawn: the page drew this frame; active: it is on screen */ +static uint8_t taken_trig[16]; /* a TRIG key-down the page took, so it takes the key-up too */ + +/* The slot of the n-th effect the page shows (those without a page of their own), or -1. */ +static int shown_slot(unsigned int n) +{ + for (unsigned int slot = 0, count = core_fx_count(); slot < count; ++slot) { + if (!(core_fx[slot]->flags & DT2_FX_OWN_PAGE) && n-- == 0) { + return (int)slot; + } + } + return -1; +} + +static unsigned int shown_count(void) +{ + unsigned int n = 0; + while (shown_slot(n) >= 0) { + ++n; + } + return n; +} + +static void label(void *view, void *bmp, const char *text) +{ + ((void (*)(void *, void *))MIXER_PAGE_FRAME)(view, bmp); + fw_fillrect(bmp, 15, 0, 124, 53, 0); + fw_fillrect(bmp, 0, 27, 14, 50, 0); + fw_textf(bmp, fw_font_narrow, 7, 36, 2, text); +} + +static void draw_fx(void *view, void *bmp) +{ + label(view, bmp, "FX"); + drawn = 1; + const unsigned int count = shown_count(); + if (selected >= count) { + selected = 0; + } + const int slot = shown_slot(selected); + if (slot < 0) { + return; + } + const struct dt2_fx *fx = core_fx[slot]; + fw_textf(bmp, fw_font_narrow, 18, 44, 0, "%s", fx->name); + fw_textf(bmp, fw_font_narrow, 116, 44, 4, "%u/%u", selected + 1, count); + for (unsigned int k = 0; k < DT2_FX_VALUES && k < fx->values; ++k) { + const int x = 18 + 27 * (int)(k % 4), y = k < 4 ? 32 : 18; + fw_textf(bmp, fw_font_narrow, x, y, 0, "%s", fx->value[k].name); + fw_textf(bmp, fw_font_narrow, x, y - 7, 0, "%u", (unsigned int)core_fx_get((unsigned int)slot, k)); + } + const uint32_t tracks = core_fx_get((unsigned int)slot, DT2_FX_TRACKS); + for (unsigned int t = 0; t < 16; ++t) { + const int x = 18 + 6 * (int)t + (t >= 8 ? 4 : 0); + fw_fillrect(bmp, x, 1, x + 4, 5, 1); + if (!(tracks & (1u << t))) { + fw_fillrect(bmp, x + 1, 2, x + 3, 4, 0); + } + } +} + +static const struct dt2_mixer_extension fx_page = { &fx_descriptor, draw_fx }; + +/* ev_draw, after the frame is composed: the page is on screen while it drew this frame. */ +void core_fx_page_after_draw(void *bmp, void *ctrl) +{ + (void)bmp; + (void)ctrl; + active = drawn; + drawn = 0; +} + +static uint32_t word(const void *event, unsigned int offset) +{ + return *(const uint32_t *)((const uint8_t *)event + offset); +} + +int core_fx_page_enc(void *brain, void *event) +{ + (void)brain; + const int slot = active ? shown_slot(selected) : -1; + const unsigned int knob = word(event, EVENT_CODE); + if (slot < 0 || knob < 1 || knob > DT2_FX_VALUES) { + return 0; + } + const struct dt2_fx *fx = core_fx[slot]; + if (knob > fx->values) { + return 1; /* a knob the effect does not use: nothing happens, as on a stock page's empty knob */ + } + int8_t *count = &pending[knob - 1]; + const int32_t raw = (int32_t)word(event, EVENT_DELTA); + int32_t total = *count + raw; + int32_t steps = total / COUNTS_PER_STEP; + *count = (int8_t)(total - steps * COUNTS_PER_STEP); + if (steps) { + int32_t value = (int32_t)core_fx_get((unsigned int)slot, knob - 1) + steps; + const int32_t max = fx->value[knob - 1].max; + value = value < 0 ? 0 : value > max ? max : value; + core_fx_set((unsigned int)slot, knob - 1, (uint32_t)value); + } + return 1; +} + +int core_fx_page_key(void *brain, void *event) +{ + (void)brain; + const unsigned int code = word(event, EVENT_CODE); + const int down = ((int (*)(void *))KEY_EVENT_DOWN)(event) & 0xff; + if (code >= KEY_TRIG1 && code < KEY_TRIG1 + 16 && !down && taken_trig[code - KEY_TRIG1]) { + taken_trig[code - KEY_TRIG1] = 0; + return 1; + } + const int slot = active ? shown_slot(selected) : -1; + if (slot < 0 || !down || fw_key_down(17) /* FUNC: FUNC + MOD and other gestures stay stock */) { + return 0; + } + if (code == KEY_UP || code == KEY_DOWN) { + const unsigned int count = shown_count(); + selected = code == KEY_DOWN ? (selected + 1) % count : (selected + count - 1) % count; + for (unsigned int k = 0; k < DT2_FX_VALUES; ++k) { + pending[k] = 0; + } + return 1; + } + if (code >= KEY_TRIG1 && code < KEY_TRIG1 + 16) { + const uint32_t tracks = core_fx_get((unsigned int)slot, DT2_FX_TRACKS) ^ (1u << (code - KEY_TRIG1)); + core_fx_set((unsigned int)slot, DT2_FX_TRACKS, tracks); + taken_trig[code - KEY_TRIG1] = 1; + return 1; + } + return 0; +} + +#ifdef MODWERK_MIXER_TEN_PAGES_TEST +/* Test only, never committed: the FX page always, and four stand-in module pages (mixer.c), so the Mixer has ten. */ +static const typeof(fx_descriptor) test_descriptor[4] = { + {"T1", "Test 1", {[8] = 0x9f}}, {"T2", "Test 2", {[8] = 0x9f}}, + {"T3", "Test 3", {[8] = 0x9f}}, {"T4", "Test 4", {[8] = 0x9f}}, +}; +static void draw_t1(void *view, void *bmp) { label(view, bmp, "T1"); } +static void draw_t2(void *view, void *bmp) { label(view, bmp, "T2"); } +static void draw_t3(void *view, void *bmp) { label(view, bmp, "T3"); } +static void draw_t4(void *view, void *bmp) { label(view, bmp, "T4"); } +static const struct dt2_mixer_extension test_pages[4] = { + { &test_descriptor[0], draw_t1 }, { &test_descriptor[1], draw_t2 }, + { &test_descriptor[2], draw_t3 }, { &test_descriptor[3], draw_t4 }, +}; +const struct dt2_mixer_extension *const core_mixer_test_pages[DT2_MIXER_EXTENSION_COUNT] = { + &test_pages[0], &test_pages[1], &test_pages[2], &test_pages[3], +}; + +const struct dt2_mixer_extension *core_fx_page(void) +{ + return &fx_page; +} +#else +const struct dt2_mixer_extension *core_fx_page(void) +{ + return shown_count() ? &fx_page : 0; +} +#endif diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/fx.c b/sdk/machines/digitakt-ii/elekloader/modwerk/fx.c new file mode 100644 index 0000000000..1f6b38bd02 --- /dev/null +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/fx.c @@ -0,0 +1,184 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* The base's effect slot, ColdFire side (OS 1.17): docs/verification/2026-11-25-digitakt-ii-fx-slot.md. + * + * core_fx lists the installed effects; an effect's position there is its slot on the ColdFire and on the sound chip. + * Each slot has sixteen settings words (0-14 the effect's, 15 its track mask). core_fx_set keeps a word and marks it; + * before each transfer to the sound chip (core_audio_frame_entry, mixer-entry.s) core_fx_frame writes the transfer + * tail's words 0-15 as one mailbox: a magic, a sequence number and seven {slot << 8 | index, value} pairs, the marked + * words first, then every word of every installed slot in turn, so the sound chip catches up after a load or a restart. + * The base's frame receiver on the sound chip writes each pair into that slot's settings block (dt2-sharc.ts, + * planDt2Fx). No module writes a word of the transfer itself: ev_audio_frame is read-only. + * + * The FX page's settings (each effect's track mask and values 0-7) are saved with the project in one archive block, + * FXS1, matched by each effect's tag on load. An effect with its own page (DT2_FX_OWN_PAGE) saves its own. */ +#include +#include +#include "project-archive.h" + +#define STOCK_WORD(address) (*(const volatile uint32_t *)(address)) +#define DSP_QUEUE 0x400cd48cu /* the transfer's halfword queue */ +#define FIRST_TAIL_HALF 0x402u +#define MAILBOX_MAGIC 0x46584d31u /* "FXM1" */ +#define MAILBOX_PAIRS 7u +#define EMPTY_KEY 0xffffffffu +#define WORDS 16u +#define ARCHIVE_TAG 0x46585331u /* "FXS1" */ + +extern const struct dt2_fx *const core_fx[]; + +static uint32_t words[DT2_FX_COUNT][WORDS]; +static volatile uint16_t marked[DT2_FX_COUNT]; +static uint32_t sequence; +static unsigned int refresh; /* the next slot * WORDS + index the refresh sends */ + +unsigned int core_fx_count(void) +{ + unsigned int n = 0; + while (n < DT2_FX_COUNT && core_fx[n] && core_fx[n]->magic == DT2_FX_MAGIC) { + ++n; + } + return n; +} + +int core_fx_slot(const struct dt2_fx *fx) +{ + for (unsigned int slot = 0, n = core_fx_count(); slot < n; ++slot) { + if (core_fx[slot] == fx) { + return (int)slot; + } + } + return -1; +} + +void core_fx_set(unsigned int slot, unsigned int index, uint32_t value) +{ + if (slot >= core_fx_count() || index >= WORDS) { + return; + } + if (words[slot][index] != value) { + words[slot][index] = value; + marked[slot] |= (uint16_t)(1u << index); + } +} + +uint32_t core_fx_get(unsigned int slot, unsigned int index) +{ + return slot < DT2_FX_COUNT && index < WORDS ? words[slot][index] : 0; +} + +static __attribute__((noinline)) void put(volatile uint16_t *halves, unsigned int word, uint32_t value) +{ + /* The queue alternates command and data halfwords; a sound-chip word arrives low half first. The command + * halfwords stay as stock wrote them. */ + halves[4 * word] = (uint16_t)value; + halves[4 * word + 2] = (uint16_t)(value >> 16); +} + +void core_fx_frame(unsigned int data_bytes, const void *data, unsigned int frame_bytes, const void *reply) +{ + (void)data; + (void)reply; + const unsigned int n = core_fx_count(); + if (data_bytes != 0x802 || frame_bytes != 0xabc || !n) { + return; + } + volatile uint16_t *tail = (volatile uint16_t *)(STOCK_WORD(DSP_QUEUE) + 4 * FIRST_TAIL_HALF + 2); + put(tail, 0, MAILBOX_MAGIC); + put(tail, 1, ++sequence); + unsigned int pair = 0; + for (unsigned int slot = 0; slot < n && pair < MAILBOX_PAIRS; ++slot) { + for (unsigned int index = 0; index < WORDS && marked[slot] && pair < MAILBOX_PAIRS; ++index) { + if (!(marked[slot] & (1u << index))) { + continue; + } + marked[slot] &= (uint16_t)~(1u << index); + put(tail, 2 + 2 * pair, slot << 8 | index); + put(tail, 3 + 2 * pair, words[slot][index]); + ++pair; + } + } + for (unsigned int tries = 0; pair < MAILBOX_PAIRS && tries < n * WORDS; ++tries) { + const unsigned int at = refresh, slot = at / WORDS, index = at % WORDS; + refresh = at + 1 < n * WORDS ? at + 1 : 0; + put(tail, 2 + 2 * pair, slot << 8 | index); + put(tail, 3 + 2 * pair, words[slot][index]); + ++pair; + } + for (; pair < MAILBOX_PAIRS; ++pair) { + put(tail, 2 + 2 * pair, EMPTY_KEY); + put(tail, 3 + 2 * pair, 0); + } +} + +/* The FXS1 block: per effect on the FX page, its tag, track mask and values 0-7. */ +struct fx_saved { + char tag[4]; + uint16_t tracks; + uint8_t values[DT2_FX_VALUES]; + uint8_t reserved[2]; +}; +struct fx_archive { + uint32_t count; + struct fx_saved entry[DT2_FX_COUNT]; +}; + +static int same_tag(const char *a, const char *b) +{ + return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]; +} + +static void fx_save(void *data) +{ + struct fx_archive *out = data; + out->count = 0; + for (unsigned int slot = 0, n = core_fx_count(); slot < n; ++slot) { + const struct dt2_fx *fx = core_fx[slot]; + if (fx->flags & DT2_FX_OWN_PAGE) { + continue; + } + struct fx_saved *entry = &out->entry[out->count++]; + for (unsigned int k = 0; k < 4; ++k) { + entry->tag[k] = fx->tag[k]; + } + entry->tracks = (uint16_t)words[slot][DT2_FX_TRACKS]; + for (unsigned int k = 0; k < DT2_FX_VALUES; ++k) { + entry->values[k] = (uint8_t)words[slot][k]; + } + entry->reserved[0] = entry->reserved[1] = 0; + } + for (unsigned int k = out->count; k < DT2_FX_COUNT; ++k) { + struct fx_saved *entry = &out->entry[k]; + for (unsigned int b = 0; b < sizeof *entry; ++b) { + ((uint8_t *)entry)[b] = 0; + } + } +} + +/* A project without the block, a new one, or an effect missing from it: initial values, no track lit. */ +static void fx_load(const void *data) +{ + const struct fx_archive *in = data; + const unsigned int saved = in && in->count <= DT2_FX_COUNT ? in->count : 0; + for (unsigned int slot = 0, n = core_fx_count(); slot < n; ++slot) { + const struct dt2_fx *fx = core_fx[slot]; + if (fx->flags & DT2_FX_OWN_PAGE) { + continue; + } + const struct fx_saved *found = 0; + for (unsigned int k = 0; k < saved && !found; ++k) { + if (same_tag(in->entry[k].tag, fx->tag)) { + found = &in->entry[k]; + } + } + for (unsigned int k = 0; k < DT2_FX_VALUES; ++k) { + const uint8_t max = k < fx->values ? fx->value[k].max : 0; + const uint8_t value = found ? found->values[k] : (k < fx->values ? fx->value[k].initial : 0); + core_fx_set(slot, k, value <= max ? value : max); + } + core_fx_set(slot, DT2_FX_TRACKS, found ? found->tracks : 0); + } +} + +const dt2_project_archive_t core_fx_archive = { + ARCHIVE_TAG, sizeof(struct fx_archive), fx_save, fx_load, +}; diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/machine-frame.c b/sdk/machines/digitakt-ii/elekloader/modwerk/machine-frame.c index 38a25dc886..abd2750382 100644 --- a/sdk/machines/digitakt-ii/elekloader/modwerk/machine-frame.c +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/machine-frame.c @@ -11,8 +11,8 @@ * (DT2_BASE_SHARC.stepSamples in the builder: the 1X step, tracks 1-16, the view track), and puts the machine view a * player posted into its reply, which comes back here with the next transfer. * - * With no machine in core_machines nothing here runs: no tail words (the receiver then skips the wire and the view) - * and no reply read. The reply is read only while a module's page has set a view track. + * With no machine in core_machines and no effect in core_fx nothing here runs: no tail words (the receiver then skips + * the wire and the view) and no reply read. The reply is read only while a module's page has set a view track. */ #include #include @@ -45,6 +45,7 @@ extern const struct dt2_machine *const core_machines[DT2_MACHINE_COUNT]; unsigned int core_voice_lead(unsigned int track); +unsigned int core_fx_count(void); /* fx.c: effects send the wire too, for the tempo and the tracks' steps */ uint32_t core_machine_samples_per_step = 6000; /* 120 BPM until a pattern's tempo is read */ volatile uint32_t core_machine_view_track = DT2_MACHINE_VIEW_NONE; @@ -63,7 +64,7 @@ void core_machine_frame(unsigned int data_bytes, const void *data, unsigned int { (void)data; (void)reply; - if (data_bytes != 0x802 || frame_bytes != 0xabc || !core_machines[0]) { + if (data_bytes != 0x802 || frame_bytes != 0xabc || (!core_machines[0] && !core_fx_count())) { return; } const uintptr_t pattern = STOCK_WORD(CURRENT_PATTERN); diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/mixer-entry.s b/sdk/machines/digitakt-ii/elekloader/modwerk/mixer-entry.s index 135e328067..f2319e5ece 100644 --- a/sdk/machines/digitakt-ii/elekloader/modwerk/mixer-entry.s +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/mixer-entry.s @@ -14,6 +14,12 @@ core_audio_frame_entry: move.l 20(%sp),-(%sp) jsr core_machine_frame lea 16(%sp),%sp + move.l 20(%sp),-(%sp) | then the effects' settings mailbox, tail words 0-15 (fx.c) + move.l 20(%sp),-(%sp) + move.l 20(%sp),-(%sp) + move.l 20(%sp),-(%sp) + jsr core_fx_frame + lea 16(%sp),%sp lea ev_audio_frame,%a2 1: move.l (%a2)+,%d0 beq.s 2f diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/mixer.c b/sdk/machines/digitakt-ii/elekloader/modwerk/mixer.c index eee830a118..bddda82817 100644 --- a/sdk/machines/digitakt-ii/elekloader/modwerk/mixer.c +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/mixer.c @@ -1,14 +1,23 @@ /* SPDX-License-Identifier: GPL-3.0-or-later */ #include +static int complete(const struct dt2_mixer_extension *entry) +{ + return entry && entry->descriptor && entry->draw; +} + unsigned int dt2_mixer_page_list( uint32_t pages[DT2_MIXER_PAGE_CAPACITY], + const struct dt2_mixer_extension *fx, const struct dt2_mixer_extension *const extensions[DT2_MIXER_EXTENSION_COUNT]) { unsigned int next = 0; pages[next++] = 16; + if (complete(fx)) { + pages[next++] = DT2_MIXER_FX_PAGE; + } for (unsigned int slot = 0; slot < DT2_MIXER_EXTENSION_COUNT && extensions[slot]; ++slot) { - if (extensions[slot]->descriptor && extensions[slot]->draw) { + if (complete(extensions[slot])) { pages[next++] = DT2_MIXER_EXTENSION_FIRST + slot; } } @@ -18,16 +27,27 @@ unsigned int dt2_mixer_page_list( return next; } +#ifdef MODWERK_MIXER_TEN_PAGES_TEST +/* Test only, never committed: four stand-in module pages, so the Mixer shows ten pages. */ +#define core_mixer_pages core_mixer_test_pages +extern const struct dt2_mixer_extension *const core_mixer_test_pages[DT2_MIXER_EXTENSION_COUNT]; +#else extern const struct dt2_mixer_extension *const core_mixer_pages[DT2_MIXER_EXTENSION_COUNT]; +#endif +const struct dt2_mixer_extension *core_fx_page(void); /* fx-page.c: the FX page, or null while it has nothing to show */ uint32_t core_mixer_page_ids[DT2_MIXER_PAGE_CAPACITY]; unsigned int core_mixer_prepare(void) { - return dt2_mixer_page_list(core_mixer_page_ids, core_mixer_pages); + return dt2_mixer_page_list(core_mixer_page_ids, core_fx_page(), core_mixer_pages); } static const struct dt2_mixer_extension *extension(uint32_t page) { + if (page == DT2_MIXER_FX_PAGE) { + const struct dt2_mixer_extension *fx = core_fx_page(); + return complete(fx) ? fx : 0; + } uint32_t slot = page - DT2_MIXER_EXTENSION_FIRST; if (slot >= DT2_MIXER_EXTENSION_COUNT) { return 0; @@ -38,7 +58,7 @@ static const struct dt2_mixer_extension *extension(uint32_t page) } } const struct dt2_mixer_extension *entry = core_mixer_pages[slot]; - return entry && entry->descriptor && entry->draw ? entry : 0; + return complete(entry) ? entry : 0; } const void *core_mixer_descriptor(uint32_t page) diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/tests/mixer-test.c b/sdk/machines/digitakt-ii/elekloader/modwerk/tests/mixer-test.c index cc984dc3d1..4df4f8b513 100644 --- a/sdk/machines/digitakt-ii/elekloader/modwerk/tests/mixer-test.c +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/tests/mixer-test.c @@ -4,6 +4,7 @@ #include const struct dt2_mixer_extension *const core_mixer_pages[DT2_MIXER_EXTENSION_COUNT] = {0}; +const struct dt2_mixer_extension *core_fx_page(void) { return NULL; } static void draw(void *view, void *bitmap) { @@ -19,20 +20,27 @@ int main(void) const struct dt2_mixer_extension *extensions[DT2_MIXER_EXTENSION_COUNT] = {0}; uint32_t pages[DT2_MIXER_PAGE_CAPACITY]; - assert(dt2_mixer_page_list(pages, extensions) == 5); + assert(dt2_mixer_page_list(pages, NULL, extensions) == 5); for (uint32_t i = 0; i < 5; ++i) { assert(pages[i] == 16 + i); } extensions[0] = &page; extensions[1] = &incomplete; extensions[2] = &page; - assert(dt2_mixer_page_list(pages, extensions) == 7); + assert(dt2_mixer_page_list(pages, NULL, extensions) == 7); assert(pages[0] == 16 && pages[1] == 33 && pages[2] == 35); for (uint32_t i = 0; i < 4; ++i) { assert(pages[i + 3] == 17 + i); } extensions[1] = &page; extensions[3] = &page; - assert(dt2_mixer_page_list(pages, extensions) == DT2_MIXER_PAGE_CAPACITY); + assert(dt2_mixer_page_list(pages, NULL, extensions) == DT2_MIXER_PAGE_CAPACITY - 1); assert(pages[4] == 36 && pages[8] == 20); + + /* The base's FX page comes right after COMP and takes none of the modules' four entries. */ + assert(dt2_mixer_page_list(pages, &page, extensions) == DT2_MIXER_PAGE_CAPACITY); + assert(pages[0] == 16 && pages[1] == DT2_MIXER_FX_PAGE && pages[2] == 33 && pages[5] == 36 && pages[9] == 20); + assert(DT2_MIXER_FX_PAGE == 37); + assert(dt2_mixer_page_list(pages, &incomplete, extensions) == DT2_MIXER_PAGE_CAPACITY - 1); + assert(pages[1] == 33); } diff --git a/sdk/machines/digitakt-ii/include/mk2/fx.h b/sdk/machines/digitakt-ii/include/mk2/fx.h new file mode 100644 index 0000000000..4a10778a18 --- /dev/null +++ b/sdk/machines/digitakt-ii/include/mk2/fx.h @@ -0,0 +1,47 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* The Digitakt II base's effect slot (OS 1.17): docs/verification/2026-11-25-digitakt-ii-fx-slot.md. */ +#ifndef MODWERK_DT2_FX_H +#define MODWERK_DT2_FX_H + +#include + +enum { + DT2_FX_MAGIC = 0x46584631u, /* "FXF1": a struct dt2_fx */ + DT2_FX_COUNT = 8, /* core_fx's room; the builder refuses a ninth */ + DT2_FX_VALUES = 8, /* values on knobs A-H of the FX page */ + DT2_FX_WORDS = 15, /* settings words 0-14 an effect may set through core_fx_set */ + DT2_FX_TRACKS = 15, /* core_fx_set's index for the track mask (bit t: track t + 1) */ + DT2_FX_LISTEN = 1u << 0, /* the package's sound-chip part has a listen routine */ + DT2_FX_PROCESS = 1u << 1, /* ... and a process routine */ + DT2_FX_OWN_PAGE = 1u << 2, /* the effect draws its own Mixer pages and is not on the FX page */ +}; + +struct dt2_fx_value { + char name[5]; /* four letters and a NUL, drawn above the knob */ + uint8_t max; /* values 0..max, max <= 127 */ + uint8_t initial; /* the value in a new project */ + uint8_t reserved; +}; + +/* One record per effect, contributed to core_fx with the effect's order band (10-39 tone and drive, 40-69 time, + * 70-99 dynamics): the table's position is the effect's slot, on the ColdFire and on the sound chip. */ +struct dt2_fx { + uint32_t magic; /* DT2_FX_MAGIC */ + char tag[4]; /* the module's own tag, for the saved settings */ + uint16_t order; /* the contribution's order, repeated */ + uint16_t flags; /* DT2_FX_LISTEN, DT2_FX_PROCESS, DT2_FX_OWN_PAGE */ + char name[12]; /* the FX page's row, NUL-terminated */ + uint8_t values; /* 0-8 values on knobs A-H */ + uint8_t reserved[3]; + struct dt2_fx_value value[DT2_FX_VALUES]; +}; + +/* The slot of `fx` in core_fx, or -1 when it is not there. */ +int core_fx_slot(const struct dt2_fx *fx); +/* Set settings word `index` (0-14, or DT2_FX_TRACKS for the track mask) of `slot` on the sound chip; from the UI task. + * The base sends changes first, then every word in turn, a few each transfer. */ +void core_fx_set(unsigned int slot, unsigned int index, uint32_t value); +/* The value core_fx_set last set (0 before any). */ +uint32_t core_fx_get(unsigned int slot, unsigned int index); + +#endif diff --git a/sdk/machines/digitakt-ii/include/mk2/mixer.h b/sdk/machines/digitakt-ii/include/mk2/mixer.h index bf494ab2b9..a104a44d03 100644 --- a/sdk/machines/digitakt-ii/include/mk2/mixer.h +++ b/sdk/machines/digitakt-ii/include/mk2/mixer.h @@ -7,7 +7,10 @@ enum { DT2_MIXER_EXTENSION_FIRST = 33, DT2_MIXER_EXTENSION_COUNT = 4, - DT2_MIXER_PAGE_CAPACITY = 5 + DT2_MIXER_EXTENSION_COUNT, + /* The base's own FX page (fx-page.c): not one of the modules' entries. */ + DT2_MIXER_FX_PAGE = DT2_MIXER_EXTENSION_FIRST + DT2_MIXER_EXTENSION_COUNT, + /* COMP, the FX page, the modules' pages, then the four stock pages after COMP. */ + DT2_MIXER_PAGE_CAPACITY = 6 + DT2_MIXER_EXTENSION_COUNT, }; /* The linker's collection index owns the page number. The table ends at @@ -17,8 +20,11 @@ struct dt2_mixer_extension { void (*draw)(void *view, void *bitmap); }; +/* The Mixer's page list: COMP, the base's FX page when `fx` is a complete entry, each complete module entry, then + * the four stock pages. Returns the count. */ unsigned int dt2_mixer_page_list( uint32_t pages[DT2_MIXER_PAGE_CAPACITY], + const struct dt2_mixer_extension *fx, const struct dt2_mixer_extension *const extensions[DT2_MIXER_EXTENSION_COUNT]); #endif diff --git a/src/catalog/module-contract-v3.ts b/src/catalog/module-contract-v3.ts index 8ce338072b..a084447b20 100644 --- a/src/catalog/module-contract-v3.ts +++ b/src/catalog/module-contract-v3.ts @@ -343,7 +343,9 @@ export type ElemodBuildSpec = { claims: string[]; requires: string[] // A Digitakt II machine module's sound-chip player: its source, assembled into the package's build.dt2_sharc, and // the machine types (7-10, each claimed as machine:) whose voices it plays from which entry label. - sharc?: { source: string; players: { type: number; entry: string }[] } + // An effect module's routines for the base's effect slot instead (one effect per module), each entry a label in the source, + // and its worst case in busy sound-chip instructions a block with all sixteen tracks lit. + sharc?: { source: string; players: { type: number; entry: string }[]; fx?: { listen?: string; process?: string; cost: number } } // Steps that need the stock OS run only during the owner's local build, never in CI. derive: { kind: string; note: string; release: string; releases: string[]; block: [string, string]; sram: [string, string]; callSites: { addr: string; len: number; stockSha256: string; target: string }[] } | null releases: Record @@ -461,10 +463,10 @@ export function parseElemodBuild(value: unknown, document: Pick [symbol(name, 'build.strings.' + name), text(value, 'build.strings.' + name, 120)])) let sharc: ElemodBuildSpec['sharc'] if (item.sharc !== undefined) { - const value = object(item.sharc, 'build.sharc', ['source', 'players']) + const value = object(item.sharc, 'build.sharc', ['source'], ['players', 'fx']) const source = modulePath(value.source, 'build.sharc.source') if (!/^src\/.+\.sharc$/.test(source)) fail('build.sharc.source', 'expected a .sharc source under src/') - const players = list(value.players, 'build.sharc.players', 1, 4).map((entry, index) => { + const players = list(value.players ?? [], 'build.sharc.players', value.fx === undefined ? 1 : 0, 4).map((entry, index) => { const at = 'build.sharc.players[' + index + ']', player = object(entry, at, ['type', 'entry']) const type = count(player.type, at + '.type') if (type === null || type < 7 || type > 10) fail(at + '.type', 'expected an added machine type, 7 to 10') @@ -472,7 +474,17 @@ export function parseElemodBuild(value: unknown, document: Pick player.type)).size !== players.length) fail('build.sharc.players', 'one player per machine type') - sharc = { source, players } + let fx: NonNullable['fx'] + if (value.fx !== undefined) { + const entry = object(value.fx, 'build.sharc.fx', ['cost'], ['listen', 'process']) + const cost = count(entry.cost, 'build.sharc.fx.cost') + if (cost === null || cost < 1 || cost > 60000) fail('build.sharc.fx.cost', 'expected the worst case in busy instructions a block, 1 to 60000') + if (entry.listen === undefined && entry.process === undefined) fail('build.sharc.fx', 'expected a listen or a process routine') + if (players.length) fail('build.sharc.fx', 'one effect per module, and an effect is not a machine') + fx = { ...(entry.listen === undefined ? {} : { listen: symbol(entry.listen, 'build.sharc.fx.listen') }), + ...(entry.process === undefined ? {} : { process: symbol(entry.process, 'build.sharc.fx.process') }), cost: cost! } + } + sharc = { source, players, ...(fx ? { fx } : {}) } } return { schemaVersion: 1, sources, strings, defsym: defines(item.defsym, 'build.defsym'), cflags: texts(item.cflags, 'build.cflags', 0, 16, 60), weak: list(item.weak, 'build.weak', 0, 64).map((name, index) => symbol(name, 'build.weak[' + index + ']')), subscribe, contribute, collections, copied, regions, storage, claims, requires, derive, releases, ...(sharc ? { sharc } : {}) } } diff --git a/src/engine/elekloader/digi-preflight.test.ts b/src/engine/elekloader/digi-preflight.test.ts index 7661465020..45582e472b 100644 --- a/src/engine/elekloader/digi-preflight.test.ts +++ b/src/engine/elekloader/digi-preflight.test.ts @@ -5,7 +5,7 @@ import { packSection } from '../aplib' import { ELE3_DEVICES } from '../elektron/ele3' import { LINK_DEVICES, type ParsedMod } from '../elektron/elemod' import { contentChecksum, encodeSyx } from '../elektron/sysex' -import { PreflightError, appendLimit, parseBuildMods, preflightBuild, rawCardWrite } from './digi-preflight' +import { PreflightError, appendLimit, dspTransferQueue, parseBuildMods, preflightBuild, rawCardWrite } from './digi-preflight' import { BUILDER_CATALOG } from './machine-build' // A synthetic Digitakt II container: invented sections, a main OS of NOPs and a 32-byte tail where a sealed file keeps @@ -129,6 +129,24 @@ describe('Digitakt II build preflight', () => { expect(rawCardWrite(saver({ device: LINK_DEVICES.find(device => device.machine === 'digitakt')!, sections: run([0x40, 0x12, 0xe3, 0x9c]) }))).toBeNull() }) + it('refuses a mod that names the transfer to the sound chip, whose tail is the base\'s, and passes the base', async () => { + const built = syx(main([[0x40000500, JMP]], 96)), QUEUE = 0x400cd48c + const run = (bytes: number[]) => ({ '.run': { align: 2, parts: [{ kind: 'hex' as const, bytes: Uint8Array.from(bytes) }], length: bytes.length } }) + const reloc = (target: string, addend = 0) => [{ section: '.run' as const, offset: 2, type: 'abs32' as const, target, addend }] + const writer = (extra: Partial) => mod({ id: 'writer', version: '0.1', sites: [], sections: run([0x20, 0x79, 0, 0, 0, 0, 0x4e, 0x75]), ...extra }) + const refusal = ['writer 0.1 names 0x400cd48c, the transfer to the sound chip, whose tail is the base\'s: send settings through core_fx_set'] + expect(await problems(preflightBuild('digitakt-ii', stock, built, [mod(), writer({ relocs: reloc('abs', QUEUE) })]))).toEqual(refusal) + expect(await problems(preflightBuild('digitakt-ii', stock, built, [mod(), writer({ sections: run([0x20, 0x79, 0x40, 0x0c, 0xd4, 0x8c, 0x4e, 0x75]) })]))).toEqual(refusal) + expect(dspTransferQueue(mod({ sections: run([0x20, 0x79, 0x40, 0x0c, 0xd4, 0x8c, 0x4e, 0x75]) }))).toBeNull() + expect(await problems(preflightBuild('digitakt-ii', stock, built, [mod(), writer({})]))).toEqual([]) + }) + + it('finds no Digitakt II module in the builder catalogue that names the transfer to the sound chip', () => { + const files = BUILDER_CATALOG.mods.filter(pin => pin.device === DT2.key).map(pin => pin.file) + const mods = parseBuildMods(files.map(name => ({ name, bytes: readFileSync(new URL('../../../vendor/elekloader/catalog/' + name, import.meta.url)) }))) + expect(mods.filter(dspTransferQueue).map(found => found.id + ' ' + found.version)).toEqual([]) + }) + it('finds no Digitakt II package in the builder catalogue that reaches the raw card write', () => { const files = [...BUILDER_CATALOG.cores, ...BUILDER_CATALOG.mods].filter(pin => pin.device === DT2.key).map(pin => pin.file) const mods = parseBuildMods(files.map(name => ({ name, bytes: readFileSync(new URL('../../../vendor/elekloader/catalog/' + name, import.meta.url)) }))) diff --git a/src/engine/elekloader/digi-preflight.ts b/src/engine/elekloader/digi-preflight.ts index 52bfe32d92..604237dc73 100644 --- a/src/engine/elekloader/digi-preflight.ts +++ b/src/engine/elekloader/digi-preflight.ts @@ -67,6 +67,26 @@ export function rawCardWrite(mod: ParsedMod): string | null { return resolved || named ? 'names ' + hex32(address) : null } +/** The queue of each ColdFire-to-sound-chip transfer (Digitakt II OS 1.17). Its tail carries the base's machine wire and + * the effects' settings mailbox; ev_audio_frame subscribers write no word of it (docs/verification/2026-11-25-digitakt-ii- + * fx-slot.md), so no mod of a build but the base itself may name it. */ +export const DSP_TRANSFER_QUEUE: Partial> = { 'digitakt-ii': 0x400cd48c } + +/** How `mod` names its machine's transfer queue, or null: by a relocation that resolves to its address, or by the address + * among the mod's own bytes. The base (`core`) owns the queue's tail and is not checked. */ +export function dspTransferQueue(mod: ParsedMod): string | null { + const address = DSP_TRANSFER_QUEUE[mod.device.machine] + if (address === undefined || mod.id === 'core') return null + const relocs = [...mod.relocs, ...mod.sites.flatMap(site => site.relocs), ...mod.contribute.flatMap(entry => entry.relocs)] + const resolved = relocs.some(reloc => { + const at = reloc.target === 'abs' ? 0 : reloc.target.startsWith('sym:') && mod.symbols.get(reloc.target.slice(4))?.[0] === 'abs' ? mod.symbols.get(reloc.target.slice(4))![1] : null + return at !== null && ((at + reloc.addend) >>> 0) === address + }) + const own = [...Object.values(mod.sections).flatMap(section => 'parts' in section ? section.parts.flatMap(part => part.kind === 'hex' ? [part.bytes] : []) : []), ...mod.sites.map(site => site.bytes), ...mod.contribute.map(entry => entry.data)] + const named = own.some(bytes => bytes.some((_, i) => i + 4 <= bytes.length && ((bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0) === address)) + return resolved || named ? 'names ' + hex32(address) : null +} + /** Bytes after the stock main OS the linked mods may account for: the core's boot code (16-aligned), the RAM image of * the device's run area, and the mod-storage lockfile the build carries at its end. */ export function appendLimit(mods: readonly ParsedMod[], builtMain: Uint8Array, stockLength: number): number { @@ -154,6 +174,8 @@ export async function preflightBuild(machine: ElemodMachine, stockSyx: Uint8Arra if (mod.format !== 2) problems.push(mod.id + ' ' + mod.version + ' is a whole build, which the preflight does not check') const reach = rawCardWrite(mod) if (reach) problems.push(mod.id + ' ' + mod.version + ' ' + reach + ', the raw block write to the +Drive, which no mod may use: keep a mod\'s data in the project and its kits (core_projdata, core_kitdata)') + const queue = dspTransferQueue(mod) + if (queue) problems.push(mod.id + ' ' + mod.version + ' ' + queue + ', the transfer to the sound chip, whose tail is the base\'s: send settings through core_fx_set') } const stockMain = mainImage(stock, device), builtMain = mainImage(built, device) const sites = declaredSites(mods) diff --git a/src/engine/elekloader/dt2-render-build.test.ts b/src/engine/elekloader/dt2-render-build.test.ts index 3af3874c9c..c0669c5efd 100644 --- a/src/engine/elekloader/dt2-render-build.test.ts +++ b/src/engine/elekloader/dt2-render-build.test.ts @@ -4,7 +4,9 @@ import { buildDt2RenderSection, unpackDt2SharcSection, type Dt2RenderPlan } from import { readEle3Syx } from '../elektron/ele3' import type { ParsedMod } from '../elektron/elemod' import { sharcProgramCounter } from '../elektron/sharc-asm' -import { DT2_BASE_SHARC, dt2RegisteredMachines, planDt2MachineParts, readDt2SharcPart, type Dt2SharcPart } from './dt2-render-build' +import { + DT2_ADDED_BUDGET, DT2_BASE_SHARC, dt2EffectSlots, dt2RegisteredMachines, planDt2MachineParts, readDt2SharcPart, type Dt2Effect, type Dt2SharcPart, +} from './dt2-render-build' const code8 = btoa('\x01\x02\x03\x04\x05\x06\x07\x08') const part = (extra: Record = {}) => ({ build: { dt2_sharc: { version: 2, allocations: [{ address: 0x200d0000, data: code8, code: true }], players: [{ type: 7, entry: 0xbe8000 }], ...extra } } }) @@ -38,6 +40,32 @@ describe('Digitakt II machine sound-chip parts', () => { }) }) +describe('Digitakt II effect sound-chip parts', () => { + const effect = (fx: Record) => part({ players: [], fx }) + it('reads an effect\'s routines and cost', () => { + expect(readDt2SharcPart('delay', effect({ process: 0xbe8000, cost: 4000 }))).toEqual({ + module: 'delay', allocations: [{ address: 0x200d0000, bytes: Uint8Array.of(1, 2, 3, 4, 5, 6, 7, 8), code: true }], players: [], + fx: { process: 0xbe8000, cost: 4000 }, + }) + }) + + it('refuses an effect with no routine, a routine outside its code, a cost out of range and a part with nothing', () => { + expect(() => readDt2SharcPart('m', effect({ cost: 10 }))).toThrow('neither a listen nor a process routine') + expect(() => readDt2SharcPart('m', effect({ listen: 0xbe9000, cost: 10 }))).toThrow('listen routine does not start in its own sound-chip code') + expect(() => readDt2SharcPart('m', effect({ process: 0xbe8000, cost: 0 }))).toThrow('declares its worst case') + expect(() => readDt2SharcPart('m', effect({ process: 0xbe8000, cost: DT2_ADDED_BUDGET + 1 }))).toThrow('declares its worst case') + expect(() => readDt2SharcPart('m', part({ players: [] }))).toThrow('neither a machine player nor an effect') + }) + + it('orders effects as the linker orders core_fx: order, then module id, then the module\'s own order', () => { + const effects: Dt2Effect[] = [ + { module: 'verb', order: 50, id: 'verb', index: 0 }, { module: 'drive', order: 20, id: 'drive', index: 0 }, + { module: 'delay', order: 50, id: 'delay', index: 0 }, { module: 'duck', order: 80, id: 'duck', index: 0 }, + ] + expect(dt2EffectSlots(effects).map(item => item.module)).toEqual(['drive', 'delay', 'verb', 'duck']) + }) +}) + /** A mod that registers machines as a build does: core_machines entries pointing at records in its .run. */ function machineMod(records: [type: number, standsFor: number][]): ParsedMod { const run = new Uint8Array(16 * records.length) @@ -78,6 +106,20 @@ describe('the base\'s sound-chip parts for a set', () => { }) }) +describe('the base\'s effect slot for a set', () => { + const sharc = new Uint8Array(64) // not the stock section: these cases are refused before it is read + const fx = (module: string, cost = 1000): Dt2SharcPart => ({ module, allocations: [], players: [], fx: { process: 0xbe8000, cost } }) + const record = (module: string, order = 50): Dt2Effect => ({ module, order, id: module, index: 0 }) + it('refuses a ninth effect, a record without routines, routines without a record and a set over the budget', async () => { + const nine = Array.from({ length: 9 }, (_, k) => 'fx' + k) + await expect(planDt2MachineParts(sharc, [], nine.map(name => fx(name)), [], nine.map(name => record(name)))).rejects.toThrow('More than 8 effects') + await expect(planDt2MachineParts(sharc, [], [], [], [record('delay')])).rejects.toThrow('carries no effect routine') + await expect(planDt2MachineParts(sharc, [], [fx('delay')], [], [])).rejects.toThrow('without a core_fx record') + await expect(planDt2MachineParts(sharc, [], [fx('a', 40_000), fx('b', 30_000)], [], [record('a'), record('b')])).rejects.toThrow('over the 60000 the base allows') + await expect(planDt2MachineParts(sharc, [], [fx('a')], [], [record('a'), { ...record('a'), index: 1 }])).rejects.toThrow('more than one effect') + }) +}) + // With the owner's OS 1.17 file (never in the repository): MODWERK_DT2_STOCK=. const STOCK = process.env.MODWERK_DT2_STOCK describe.runIf(STOCK)('the base\'s sound-chip parts with the owner\'s OS', () => { @@ -123,6 +165,30 @@ describe.runIf(STOCK)('the base\'s sound-chip parts with the owner\'s OS', () => for (let k = 1; k < 4; k++) expect(slot(plan, DT2_BASE_SHARC.frameSlots, k)).toEqual(RTS) }) + it('places the effect slot at the render site with the same base code for every set, and leaves a machine-only set without it', async () => { + const stock = sharc() + const effect = (module: string, process: number): Dt2SharcPart => ({ + module, allocations: [{ address: 0x200b0000 + (process - 0xbd8000) * 2, bytes: new Uint8Array(8), code: true }], players: [], fx: { process, cost: 4000 }, + }) + const record = (module: string, order: number): Dt2Effect => ({ module, order, id: module, index: 0 }) + const one = (await planDt2MachineParts(stock, [], [effect('drive', 0xbd8000)], [], [record('drive', 20)]))! + const two = (await planDt2MachineParts(stock, [], [effect('verb', 0xbd8100), effect('drive', 0xbd8000)], [], [record('verb', 50), record('drive', 20)]))! + expect(one.renderInstruction).toBeDefined() + expect(two.renderInstruction).toEqual(one.renderInstruction) + for (const address of [DT2_BASE_SHARC.fxCode, DT2_BASE_SHARC.wire]) expect(block(two, address)).toEqual(block(one, address)) + // Listen slots 0-7 then process slots 0-7: drive (order 20) is slot 0 and verb (order 50) slot 1. + for (let k = 0; k < 8; k++) expect(slot(two, DT2_BASE_SHARC.fxSlots, k)).toEqual(RTS) + expect(slot(two, DT2_BASE_SHARC.fxSlots, 8)).toEqual(jump(0xbd8000)) + expect(slot(two, DT2_BASE_SHARC.fxSlots, 9)).toEqual(jump(0xbd8100)) + for (let k = 10; k < 16; k++) expect(slot(two, DT2_BASE_SHARC.fxSlots, k)).toEqual(RTS) + await buildDt2RenderSection(stock, two) + // Machines alone: no render site and the frame receiver without the mailbox call, as before the slot. + const machines = (await planDt2MachineParts(stock, [{ module: 'synth', type: 8, standsFor: 2 }], []))! + expect(machines.renderInstruction).toBeUndefined() + expect(block(machines, DT2_BASE_SHARC.wire).length).toBeLessThan(block(one, DT2_BASE_SHARC.wire).length) + expect(machines.allocations.some(item => item.address === DT2_BASE_SHARC.fxCode)).toBe(false) + }) + it('refuses a set whose stock section is not the pinned one', async () => { const changed = sharc().slice() changed[changed.length - 1] ^= 1 diff --git a/src/engine/elekloader/dt2-render-build.ts b/src/engine/elekloader/dt2-render-build.ts index 46cee7939a..5ccf06b3ac 100644 --- a/src/engine/elekloader/dt2-render-build.ts +++ b/src/engine/elekloader/dt2-render-build.ts @@ -2,8 +2,8 @@ import { DIGITAKT_MK2 } from '../../../vendor/elekloader/kit/src/devices.ts' import { Syx, packMain, verify, write } from '../../../vendor/elekloader/kit/src/syx.ts' import { - buildDt2RenderSection, combineDt2Plans, DT2_ADDED_TYPES, DT2_FIRST_ADDED_TYPE, DT2_MACHINE_KNOBS_AT, DT2_MACHINE_TYPES_AT, planDt2FrameReceive, - planDt2MachinePlayers, planDt2MachineSelectors, unpackDt2SharcSection, + buildDt2RenderSection, combineDt2Plans, DT2_ADDED_TYPES, DT2_FIRST_ADDED_TYPE, DT2_FX_SLOTS, DT2_MACHINE_KNOBS_AT, DT2_MACHINE_TYPES_AT, + planDt2FrameReceive, planDt2Fx, planDt2MachinePlayers, planDt2MachineSelectors, unpackDt2SharcSection, type Dt2MachinePlayer, type Dt2RenderPlan, } from '../elektron/dt2-sharc.ts' import { ELE3_DEVICES } from '../elektron/ele3.ts' @@ -42,42 +42,54 @@ export async function buildDt2RenderFirmware( return { output, facts } } -/** The sound-chip part a machine module carries in its package (`build.dt2_sharc`, version 2): its code and data at - * fixed L2 addresses (each range claimed on the agent board as a dsp-region; `code` marks the instruction blocks) and - * the voice player of each machine type it adds. Addresses are loader byte addresses; `entry` is the player's - * short-word program counter, inside one of the part's own code blocks. */ +/** The sound-chip part a module carries in its package (`build.dt2_sharc`, version 2): its code and data at fixed L2 + * addresses (each range claimed on the agent board as a dsp-region; `code` marks the instruction blocks), the voice + * player of each machine type it adds and, for an effect, its listen and process routines and its declared worst case + * in busy instructions per block with all sixteen tracks lit. Addresses are loader byte addresses; `entry`, `listen` and + * `process` are short-word program counters inside the part's own code blocks. */ export type Dt2SharcPart = { module: string allocations: { address: number; bytes: Uint8Array; code: boolean }[] players: Dt2MachinePlayer[] + fx?: { listen?: number; process?: number; cost: number } } /** A machine a module registers in the base's core_machines table: its type (7-10) and the stock type it stands for. */ export type Dt2Machine = { module: string; type: number; standsFor: number } +/** An effect a module registers in the base's core_fx table, with the key the linker sorts the table by. */ +export type Dt2Effect = { module: string; order: number; id: string; index: number } + // L2 the base keeps for its own sound-chip parts: the selector table, the player and frame registry slots, the player -// dispatcher and its data, and the frame receiver and its data. A player reads the samples per sixteenth step at -// `stepSamples`: the 1X step, then tracks 1-16 at their speeds (17 words), then `viewTrack` (0-15, 16 for none): the -// track whose voice a player posts in the 32 words at `view` (its own magic first, then that track), which reach the -// ColdFire as core_machine_view. These parts are the same for every set of modules; only the slots and the selector -// words for types 7-10 follow the set. +// dispatcher and its data, and the frame receiver and its data; then the effect slot's registry slots, its dispatcher +// and mailbox routine, their save area and the sixteen settings blocks (eight effects, eight kept for machine players). +// A player reads the samples per sixteenth step at `stepSamples`: the 1X step, then tracks 1-16 at their speeds (17 +// words), then `viewTrack` (0-15, 16 for none): the track whose voice a player posts in the 32 words at `view` (its own +// magic first, then that track), which reach the ColdFire as core_machine_view. These parts are the same for every set of +// modules; only the slots and the selector words for types 7-10 follow the set. export const DT2_BASE_SHARC = { selectors: 0x200c0100, playerSlots: 0x200c0f00, frameSlots: 0x200c0f80, dispatcher: 0x200c1000, dispatcherData: 0x200c2000, wire: 0x200c2800, wireData: 0x200c2c00, stepSamples: 0x200c2c20, viewTrack: 0x200c2c64, view: 0x200c2c68, trackTypes: 0x200c2c00 + 4 * DT2_MACHINE_TYPES_AT, trackKnobs: 0x200c2c00 + 4 * DT2_MACHINE_KNOBS_AT, - end: 0x200c3000, + fxSlots: 0x200c3000, fxCode: 0x200c3100, fxData: 0x200c3800, fxSettings: 0x200c3c00, + end: 0x200c4000, } +/** Busy sound-chip instructions a block that the added work of a set may take, all together: 85% of the block at the + * provisional high cycle factor (1.41) with stock at its busiest in the emulator (342,016). Set again from a unit + * cycle count before the base ships (docs/verification/2026-11-25-digitakt-ii-fx-slot.md, "Cost and memory"). */ +export const DT2_ADDED_BUDGET = 60_000 + const base64 = (text: string) => Uint8Array.from(atob(text), c => c.charCodeAt(0)) const byteAddress = (pc: number) => 0x20000000 + (pc - 0xb80000) * 2 -/** The module's sound-chip part, or null when its package has none. Throws on a malformed part, and on a player - * entry outside the part's own code. */ +/** The module's sound-chip part, or null when its package has none. Throws on a malformed part, and on a player or + * effect entry outside the part's own code. */ export function readDt2SharcPart(name: string, document: unknown): Dt2SharcPart | null { const part = (document as { build?: { dt2_sharc?: unknown } } | null)?.build?.dt2_sharc as - { version?: unknown; allocations?: unknown; players?: unknown } | undefined - // Version 1 is the render-hook format of the sidechain work, composed by its own path, not a machine part. + { version?: unknown; allocations?: unknown; players?: unknown; fx?: unknown } | undefined + // Version 1 is the render-hook format of the sidechain work, composed by its own path, not a part. if (part === undefined || part?.version === 1) return null if (!part || part.version !== 2 || !Array.isArray(part.allocations) || !Array.isArray(part.players)) { throw new Error(name + ': unsupported sound-chip part') @@ -87,20 +99,34 @@ export function readDt2SharcPart(name: string, document: unknown): Dt2SharcPart if (!Number.isInteger(address) || typeof data !== 'string' || typeof code !== 'boolean') throw new Error(name + ': malformed sound-chip allocation') const bytes = base64(data) if ((address as number) < DT2_BASE_SHARC.end && (address as number) + bytes.length > DT2_BASE_SHARC.selectors) { - throw new Error(name + ': its sound-chip code overlaps the base\'s machine parts') + throw new Error(name + ': its sound-chip code overlaps the base\'s sound-chip parts') } return { address: address as number, bytes, code } }) + const inCode = (pc: number) => { + const at = byteAddress(pc) + return allocations.some(block => block.code && at >= block.address && at + 6 <= block.address + block.bytes.length) + } const players = part.players.map(entry => { const { type, entry: pc } = entry as { type?: unknown; entry?: unknown } if (!Number.isInteger(type) || !Number.isInteger(pc)) throw new Error(name + ': malformed machine player') - const at = byteAddress(pc as number) - if (!allocations.some(block => block.code && at >= block.address && at + 6 <= block.address + block.bytes.length)) { - throw new Error(name + ': the player for type ' + String(type) + ' does not start in its own sound-chip code') - } + if (!inCode(pc as number)) throw new Error(name + ': the player for type ' + String(type) + ' does not start in its own sound-chip code') return { type: type as number, entry: pc as number } }) - return { module: name, allocations, players } + let fx: Dt2SharcPart['fx'] + if (part.fx !== undefined) { + const { listen, process, cost } = (part.fx ?? {}) as { listen?: unknown; process?: unknown; cost?: unknown } + for (const [what, pc] of [['listen', listen], ['process', process]] as const) { + if (pc !== undefined && (!Number.isInteger(pc) || !inCode(pc as number))) throw new Error(name + ': its effect ' + what + ' routine does not start in its own sound-chip code') + } + if (listen === undefined && process === undefined) throw new Error(name + ': an effect part names neither a listen nor a process routine') + if (!Number.isInteger(cost) || (cost as number) < 1 || (cost as number) > DT2_ADDED_BUDGET) { + throw new Error(name + ': an effect part declares its worst case as busy instructions a block, 1-' + DT2_ADDED_BUDGET) + } + fx = { ...(listen === undefined ? {} : { listen: listen as number }), ...(process === undefined ? {} : { process: process as number }), cost: cost as number } + } + if (!players.length && !fx) throw new Error(name + ': a sound-chip part with neither a machine player nor an effect') + return { module: name, allocations, players, ...(fx ? { fx } : {}) } } /** The bytes of `section` in a mod, from its own hex parts (a record never copies stock bytes). */ @@ -130,13 +156,30 @@ export function dt2RegisteredMachines(name: string, mod: ParsedMod): Dt2Machine[ }) } -/** The base's sound-chip parts for the registered machines, their modules' players and any frame receivers, plus the - * modules' own allocations, as one plan; null when the set registers no machine and brings no sound-chip part or frame - * receiver (the sound chip then stays stock). Types 7-10 get the selector of the stock type each stands for. */ +/** The effects a module registers in core_fx (mk2/fx.h), each with the linker's sort key. */ +export function dt2RegisteredEffects(name: string, mod: ParsedMod): Dt2Effect[] { + return mod.contribute.filter(entry => entry.to === 'core_fx').map(entry => ({ module: name, order: entry.order, id: mod.id, index: entry.index })) +} + +/** core_fx in the linker's order (contribution order, then module id, then the module's own order): an effect's + * position is its slot on the ColdFire and on the sound chip. */ +export function dt2EffectSlots(effects: readonly Dt2Effect[]): Dt2Effect[] { + const key = (effect: Dt2Effect) => [effect.order, effect.id, effect.index] as const + return [...effects].sort((a, b) => { + const [x, y] = [key(a), key(b)] + return x[0] - y[0] || (x[1] < y[1] ? -1 : x[1] > y[1] ? 1 : 0) || x[2] - y[2] + }) +} + +/** The base's sound-chip parts for the registered machines and effects, their modules' players and routines and any + * frame receivers, plus the modules' own allocations, as one plan; null when the set registers no machine or effect and + * brings no sound-chip part or frame receiver (the sound chip then stays stock). Types 7-10 get the selector of the + * stock type each stands for. Each effect's slot follows core_fx's order; a set over DT2_ADDED_BUDGET is refused. */ export async function planDt2MachineParts( sharc: Uint8Array, machines: readonly Dt2Machine[], parts: readonly Dt2SharcPart[], frameReceivers: readonly number[] = [], + effects: readonly Dt2Effect[] = [], ): Promise { - if (!machines.length && !parts.length && !frameReceivers.length) return null + if (!machines.length && !parts.length && !frameReceivers.length && !effects.length) return null for (const machine of machines) { if (!Number.isInteger(machine.type) || machine.type < DT2_FIRST_ADDED_TYPE || machine.type >= DT2_FIRST_ADDED_TYPE + DT2_ADDED_TYPES) { throw new Error(machine.module + ': machine type ' + machine.type + ' is not one of 7-10') @@ -153,31 +196,54 @@ export async function planDt2MachineParts( } return player })) - const standsFor = Array.from({ length: DT2_ADDED_TYPES }, (_, k) => machines.find(machine => machine.type === DT2_FIRST_ADDED_TYPE + k)?.standsFor ?? 0) - const selectors = await planDt2MachineSelectors(sharc, DT2_BASE_SHARC.selectors, standsFor) - const dispatcher = await planDt2MachinePlayers(sharc, DT2_BASE_SHARC.dispatcher, DT2_BASE_SHARC.dispatcherData, - DT2_BASE_SHARC.playerSlots, players, DT2_BASE_SHARC.trackTypes) + const slots = dt2EffectSlots(effects) + if (slots.length > DT2_FX_SLOTS) throw new Error('More than ' + DT2_FX_SLOTS + ' effects: ' + slots.map(effect => effect.module).join(', ')) + const entries = slots.map(effect => { + const fx = parts.find(part => part.module === effect.module)?.fx + if (!fx) throw new Error(effect.module + ': registers an effect in core_fx but carries no effect routine in its sound-chip part') + if (slots.filter(other => other.module === effect.module).length > 1) throw new Error(effect.module + ': registers more than one effect (one effect per module)') + return fx + }) + for (const part of parts) { + if (part.fx && !slots.some(effect => effect.module === part.module)) throw new Error(part.module + ': an effect routine without a core_fx record') + } + const cost = entries.reduce((sum, fx) => sum + fx.cost, 0) + if (cost > DT2_ADDED_BUDGET) { + throw new Error('The effects ask for ' + cost + ' busy sound-chip instructions a block, over the ' + DT2_ADDED_BUDGET + ' the base allows: ' + + slots.map((effect, k) => effect.module + ' ' + entries[k].cost).join(', ')) + } + const fx = entries.length ? await planDt2Fx(sharc, DT2_BASE_SHARC.fxSlots, DT2_BASE_SHARC.fxCode, DT2_BASE_SHARC.fxData, + DT2_BASE_SHARC.fxSettings, entries) : null + const machineParts = machines.length || players.length ? [ + await planDt2MachineSelectors(sharc, DT2_BASE_SHARC.selectors, + Array.from({ length: DT2_ADDED_TYPES }, (_, k) => machines.find(machine => machine.type === DT2_FIRST_ADDED_TYPE + k)?.standsFor ?? 0)), + await planDt2MachinePlayers(sharc, DT2_BASE_SHARC.dispatcher, DT2_BASE_SHARC.dispatcherData, + DT2_BASE_SHARC.playerSlots, players, DT2_BASE_SHARC.trackTypes), + ] : [] const receive = await planDt2FrameReceive(sharc, DT2_BASE_SHARC.wire, DT2_BASE_SHARC.wireData, DT2_BASE_SHARC.frameSlots, - frameReceivers.map(sharcProgramCounter)) - return combineDt2Plans(selectors, dispatcher, receive, ...parts.map(part => ({ allocations: part.allocations.map(({ address, bytes }) => ({ address, bytes })) }))) + frameReceivers.map(sharcProgramCounter), fx?.mailbox) + return combineDt2Plans(...machineParts, receive, fx ? { renderInstruction: fx.renderInstruction, allocations: fx.allocations } : null, + ...parts.map(part => ({ allocations: part.allocations.map(({ address, bytes }) => ({ address, bytes })) }))) } -/** The selected packages' machines and sound-chip parts, read from their documents. */ +/** The selected packages' machines, effects and sound-chip parts, read from their documents. */ export function readDt2MachineSet(documents: readonly { name: string; document: unknown }[]) { - const machines = documents.flatMap(({ name, document }) => dt2RegisteredMachines(name, parseElemod(document as Record, name))) + const mods = documents.map(({ name, document }) => ({ name, mod: parseElemod(document as Record, name) })) + const machines = mods.flatMap(({ name, mod }) => dt2RegisteredMachines(name, mod)) + const effects = mods.flatMap(({ name, mod }) => dt2RegisteredEffects(name, mod)) const parts = documents.map(({ name, document }) => readDt2SharcPart(name, document)).filter((part): part is Dt2SharcPart => part !== null) - return { machines, parts } + return { machines, effects, parts } } /** A finished kit build with the base's sound-chip parts and the selected modules', checked by the preflight with that - * plan; null when no selected module registers a machine or carries a sound-chip part, so the kit build stands as it - * is. The website's preflight and scripts/link-image.mjs both compose through this, so the same stock file, packages - * and version give the same image. */ + * plan; null when no selected module registers a machine or an effect or carries a sound-chip part, so the kit build + * stands as it is. The website's preflight and scripts/link-image.mjs both compose through this, so the same stock + * file, packages and version give the same image. */ export async function composeDt2MachineBuild(stockBytes: Uint8Array, kitBuildBytes: Uint8Array, mods: readonly ParsedMod[], documents: readonly { name: string; document: unknown }[]) { - const { machines, parts } = readDt2MachineSet(documents) - if (!machines.length && !parts.length) return null + const { machines, effects, parts } = readDt2MachineSet(documents) + if (!machines.length && !effects.length && !parts.length) return null const sharc = unpackDt2SharcSection(new Syx(stockBytes).stored.get(SHARC_SECTION)) - const plan = await planDt2MachineParts(sharc, machines, parts) + const plan = await planDt2MachineParts(sharc, machines, parts, [], effects) return plan ? buildDt2RenderFirmware(stockBytes, kitBuildBytes, mods, plan) : null } diff --git a/src/engine/elektron/dt2-sharc.ts b/src/engine/elektron/dt2-sharc.ts index fa3bd3ebbe..18b433abe0 100644 --- a/src/engine/elektron/dt2-sharc.ts +++ b/src/engine/elektron/dt2-sharc.ts @@ -377,9 +377,11 @@ export const DT2_FRAME_RECEIVERS = 4 * - restores what it kept, replays the displaced instruction and resumes. */ export async function planDt2FrameReceive( stock: Uint8Array, codeAddress: number, dataAddress: number, slotsAddress: number, receivers: readonly number[], + mailbox?: number, ): Promise { if (await sha256Hex(stock) !== STOCK_SECTION) throw new Error('Unsupported Digitakt II SHARC image') - if (receivers.length > DT2_FRAME_RECEIVERS || receivers.some(pc => !Number.isInteger(pc) || pc < L2_PROGRAM[0] || pc >= L2_PROGRAM[1])) { + if (receivers.length > DT2_FRAME_RECEIVERS || [...receivers, ...(mailbox === undefined ? [] : [mailbox])] + .some(pc => !Number.isInteger(pc) || pc < L2_PROGRAM[0] || pc >= L2_PROGRAM[1])) { throw new Error('Invalid SHARC frame receiver entry') } const displaced = await dt2DisplacedInstruction(stock, 'receive') @@ -436,6 +438,7 @@ knobbed: DM(I1, M0) = R0 DM(I0, M0) = R0 viewed: DM(I2, M0) = R0 absent: +${mailbox === undefined ? '' : ` CALL ${mailbox}`} ${Array.from({ length: DT2_FRAME_RECEIVERS }, (_, k) => ` CALL ${slot(k)}`).join('\n')} I2 = DM(${save + VIEW_SAVE}) L2 = DM(${save + VIEW_SAVE + 1}) @@ -549,3 +552,109 @@ export async function planDt2Render( ...(bridge ? { frameReceivers: [bridge.receiverAddress] } : {}), } } + +// The base's effect slot (docs/verification/2026-11-25-digitakt-ii-fx-slot.md): a fixed dispatcher at the pre-send render +// site that calls up to eight listen and eight process routines through registry slots, and a mailbox routine the +// frame receiver calls, which writes the ColdFire's settings pairs into each slot's settings block. +export const DT2_FX_SLOTS = 8, DT2_FX_WORDS = 16, DT2_FX_TRACKS = 15 +export const DT2_FX_MAILBOX_MAGIC = 0x46584d31 // "FXM1", the transfer tail's word 0 (fx.c) +const FX_MAILBOX_PAIRS = 7 +const I4 = 0x14 +const FX_REGISTERS = [...RENDER_REGISTERS, I4] + +/** An installed effect's sound-chip entries (short-word program counters), by slot (its place in core_fx). */ +export type Dt2FxEntries = { listen?: number; process?: number } + +/** A plan fragment for the effect slot: the registry slots at `slotsAddress` (listen 0-7, then process 0-7: a jump to + * the routine, or an RTS), the dispatcher and the mailbox routine at `codeAddress`, its register save area at + * `dataAddress` and the sixteen settings blocks at `settingsAddress` (sixteen words each: 0-14 the effect's, 15 its track + * mask). The dispatcher replaces the render site's instruction: it keeps the registers the stock path keeps and I4, + * calls each slot whose track mask is not 0 with I4 at its settings block, listen routines first, restores, replays the + * displaced instruction and resumes. `mailbox` is the routine's program counter, for planDt2FrameReceive. */ +export async function planDt2Fx( + stock: Uint8Array, slotsAddress: number, codeAddress: number, dataAddress: number, settingsAddress: number, + effects: readonly Dt2FxEntries[], +): Promise { + if (await sha256Hex(stock) !== STOCK_SECTION) throw new Error('Unsupported Digitakt II SHARC image') + if (effects.length > DT2_FX_SLOTS || effects.some(effect => [effect.listen, effect.process].some(pc => pc !== undefined && + (!Number.isInteger(pc) || pc < L2_PROGRAM[0] || pc >= L2_PROGRAM[1])))) { + throw new Error('Invalid SHARC effect entry') + } + const displaced = await dt2DisplacedInstruction(stock, 'render') + const save = dataAddress / 4, settings = (slot: number) => settingsAddress + 4 * DT2_FX_WORDS * slot + const slot = (k: number) => programCounter(slotsAddress) + k * SLOT_BYTES / 2 + const names = FX_REGISTERS.map(reg => reg < 0x10 ? 'R' + reg : ({ 0x10: 'I0', 0x11: 'I1', 0x12: 'I2', 0x14: 'I4', 0x24: 'M4', 0x25: 'M5', + 0x26: 'M6', 0x30: 'L0', 0x31: 'L1', 0x32: 'L2', 0x78: 'STKYX', 0x76: 'ASTATX' } as Record)[reg]) + const calls = (phase: number) => Array.from({ length: DT2_FX_SLOTS }, (_, k) => ` + I4 = ${settings(k)} + M4 = ${DT2_FX_TRACKS} + R0 = DM(M4, I4) + R0 = PASS R0 + IF EQ JUMP skip${phase}_${k} + CALL ${slot(phase * DT2_FX_SLOTS + k)} +skip${phase}_${k}:`).join('') + const pairs = Array.from({ length: FX_MAILBOX_PAIRS }, (_, k) => ` + M0 = ${2 + 2 * k} + R0 = DM(M0, I0) + M0 = ${3 + 2 * k} + R1 = DM(M0, I0) + R2 = -1 + COMP(R0, R2) + IF EQ JUMP next${k} + R2 = 15 + R3 = R0 AND R2 + R2 = -4 + R0 = LSHIFT R0 BY R2 + R2 = 0xf0 + R0 = R0 AND R2 + R0 = R0 OR R3 + M0 = R0 + I1 = ${settingsAddress} + DM(M0, I1) = R1 +next${k}:`).join('') + const { blocks: program, symbols } = assembleSharc(` +.code ${codeAddress} +dispatch: +${names.map((name, index) => ` DM(${save + index}) = ${name}`).join('\n')} +${calls(0)} +${calls(1)} +${names.map((name, index) => ` ${name} = DM(${save + index})`).join('\n')} +displaced: NOP + JUMP ${RENDER_RESUME} +mailbox: + DM(${save + 30}) = R2 + DM(${save + 31}) = R3 + R0 = I3 + R1 = ${TAIL} + R0 = R0 + R1 + I0 = R0 + M0 = 0 + R0 = DM(M0, I0) + R1 = ${DT2_FX_MAILBOX_MAGIC} + COMP(R0, R1) + IF NE JUMP done +${pairs} +done: + R2 = DM(${save + 30}) + R3 = DM(${save + 31}) + RTS +`) + if (program.length !== 1) throw new Error('Unexpected SHARC effect dispatcher layout') + const code = program[0].bytes + code.set(displaced, (symbols.get('displaced')! - programCounter(codeAddress)) * 2) + const slots = new Uint8Array(SLOT_BYTES * 2 * DT2_FX_SLOTS) + for (let phase = 0; phase < 2; phase++) { + for (let k = 0; k < DT2_FX_SLOTS; k++) { + const entry = phase ? effects[k]?.process : effects[k]?.listen + slots.set(entry === undefined ? SLOT_RTS : slotJump(entry), SLOT_BYTES * (phase * DT2_FX_SLOTS + k)) + } + } + const allocations = [ + { address: slotsAddress, bytes: slots }, + { address: codeAddress, bytes: code }, + { address: dataAddress, bytes: new Uint8Array(4 * 32) }, + { address: settingsAddress, bytes: new Uint8Array(4 * DT2_FX_WORDS * 16) }, + ] + checkAllocations(allocations) + return { renderInstruction: instruction(0x063e, symbols.get('dispatch')!), allocations, mailbox: symbols.get('mailbox')! } +}