diff --git a/changelog/2026-11-29-digitakt-ii-filter-types.md b/changelog/2026-11-29-digitakt-ii-filter-types.md new file mode 100644 index 0000000000..9e7720fea1 --- /dev/null +++ b/changelog/2026-11-29-digitakt-ii-filter-types.md @@ -0,0 +1 @@ +- Digitakt II base (development): modules can add filter types to each track's FLTR page, listed after the six stock types with their own names and knob names, saved with the kit, and running their own sound-chip routine with the stock filter envelope and LFO. Stock filters are unchanged; a kit saved with a module filter opens on the official OS with the default filter. A filter module names its routine and its cost in `build.json` (`sharc.filters`, `sharc.cost`). Run on one unit with a test filter. diff --git a/docs/verification/2026-11-25-digitakt-ii-filter-types.md b/docs/verification/2026-11-25-digitakt-ii-filter-types.md index 4802bc9ef4..1fb635781f 100644 --- a/docs/verification/2026-11-25-digitakt-ii-filter-types.md +++ b/docs/verification/2026-11-25-digitakt-ii-filter-types.md @@ -1,6 +1,6 @@ # Proposal: module filter types on the Digitakt II's FLTR page -Status: design approved by the owner on 25 November 2026 (types in the stock list, one type per module, stock movement, the per-voice site at `0x1c6c13`, `tables/7`), with four points folded in below: the official OS must open these kits, the fallback is the stock default, one budget per block, and how a fifth filter gets its number. No base code yet; the open points below come first. +Status: design approved by the owner on 25 November 2026 (types in the stock list, one type per module, stock movement, the per-voice site at `0x1c6c13`, `tables/7`), with four points folded in below: the official OS must open these kits, the fallback is the stock default, one budget per block, and how a fifth filter gets its number. Built in the base on this branch, checked in the emulator and on one unit (below). ## Why @@ -71,11 +71,11 @@ struct dt2_filter { }; ``` -Each module filter has its own fixed type number, claimed on the agent board and kept once released, because kits save it, so it needs the same protection as a machine id. The base code adds a board kind `filter-id` (`filter-id digitakt-ii/N`, in `KINDS` in `scripts/agent-board.mjs`), and `pr:ready` detects a package's new `filter:` the way it detects a new `machine:`. Until that kind exists, types 7 and 8 for the first two filters are claimed by hand as `machine-id` claims named `digitakt-ii/filter-7` and `digitakt-ii/filter-8`. Numbers start at 7 and have no fixed end below 127 (the stored byte is signed, and `0xff` means "none"): the fifth filter module claims 11, the sixth 12, and so on. Room 4 limits how many filters are installed together, not which numbers exist, so a fifth module only needs the room raised in a base update, and its type number never moves. The base's sound-chip table covers types up to the highest registered number. The base answers the descriptor lookup, the names, the list, the parameter codes and the kit-load check for registered types. An unregistered type loads as the stock default (type 0), as on the official OS. +Each module filter has its own fixed type number, claimed on the agent board and kept once released, because kits save it, so it needs the same protection as a machine id. The base code adds a board kind `filter-id` (`filter-id digitakt-ii/N`, in `KINDS` in `scripts/agent-board.mjs`), and `pr:ready` detects a package's new `filter:` the way it detects a new `machine:`. The kind came with #2447; types 7 (Vowel) and 8 (Notch/Peak) are claimed as `filter-id digitakt-ii/7` and `digitakt-ii/8`. Numbers start at 7 and have no fixed end below 127 (the stored byte is signed, and `0xff` means "none"): the fifth filter module claims 11, the sixth 12, and so on. Room 4 limits how many filters are installed together, not which numbers exist, so a fifth module only needs the room raised in a base update, and its type number never moves. The base's sound-chip table answers every index from -128 to 255. The base answers the descriptor lookup, the names, the list, the parameter codes and the kit-load check for registered types. An unregistered type loads as the stock default (type 0), as on the official OS. ### Sound-chip slots -A module's package carries its filter in `build.dt2_sharc` as machine players do, with `{ "filters": [{ "type": 7, "entry": "label" }] }`. The base keeps L2 `0x200c4000`-`0x200c4800` (after the effect slot's `0x200c3000`-`0x200c4000`) for its filter dispatcher, four slots (one 48-bit instruction each) and four per-voice state areas' pointers. The builder writes `JUMP entry` for a registered filter and a jump to its stand-in's stock case for a type with no code. The site at `0x1c6c13` becomes a jump to the dispatcher only for types 7 or more; types 0-5 take the stock path untouched. +A module's package carries its filter in `build.dt2_sharc` as machine players do, with `{ "filters": [{ "type": 7, "entry": "label" }] }`. The base keeps L2 `0x200c4000`-`0x200c4800` (after the effect slot's `0x200c3000`-`0x200c4000`) for its type table (`0x200c4000`), four slots (one 48-bit instruction each, `0x200c4600`) and its filter dispatcher (`0x200c4640`). The builder writes `JUMP entry` for a registered filter and a jump to its stand-in's stock case for a type with no code. The site at `0x1c6c13` becomes a jump to the dispatcher only for types 7 or more; types 0-5 take the stock path untouched. The dispatcher saves the registers the voice loop keeps (the machine work found `R0` live across a nearby test; the set will be read off a register dump before code is written), reads the type in `R2`, and calls the slot. A filter routine: @@ -97,9 +97,45 @@ Different site (effects: pre-send `0x1c18a6`; filters: per-voice dispatch `0x1c6 No module on the Digitakt II. On the Digitakt I, draadpiraat's Filters (#1445, draft) adds two types to the FLTR page by its own patch; that machine's base has no filter hook either, and nothing is shared between the two. -## Still to confirm before code +## Built so far (25 November 2026, development base, emulator only) -1. In a coupled run: that `DM(0x255990 + track)` follows the FLTR type the musician picks, and the field each stock type gives. A first scripted run (25 November, FUNC+FLTR, DOWN, YES twice, then a trig) left every voice's field at 1, the default type's, so that key sequence did not change the type; the next run picks it by the path the OS's list really uses. +- **ColdFire** (`filters.c`, `filters-entry.s`, `mk2/filters.h`): `core_filters` (room 4), and five guarded sites: the filter descriptor lookup `0x400c89c6`, the filter-type list getter `0x40052c98` (the menu that FUNC+SRC opens on the FLTR page), the name and short-name lookups `0x400da71e` and `0x400da744` (12-byte records at `0x4020ef30`), and the kit-load check `0x400db492`. The parameter-code lookup `0x400da3a2`, which the base already takes for machines, reads the filter type as its third argument for slots 35-37 (bound 5); its entry answers an added filter as its stand-in. The FLTR page's knob names follow the type on E, F and G. +- **Sound chip** (`planDt2FilterTable`): the lookup at `0x1c26df` points at a table in L2 `0x200c4000`-`0x200c4600` that answers every index from -128 to 255 (index 0 at `0x200c4200`), with a registered type's field set to its stand-in's. Builder tests with the owner's OS check the six stock words (1, 3, 2, 4, 5, 6), the stand-ins' words, none for every other number, and that a set with filters and no machine changes only this site. +- **Panel probe** (development base `a444e01d`, a test filter standing for Multi-Mode): the list shows TEST FILTER after EQUALIZER; choosing it sets track 1's filter byte to 7; the FLTR page shows TFRQ, TRES and TMOR; no fault. The filter picture above FREQ and RESO is not drawn for the added type (a per-type view switch, still to find). +- **Coupled run** (development base `85ccfb78`, the test filter standing for Lowpass 4, image `ea693607`): choosing TEST FILTER runs per-voice field 3 (Lowpass 4) on track 1, and the PCM since the ready point is identical to choosing Lowpass 4 (`82c37eb7`). So an added type reaches the sound chip as itself and plays as its stand-in. + +## Later checks (29-30 November 2026) + +- **Track 9** (emulator, image `f3dev`): with the test filter on track 9 and track 1 on a stock type, the routine ran for voices 16 and 17 only, so filter types reach the sound chip per track (the machine words' track-1-only trap does not apply). +- **The official OS opens these kits** (emulator, stock OS 1.17 image, a persistence card): track 1's filter byte set to 7, SAVE PROJECT, the byte set to 5, LOAD PROJECT. The load routine read the stored 7 (`d0` at `0x400db492`), stored 0, and the FLTR page drew Multi-Mode; no fault. On the development base the same round trip keeps 7. +- **The FLTR page's picture** (`0x40074580`, a switch on types 0-5) now answers an added type as its stand-in. +- **One budget**: packages declare `build.dt2_sharc` `cost`; the builder sums machines, filters and effects against `DT2_SHARC_BUDGET`. +- **Unit**, Digitakt II, OS 1.17, image `443ff13134c316e4e40df919cdc63b859b1a4af0b2d51396ac8de1c03b4fdf58` (development base `6273bc6b` with a test routine for filter 7 that halves the voice, standing for Lowpass 4), run by Claptom-music on 30 November 2026, reported as all steps passed: the type list showed the six stock types and TEST FILTER last; the stock types sounded as before; TEST FILTER played the track at about half level without clicks and showed Lowpass 4's box with TFRQ and TRES; back on Lowpass 4 the level returned; with TEST FILTER on track 9 and a stock type on track 1 only track 9 was quieter; SAVE PROJECT, another project and back kept TEST FILTER; a busy pattern with it on several tracks ran for a minute without freezes or clicks; the saved project loaded on the official OS 1.17 with Multi-Mode and no freeze. + +## The owner's review (30 November 2026) + +- **Claims**: `filter-id digitakt-ii/7` and `/8` are on the board. +- **Build path**: a module's `build.json` names its routine in `sharc.filters` (`{type, entry label}`, type 7-126 claimed as `filter:`) with `sharc.cost` above 0; a filter-only part needs no `players`. The package build writes both into `build.dt2_sharc`. The contract refuses a routine without a cost or with cost 0, an unclaimed or out-of-range type and an empty part; the builder refuses cost 0 too. +- **The sound chip's bound**: the index the table is read with is the track's word at `0x255990` as it is (`M0 = DM(I1, M4)`, `0x1c26c5`); nothing bounds it on stock either. The table now answers -128 to 255, every index but the six stock ones and the registered types giving 0 (no filter), so neither a stored `0xff` (255 or, sign-extended, -1) nor any other byte reaches a slot. Builder tests read indices -128, -1, 127, 128 and 255 as 0. +- **`d4` after the picture switch** (`filters-entry.s`): after `0x40074588` every case ends at `0x40074800`, which restores `d4` with the other saved registers before `rts`; the only later uses (`0x40074670` on) are on another path and write `d4` first. Nothing reads the stand-in type after the switch. +- **After #2445 merges in**: the shared `I4` constant, one budget for effects with machines and filters, and the table order in `interface.json` and `base.json`. +- **Builder tests** added: more than four routines, module code over the filter range, the filter-only set (only the filter parts and the module's code). + +Unit cases for the combined image (not run yet): + +1. The base with no filter module installed, against stock: every stock filter type sounds and draws as before. +2. Morpha on machine type 9 after the parameter-lookup change in `machines-entry.s`: its knobs and sound as before. +3. Two filter types in one kit, on two tracks, with the knob names switching between them. +4. A kit naming a filter type the build doesn't have, opened on the official OS 1.17. +5. A cycle count with a filter routine on every voice. + +## Open (as of 30 November 2026) + +Items 1, 3 and 4 below are done; item 2, where each stand-in keeps its cooked cutoff, is open in [FILTERS.md](../../sdk/machines/digitakt-ii/elekloader/modwerk/FILTERS.md), and a unit cycle count sets the budget again. + +## Confirmed before code + +1. Done for track 1 (above). Still to check on other tracks: the machine work found the sound chip's own per-track machine words held the added type for track 1 only, so a run with the filter on track 9 decides whether the filter types need the same treatment. 2. Where the stand-in's cooked cutoff and second value live per voice: inside each filter's own per-voice state (`R4` at its case). Whether that state is updated for a voice on another type decides whether a module filter reads it there or the base computes it. 3. Registers: the stock cases call their routine as a compiled function, so the module routine's contract is the same (keep the compiler's preserved registers, `R15` saved by the caller); `R0` holds the comparison from `0x1c6c10` when the branch is taken. 4. The ColdFire list, names and parameter-code sites. diff --git a/scripts/build-elemod-packages.mjs b/scripts/build-elemod-packages.mjs index d0da445860..3c7a77faed 100644 --- a/scripts/build-elemod-packages.mjs +++ b/scripts/build-elemod-packages.mjs @@ -149,15 +149,18 @@ 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 code (machine players, filter 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 sound-chip code: ' + 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 } + const entries = list => (list ?? []).map(item => { + const entry = program.symbols.get(item.entry) + if (entry === undefined) throw new Error(document.id + ': no label ' + item.entry + ' in ' + build.sharc.source) + return { type: item.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 players = entries(build.sharc.players), filters = entries(build.sharc.filters) + 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, + ...(filters.length ? { filters } : {}), ...(build.sharc.cost === undefined ? {} : { cost: build.sharc.cost }) } } } 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..57d0e3ce7a 100644 --- a/sdk/digitakt-ii/core-profile/interface.json +++ b/sdk/digitakt-ii/core-profile/interface.json @@ -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_filters", + "since": "1.1", + "entry": 4, + "room": 4, + "purpose": "Null-terminated pointers to struct dt2_filter records (mk2/filters.h): filter types added after the six stock ones, each with its own fixed type from 7 (claimed as filter-id digitakt-ii/N, saved with kits; numbers have no fixed end below 127, room limits how many are installed together), the stock type it stands for, its names and its three knob names (E-G) on the stand-in's parameters. The base lists them in the FLTR page's type list, shows their names and the stand-in's picture, keeps them through kit load (an unregistered type loads as the stock default, as on the official OS) and, when the module's package carries a build.sharc filter routine, calls it for their voices on the sound chip in one of four slots with the stand-in's per-voice state; without one they filter as the stock type they stand for. Proposal board index: tables/7, after core_fx (#2146)." } ], "exports": [ diff --git a/sdk/machines/digitakt-ii/README.md b/sdk/machines/digitakt-ii/README.md index 0278a6cb79..bddd9027e9 100644 --- a/sdk/machines/digitakt-ii/README.md +++ b/sdk/machines/digitakt-ii/README.md @@ -44,7 +44,7 @@ By the core's documentation (emulator-tested, not hardware-tested), both data ar 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 [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. -**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. +**Filters are the base's filter types.** A filter module never patches the per-voice filter on the sound chip: it registers one type in `core_filters`, listed after the six stock types (FUNC+SRC on the FLTR page), with its own names on knobs E-G over the rows of the stock type it stands for, and its routine runs in that type's slot with the stand-in's moving cutoff ([FILTERS.md](elekloader/modwerk/FILTERS.md), [proposal and emulator record](../../../docs/verification/2026-11-25-digitakt-ii-filter-types.md)). Machines, filters and effects share one sound-chip budget per block. The proposed Mixer and frame interfaces are declared in [core-profile/interface.json](../../digitakt-ii/core-profile/interface.json). diff --git a/sdk/machines/digitakt-ii/elekloader/base.json b/sdk/machines/digitakt-ii/elekloader/base.json index cf361633d5..cf2384cd26 100644 --- a/sdk/machines/digitakt-ii/elekloader/base.json +++ b/sdk/machines/digitakt-ii/elekloader/base.json @@ -50,6 +50,8 @@ "../modwerk/machine-knobs.c", "../modwerk/machine-frame.c", "../modwerk/machines-entry.s", + "../modwerk/filters.c", + "../modwerk/filters-entry.s", "../modwerk/voices.c", "../modwerk/voices-entry.s", "../modwerk/fw-bindings.s" @@ -330,6 +332,48 @@ "stockSha256": "0166e13a30fefeb32317b7893a65d1b7f86a9432659ec84c3b1b1982262375f3", "op": "jmp", "target": "core_machine_slot_entry_1844c" + }, + { + "addr": "0x400c89c6", + "len": 6, + "stockSha256": "ee3af96091c4b93c7521b8497449ed07268395479720ba1a8e05987f14d25a60", + "op": "jmp", + "target": "core_filter_descriptor_entry" + }, + { + "addr": "0x40052c98", + "len": 8, + "stockSha256": "7c6d66d691f9f6af7a3a8f3f31d35c8bdaf38f4ed587f0908c1e95894640ffd6", + "op": "jmp", + "target": "core_filter_list_entry" + }, + { + "addr": "0x400db492", + "len": 16, + "stockSha256": "3f7c0914e158f38eeed2b22d145a76b742f97bf1cbed7f18de2fcc310a1a6c2a", + "op": "jmp", + "target": "core_filter_kit_type_entry" + }, + { + "addr": "0x400da71e", + "len": 6, + "stockSha256": "ee3af96091c4b93c7521b8497449ed07268395479720ba1a8e05987f14d25a60", + "op": "jmp", + "target": "core_filter_name_entry" + }, + { + "addr": "0x400da744", + "len": 6, + "stockSha256": "ee3af96091c4b93c7521b8497449ed07268395479720ba1a8e05987f14d25a60", + "op": "jmp", + "target": "core_filter_short_entry" + }, + { + "addr": "0x40074580", + "len": 8, + "stockSha256": "64e7d850317c6f861939f2dde60a9f1f307547aca52162721f06f162b98dfe57", + "op": "jmp", + "target": "core_filter_view_entry" } ], "collections": { @@ -339,15 +383,30 @@ "core_mixer_pages": 4, "ev_audio_frame": 4, "core_project_archive": 4, - "core_machines": 4 + "core_machines": 4, + "core_filters": 4 } }, "dev": { - "about": "A development base adds one test machine (type 7) that stands for SAMPLE, to check the machine hooks in the emulator. Never released.", + "about": "A development base adds one test machine (type 7) that stands for SAMPLE and one test filter (type 7) that stands for Lowpass 4, to check the machine and filter hooks in the emulator. Never released.", "sources": [ - "../base/machines-fixture.c" + "../base/machines-fixture.c", + "../base/filters-fixture.c" ], "contribute": [ + { + "to": "core_filters", + "order": 50, + "data": "00000000", + "relocs": [ + [ + 0, + "abs32", + "sym:dt2_test_filter", + 0 + ] + ] + }, { "to": "core_machines", "order": 50, diff --git a/sdk/machines/digitakt-ii/elekloader/base/filters-fixture.c b/sdk/machines/digitakt-ii/elekloader/base/filters-fixture.c new file mode 100644 index 0000000000..9f34be64df --- /dev/null +++ b/sdk/machines/digitakt-ii/elekloader/base/filters-fixture.c @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Development base only: one added filter type (7) that stands for Lowpass 4 (type 1; not the default type, so a + * test can tell them apart on the sound chip), with its own names and knob names on E, F and G. */ +#include + +const struct dt2_filter dt2_test_filter = { + .type = 7, + .stands_for = 1, + .strings = { "Test Filter", "TST" }, + .knobs = { + { "Test Frequency", "TFRQ" }, + { "Test Resonance", "TRES" }, + { "Test Morph", "TMOR" }, + }, +}; diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/FILTERS.md b/sdk/machines/digitakt-ii/elekloader/modwerk/FILTERS.md new file mode 100644 index 0000000000..5ba2a7cf2c --- /dev/null +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/FILTERS.md @@ -0,0 +1,36 @@ +# Digitakt II filter types + +The base lets a module add a filter type after the six stock ones on the FLTR page (OS 1.17: Multi-Mode 0, Lowpass 4 1, Equalizer 2, Comb- 3, Legacy LP/HP 4, Comb+ 5). The design, the stock sites and the emulator record are in [the proposal](../../../../../docs/verification/2026-11-25-digitakt-ii-filter-types.md); this page is the contract a filter module works to. + +## The record + +Contribute one pointer to a `const struct dt2_filter` (`mk2/filters.h`) to `core_filters`: + +- `type`: your filter type, 7 to 126, claimed on the agent board as `filter-id digitakt-ii/` and kept once released (kits save it). List it as `filter:` in your manifest's `platform.claims` and `build.json`'s `claims`; `pr:ready` then asks for the claim. 7 (Vowel) and 8 (Notch/Peak) are taken. +- `stands_for`: the stock type (0-5) whose knob rows, ranges, picture and per-voice values you borrow. Knobs E, F and G are the stand-in's own parameters on sound slots 36, 37 and 35, so locks, LFO, MIDI and saving work as on the stand-in. +- `strings`: the name and short name in the type list. +- `knobs`: your names for E, F and G (a null name keeps the stand-in's). + +Without the module, a kit that names your type loads with the stock default, Multi-Mode, as the official OS does. + +## The routine + +Name it in your `build.json`'s sound-chip part, as a machine module names its player: + +```json +"sharc": { "source": "src/filter.sharc", "filters": [{ "type": 7, "entry": "vowel_filter" }], "cost": 12000 } +``` + +`entry` is a label in your `.sharc` source; the package build assembles it and writes the routine's program counter into the package's `build.dt2_sharc`. A filter-only module needs no `players`. `cost` is required and above 0: your worst case in instructions per 32-sample block over the stand-in's stock filter work it replaces, at the voices your type can really hold (32 when every voice uses it). At most four filter routines fit in one set. The base calls yours for each voice whose track uses your type, once per block, in place of the stand-in's stock routine, exactly as the stock case calls a stock routine: + +- `R8` and `R12`: the voice's 32 samples, 32-bit floats one word apart, filtered in place. +- `R4`: the stand-in's per-voice state for this voice, where the stock filter keeps its coefficients and history. +- A linked call (`CCALL`): return with the stock epilogue (`CRET`), keep the registers a compiled SHARC function keeps, use only `R0`-`R2`, `R4`, `R8`, `R12`, `I4`, `I12`, `M4`, `M12` freely. `M5` is 0, `M6` 1 and `M7` -1, as the C runtime keeps them. +- Your own state per voice lives in an L2 range you claim as a `dsp-region`. The [SHARC code rules](../../README.md#sharc-code-rules) apply. + +The builder refuses a set whose machines, filters and effects together pass the shared budget (`DT2_SHARC_BUDGET`, 60,000 instructions a block for now), a filter routine without a cost above 0, more than four routines, and module code inside the base's filter range (L2 `0x200c4000`-`0x200c4800`). + +## Open + +- Which words of each stand-in's state hold the cooked cutoff and resonance (after the envelope, LFO and key tracking): to read off a register dump at each stock routine, and record here. +- A unit cycle count of a stock filter per voice, to set the budget again. diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/filters-entry.s b/sdk/machines/digitakt-ii/elekloader/modwerk/filters-entry.s new file mode 100644 index 0000000000..7b797d888d --- /dev/null +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/filters-entry.s @@ -0,0 +1,134 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Added filter types (filters.c). Each entry answers an added type the base knows and otherwise replays the displaced + * stock instructions and continues in stock. a0 and a1 are kept, as stock leaves them. */ + .text + .even + +/* Filter descriptor lookup (0x400c89c6): (type) -> 44-byte descriptor. Replays `moveq #5,%d1; move.l 4(%sp),%d0`. */ + .globl core_filter_descriptor_entry, core_stock_filter_descriptor +core_filter_descriptor_entry: + move.l %a0,-(%sp) + move.l %a1,-(%sp) + move.l 12(%sp),-(%sp) + jsr core_filter_knob_names | the knob rows' names follow the type asked for + addq.l #4,%sp + move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + moveq #7,%d1 + move.l 4(%sp),%d0 + cmp.l %d1,%d0 + bcs.s 2f + move.l %a0,-(%sp) + move.l %a1,-(%sp) + move.l %d0,-(%sp) + jsr core_filter_descriptor + addq.l #4,%sp + move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + tst.l %d0 + beq.s 1f + rts +1: move.l 4(%sp),%d0 +2: moveq #5,%d1 + jmp 0x400c89cc +/* The stock lookup for a stock type, callable from C: (type) -> descriptor; clobbers d0 and d1. */ +core_stock_filter_descriptor: + moveq #5,%d1 + move.l 4(%sp),%d0 + jmp 0x400c89cc + +/* The filter-type list getter (0x40052c98; a0: the result vector): run stock, then let the base append the added + * types. Replays `lea -12(%sp),%sp; movem.l %d2/%a2-%a3,(%sp)`. */ + .globl core_filter_list_entry +core_filter_list_entry: + move.l %a0,-(%sp) + move.l 8(%sp),-(%sp) + bsr.s stock_filter_list + addq.l #4,%sp + move.l %d0,-(%sp) + move.l 4(%sp),-(%sp) + jsr core_filter_list_extend + addq.l #4,%sp + move.l (%sp)+,%d0 + move.l (%sp)+,%a0 + rts +stock_filter_list: + lea -12(%sp),%sp + movem.l %d2/%a2-%a3,(%sp) + jmp 0x40052ca0 + +/* Sound load (0x400db492, 16 bytes): d0 holds the stored filter type byte. Stock keeps 0-5 and 0xff and turns + * anything else into 0; the base also keeps an installed added type. Leaves d2 = 4, as the replaced code does, and + * stores nothing itself: stock stores d0 at 0x400db4a2. */ + .globl core_filter_kit_type_entry +core_filter_kit_type_entry: + move.l %a0,-(%sp) + move.l %a1,-(%sp) + move.l %d0,-(%sp) + jsr core_filter_kit_type + addq.l #4,%sp + move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + moveq #4,%d2 + jmp 0x400db4a2 + +/* The FLTR page's filter picture (0x40074580, 8 bytes): a switch on the filter type in d4 draws types 0-5 and + * nothing above. An added type draws as the stock type it stands for. Replays `moveq #5,%d0; cmp.l %d4,%d0; + * bcs.w 0x4007461a` and continues at the switch, 0x40074588. Keeps d1, a0 and a1. */ + .globl core_filter_view_entry +core_filter_view_entry: + moveq #7,%d0 + cmp.l %d0,%d4 + bcs.s 1f + move.l %d1,-(%sp) + move.l %a0,-(%sp) + move.l %a1,-(%sp) + move.l %d4,-(%sp) + jsr core_filter_stands_for + addq.l #4,%sp + move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + move.l (%sp)+,%d1 + tst.l %d0 + bmi.s 1f + move.l %d0,%d4 +1: moveq #5,%d0 + cmp.l %d4,%d0 + bcs.s 2f + jmp 0x40074588 +2: jmp 0x4007461a + +/* The two filter-string lookups (type): name and short name. An added type answers from its record, others replay + * `moveq #5,%d1; move.l 4(%sp),%d0` and continue in stock. */ + .macro FILTER_STRING label, field, cont + .globl \label +\label: + move.l 4(%sp),%d0 + moveq #7,%d1 + cmp.l %d1,%d0 + bcs.s 2f + move.l %a0,-(%sp) + move.l %a1,-(%sp) + move.l %d0,-(%sp) + jsr core_filter_stands_for + addq.l #4,%sp + tst.l %d0 + bmi.s 1f + move.l #\field,-(%sp) + move.l 16(%sp),-(%sp) + jsr core_filter_string + addq.l #8,%sp + move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + rts +1: move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + move.l 4(%sp),%d0 +2: moveq #5,%d1 + jmp \cont + .endm + + FILTER_STRING core_filter_name_entry, 0, 0x400da724 + FILTER_STRING core_filter_short_entry, 1, 0x400da74a + + .section .note.GNU-stack,"",@progbits diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/filters.c b/sdk/machines/digitakt-ii/elekloader/modwerk/filters.c new file mode 100644 index 0000000000..4ab4f328c9 --- /dev/null +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/filters.c @@ -0,0 +1,169 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Filter types added after the six stock ones (OS 1.17). The design follows the machine list (machines.c, + * machine-knobs.c): an added filter answers every per-type lookup as the stock type it stands for, except for its + * names and its knob names, and kits keep it only while its module is installed. The sites are in filters-entry.s + * and the proposal (docs/verification/2026-11-25-digitakt-ii-filter-types.md). */ +#include + +extern const struct dt2_filter *const core_filters[DT2_FILTER_COUNT]; + +#define STOCK_FILTERS 6u + +const struct dt2_filter *dt2_filter_at(uint32_t type, const struct dt2_filter *const filters[DT2_FILTER_COUNT]) +{ + if (type < DT2_FILTER_FIRST || type >= DT2_FILTER_END) { + return 0; + } + for (uint32_t i = 0; i < DT2_FILTER_COUNT && filters[i]; ++i) { + const struct dt2_filter *filter = filters[i]; + if (filter->type == type) { + return filter->stands_for < STOCK_FILTERS ? filter : 0; + } + } + return 0; +} + +/* The stock type an added filter borrows, or -1 for a stock type or an unregistered one. */ +int32_t core_filter_stands_for(uint32_t type) +{ + const struct dt2_filter *filter = dt2_filter_at(type, core_filters); + return filter ? (int32_t)filter->stands_for : -1; +} + +/* A sound's stored filter type as a load keeps it: stock types and 0xff as stock does, an added type whose module is + * installed, and the stock default (0) for anything else, as the official OS does. */ +uint32_t core_filter_kit_type(uint32_t stored) +{ + uint32_t type = stored & 0xff; + if ((uint8_t)(type + 1) < STOCK_FILTERS + 1) { + return type; + } + return dt2_filter_at(type, core_filters) ? type : 0; +} + +/* The filter-type list: the stock getter (0x40052c98) fills a vector of filter types ({begin, end, capacity}) from a + * static list of the six in menu order; the base appends the added types after them. The stock buffer it replaces is + * a few words and is not freed. */ +struct type_vector { + uint32_t *begin, *end, *capacity; +}; + +extern void *OP_NEW(uint32_t size); + +void core_filter_list_extend(struct type_vector *list) +{ + uint32_t added = 0; + for (uint32_t i = 0; i < DT2_FILTER_COUNT && core_filters[i]; ++i) { + added += dt2_filter_at(core_filters[i]->type, core_filters) != 0; + } + if (!added || !list || !list->begin) { + return; + } + uint32_t count = (uint32_t)(list->end - list->begin); + uint32_t *types = OP_NEW((count + added) * sizeof(uint32_t)); + if (!types) { + return; + } + for (uint32_t i = 0; i < count; ++i) { + types[i] = list->begin[i]; + } + uint32_t next = count; + for (uint32_t i = 0; i < DT2_FILTER_COUNT && core_filters[i] && next < count + added; ++i) { + if (dt2_filter_at(core_filters[i]->type, core_filters)) { + types[next++] = core_filters[i]->type; + } + } + list->begin = types; + list->end = types + next; + list->capacity = list->end; +} + +/* One of a filter's strings (DT2_FILTER_NAME or _SHORT); call only for a type core_filter_stands_for answers. */ +const char *core_filter_string(uint32_t type, uint32_t field) +{ + const struct dt2_filter *filter = dt2_filter_at(type, core_filters); + return filter && field <= DT2_FILTER_SHORT ? filter->strings[field] : 0; +} + +/* Knob names. A filter descriptor holds, like a machine's, a name, a label and eight parameter codes for knobs A-H; + * on the FLTR page E, F and G are the type's own knobs (sound slots 36, 37, 35). An added filter's descriptor is its + * stand-in's; when a page asks for it, the base points those rows' names at the filter's knob names, and back when + * it asks for any other type, as machine-knobs.c does for machines. */ +#define PARAMS ((uint32_t *)0x4020f59cu) /* 275 rows of 0x3c bytes */ +#define PARAM_ROWS 275u +#define ROW_WORDS 15u +#define ROW_NAME 10u /* +0x28 */ +#define ROW_SHORT 12u /* +0x30 */ + +static const uint8_t KNOB_POSITION[DT2_FILTER_KNOBS] = { 4, 5, 6 }; + +extern const uint32_t *core_stock_filter_descriptor(uint32_t type); + +static uint32_t descriptors[DT2_FILTER_COUNT][11]; +static uint32_t built_type[DT2_FILTER_COUNT]; + +const uint32_t *core_filter_descriptor(uint32_t type) +{ + const struct dt2_filter *filter = dt2_filter_at(type, core_filters); + if (!filter) { + return 0; + } + uint32_t n = 0; + while (n < DT2_FILTER_COUNT && core_filters[n] != filter) { + ++n; + } + if (n == DT2_FILTER_COUNT) { + return 0; + } + if (built_type[n] != type) { + const uint32_t *stock = core_stock_filter_descriptor(filter->stands_for); + for (uint32_t w = 0; w < 11; ++w) { + descriptors[n][w] = stock[w]; + } + built_type[n] = type; + } + return descriptors[n]; +} + +static struct { uint32_t code, name, shortname; } saved[DT2_FILTER_KNOBS]; +static uint32_t saved_count; +static uint32_t shown; /* the added type whose names the rows carry, 0 for none */ + +static void restore(void) +{ + for (uint32_t i = 0; i < saved_count; ++i) { + uint32_t *row = &PARAMS[saved[i].code * ROW_WORDS]; + row[ROW_NAME] = saved[i].name; + row[ROW_SHORT] = saved[i].shortname; + } + saved_count = 0; + shown = 0; +} + +/* Called by the filter descriptor lookup (filters-entry.s) for every type it is asked for. */ +void core_filter_knob_names(uint32_t type) +{ + const struct dt2_filter *filter = dt2_filter_at(type, core_filters); + if ((filter ? type : 0) == shown) { + return; + } + restore(); + if (filter) { + const uint32_t *descriptor = core_filter_descriptor(type); + for (uint32_t knob = 0; descriptor && knob < DT2_FILTER_KNOBS; ++knob) { + const struct dt2_filter_knob *k = &filter->knobs[knob]; + uint32_t code = descriptor[2 + KNOB_POSITION[knob]]; + if (!k->name || !code || code >= PARAM_ROWS) { + continue; + } + uint32_t *row = &PARAMS[code * ROW_WORDS]; + saved[saved_count].code = code; + saved[saved_count].name = row[ROW_NAME]; + saved[saved_count].shortname = row[ROW_SHORT]; + ++saved_count; + row[ROW_NAME] = (uint32_t)k->name; + row[ROW_SHORT] = (uint32_t)(k->label ? k->label : k->name); + } + shown = type; + } +} diff --git a/sdk/machines/digitakt-ii/elekloader/modwerk/machines-entry.s b/sdk/machines/digitakt-ii/elekloader/modwerk/machines-entry.s index fc96b4ebd8..eaf82ca77c 100644 --- a/sdk/machines/digitakt-ii/elekloader/modwerk/machines-entry.s +++ b/sdk/machines/digitakt-ii/elekloader/modwerk/machines-entry.s @@ -38,8 +38,29 @@ core_stock_descriptor: move.l 4(%sp),%d0 jmp 0x400c89aa -/* (slot, type, out) */ +/* (slot, machine type, filter type): sound slots 25-34 read the machine type, 35-37 the filter type (bound 5). An added + * filter type answers as the stock type it stands for (filters.c); the call then goes on as below with it. */ core_machine_param_entry: + moveq #7,%d1 + move.l 12(%sp),%d0 + cmp.l %d1,%d0 + bcs.s machine_param + move.l %a0,-(%sp) + move.l %a1,-(%sp) + move.l %d0,-(%sp) + jsr core_filter_stands_for + addq.l #4,%sp + move.l (%sp)+,%a1 + move.l (%sp)+,%a0 + tst.l %d0 + bmi.s machine_param + move.l %d0,-(%sp) + move.l 12(%sp),-(%sp) + move.l 12(%sp),-(%sp) + bsr.s machine_param + lea 12(%sp),%sp + rts +machine_param: moveq #7,%d1 move.l 8(%sp),%d0 cmp.l %d1,%d0 diff --git a/sdk/machines/digitakt-ii/include/mk2/filters.h b/sdk/machines/digitakt-ii/include/mk2/filters.h new file mode 100644 index 0000000000..25bb15170e --- /dev/null +++ b/sdk/machines/digitakt-ii/include/mk2/filters.h @@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef MODWERK_DT2_FILTERS_H +#define MODWERK_DT2_FILTERS_H + +#include + +/* Filter types added after the six stock ones (Multi-Mode 0, Lowpass 4 1, Equalizer 2, Comb- 3, Legacy LP/HP 4, + * Comb+ 5). Each record names its own filter type, a fixed number from DT2_FILTER_FIRST that kits save: claim it on + * the agent board (filter-id digitakt-ii/N) and keep it once released. Numbers have no fixed end below + * DT2_FILTER_END; core_filters holds up to DT2_FILTER_COUNT records installed together and ends at its first null + * entry. A kit that names a type no installed module provides loads with the stock default (0), as on the + * official OS. */ +enum { + DT2_FILTER_FIRST = 7, + DT2_FILTER_END = 127, + DT2_FILTER_COUNT = 4, +}; + +enum { + DT2_FILTER_NAME = 0, /* the filter-type list and the FLTR page, as "Multi-Mode" */ + DT2_FILTER_SHORT = 1, /* up to five capitals, as "LP4" */ +}; + +/* The three FLTR knobs a filter type names itself: E (FREQ), F and G, the stand-in type's own parameters on sound + * slots 36, 37 and 35. Their range, value, saving, trig locks, LFO, MIDI and the values the sound chip receives are + * the stand-in's. A null name keeps the stand-in's knob and name. */ +enum { + DT2_FILTER_KNOBS = 3, +}; + +struct dt2_filter_knob { + const char *name; + const char *label; +}; + +/* stands_for names the stock type (0-5) whose descriptor, knob rows and per-voice values the filter borrows. On the + * sound chip a voice on this type runs the module's filter routine (build.sharc "filters") in place of a stock one; + * a filter with no routine filters as its stand-in. */ +struct dt2_filter { + uint32_t type; + uint32_t stands_for; + const char *strings[2]; + struct dt2_filter_knob knobs[DT2_FILTER_KNOBS]; +}; + +/* The record for a filter type, or 0 when the type is stock or no valid record names it. */ +const struct dt2_filter *dt2_filter_at(uint32_t type, const struct dt2_filter *const filters[DT2_FILTER_COUNT]); + +#endif diff --git a/src/catalog/module-contract-v3.test.ts b/src/catalog/module-contract-v3.test.ts index 66e9dfd1be..549d74b7e2 100644 --- a/src/catalog/module-contract-v3.test.ts +++ b/src/catalog/module-contract-v3.test.ts @@ -123,6 +123,19 @@ describe('module contract v3', () => { expect(() => parseElemodBuild({ ...build, sharc: { ...sharc, players: [{ type: 3, entry: 'grain_player' }] } }, document)).toThrow('7 to 10') expect(() => parseElemodBuild({ ...build, sharc: { ...sharc, source: 'src/player.s' } }, document)).toThrow('.sharc source') }) + + it('takes a filter module\'s routine for the filter types it claims, with its cost', () => { + const base = parse(template()) + const document = { ...base, platform: { ...base.platform, claims: ['filter:7'] } } as typeof base + const build = { ...JSON.parse(readFileSync(resolve('sdk/templates/elemod/build.json'), 'utf8').replace('__RELEASE__', '1.54')), claims: ['filter:7'] } + const sharc = { source: 'src/vowel.sharc', filters: [{ type: 7, entry: 'vowel_filter' }], cost: 4000 } + expect(parseElemodBuild({ ...build, sharc }, document).sharc).toEqual({ ...sharc, players: [] }) + expect(() => parseElemodBuild({ ...build, sharc: { ...sharc, cost: undefined } }, document)).toThrow('more than 0') + expect(() => parseElemodBuild({ ...build, sharc: { ...sharc, cost: 0 } }, document)).toThrow('more than 0') + expect(() => parseElemodBuild({ ...build, sharc: { ...sharc, filters: [{ type: 8, entry: 'vowel_filter' }] } }, document)).toThrow('filter:8') + expect(() => parseElemodBuild({ ...build, sharc: { ...sharc, filters: [{ type: 5, entry: 'vowel_filter' }] } }, document)).toThrow('7 to 126') + expect(() => parseElemodBuild({ ...build, sharc: { source: 'src/vowel.sharc' } }, document)).toThrow('a machine player or a filter routine') + }) }) describe('module contract v3, zdl (Zoom effect files)', () => { diff --git a/src/catalog/module-contract-v3.ts b/src/catalog/module-contract-v3.ts index 8ce338072b..566c24844d 100644 --- a/src/catalog/module-contract-v3.ts +++ b/src/catalog/module-contract-v3.ts @@ -342,8 +342,10 @@ export type ElemodBuildSpec = { storage: { sym: string; scope: 'sound' | 'kit' | 'global' | 'track' | 'pattern' | 'project'; bits: number }[] // mod storage fields, for a core that keeps them 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 }[] } + // the machine types (7-10, each claimed as machine:) whose voices it plays from which entry label, and the + // filter types (7-126, each claimed as filter:) whose routine it runs per voice. `cost` is the part's worst + // case in sound-chip instructions per block over the stock work it replaces; a part with filters must declare it. + sharc?: { source: string; players: { type: number; entry: string }[]; filters?: { type: number; entry: 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', 'filters', 'cost']) 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', 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,19 @@ export function parseElemodBuild(value: unknown, document: Pick player.type)).size !== players.length) fail('build.sharc.players', 'one player per machine type') - sharc = { source, players } + const filters = list(value.filters ?? [], 'build.sharc.filters', 0, 4).map((entry, index) => { + const at = 'build.sharc.filters[' + index + ']', filter = object(entry, at, ['type', 'entry']) + const type = count(filter.type, at + '.type') + if (type === null || type < 7 || type > 126) fail(at + '.type', 'expected an added filter type, 7 to 126') + if (!claims.includes('filter:' + type)) fail(at + '.type', 'claim the filter type as filter:' + type) + return { type: type!, entry: symbol(filter.entry, at + '.entry') } + }) + if (new Set(filters.map(filter => filter.type)).size !== filters.length) fail('build.sharc.filters', 'one routine per filter type') + if (!players.length && !filters.length) fail('build.sharc', 'expected a machine player or a filter routine') + const cost = value.cost === undefined ? undefined : count(value.cost, 'build.sharc.cost') + if (cost === null) fail('build.sharc.cost', 'expected a positive integer') + if (filters.length && !cost) fail('build.sharc.cost', 'a filter routine declares its worst case in sound-chip instructions a block, more than 0') + sharc = { source, players, ...(filters.length ? { filters } : {}), ...(cost === undefined ? {} : { cost }) } } 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/dt2-render-build.test.ts b/src/engine/elekloader/dt2-render-build.test.ts index 3af3874c9c..15ff44bc63 100644 --- a/src/engine/elekloader/dt2-render-build.test.ts +++ b/src/engine/elekloader/dt2-render-build.test.ts @@ -1,10 +1,10 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' -import { buildDt2RenderSection, unpackDt2SharcSection, type Dt2RenderPlan } from '../elektron/dt2-sharc' +import { buildDt2RenderSection, dt2FilterSiteEncoding, unpackDt2SharcSection, type Dt2RenderPlan } from '../elektron/dt2-sharc' 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_BASE_SHARC, dt2RegisteredFilters, dt2SharcCost, dt2RegisteredMachines, planDt2MachineParts, readDt2SharcPart, 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 } } }) @@ -15,8 +15,23 @@ describe('Digitakt II machine sound-chip parts', () => { module: 'mikrotakt', allocations: [{ address: 0x200d0000, bytes: Uint8Array.of(1, 2, 3, 4, 5, 6, 7, 8), code: true }], players: [{ type: 7, entry: 0xbe8000 }], + filters: [], }) expect(readDt2SharcPart('plain', { build: {} })).toBeNull() + expect(readDt2SharcPart('vowel', part({ players: [], filters: [{ type: 7, entry: 0xbe8000 }] }))!.filters).toEqual([{ type: 7, entry: 0xbe8000 }]) + expect(() => readDt2SharcPart('vowel', part({ filters: [{ type: 7, entry: 0xbe9000 }] }))).toThrow('filter routine for type 7 does not start') + expect(readDt2SharcPart('vowel', part({ cost: 9000 }))!.cost).toBe(9000) + expect(() => readDt2SharcPart('vowel', part({ cost: -1 }))).toThrow('malformed sound-chip cost') + }) + + it('counts machines, filters and effects against one budget', () => { + const p = (module: string, cost?: number, filters = false): Dt2SharcPart => + ({ module, allocations: [], players: [], filters: filters ? [{ type: 7, entry: 0xbe8000 }] : [], ...(cost === undefined ? {} : { cost }) }) + expect(dt2SharcCost([p('vowel', 20000, true), p('notch', 15000, true), p('grains')])).toEqual({ total: 35000, uncounted: ['grains'] }) + expect(() => dt2SharcCost([p('vowel', 40000, true), p('morph', 30000)])).toThrow('past the 60000 they share') + expect(() => dt2SharcCost([p('vowel', undefined, true)])).toThrow('declares no sound-chip cost') + expect(() => dt2SharcCost([p('vowel', 0, true)])).toThrow('declares no sound-chip cost above 0') + expect(dt2SharcCost([p('quiet', 0)])).toEqual({ total: 0, uncounted: [] }) }) it('leaves the sidechain work\'s render-hook format (version 1) to its own path', () => { @@ -76,6 +91,35 @@ describe('the base\'s sound-chip parts for a set', () => { await expect(planDt2MachineParts(sharc, [{ module: 'a', type: 7, standsFor: 7 }], [])).rejects.toThrow('not a stock type') await expect(planDt2MachineParts(sharc, [{ module: 'a', type: 11, standsFor: 0 }], [])).rejects.toThrow('not one of 7-10') }) + + it('refuses a filter type registered twice, a stock or out-of-range number and a bad stand-in', async () => { + await expect(planDt2MachineParts(sharc, [], [], [], [{ module: 'a', type: 7, standsFor: 0 }, { module: 'b', type: 7, standsFor: 1 }])).rejects.toThrow('same filter type') + await expect(planDt2MachineParts(sharc, [], [], [], [{ module: 'a', type: 5, standsFor: 0 }])).rejects.toThrow('not one of 7-126') + await expect(planDt2MachineParts(sharc, [], [], [], [{ module: 'a', type: 127, standsFor: 0 }])).rejects.toThrow('not one of 7-126') + await expect(planDt2MachineParts(sharc, [], [], [], [{ module: 'a', type: 8, standsFor: 6 }])).rejects.toThrow('not a stock filter type') + }) + + it('refuses more filter routines than the four slots', async () => { + const types = [7, 8, 9, 10, 11] + const parts: Dt2SharcPart[] = types.map(type => ({ module: 'f' + type, allocations: [], players: [], filters: [{ type, entry: 0xbe8000 }], cost: 100 })) + await expect(planDt2MachineParts(sharc, [], parts, [], types.map(type => ({ module: 'f' + type, type, standsFor: 0 })))).rejects.toThrow('More than 4 filter routines') + }) + + it('refuses module code over the base\'s filter parts', () => { + for (const address of [DT2_BASE_SHARC.filterTable, DT2_BASE_SHARC.filterSlots, DT2_BASE_SHARC.filterEnd - 4]) { + expect(() => readDt2SharcPart('m', part({ allocations: [{ address, data: code8, code: true }] }))).toThrow('overlaps the base\'s filter parts') + } + expect(readDt2SharcPart('m', part({ allocations: [{ address: DT2_BASE_SHARC.filterEnd, data: code8, code: true }], players: [] }))).not.toBeNull() + }) +}) + +describe('the filter types a module registers', () => { + it('reads each core_filters record\'s type and stand-in', () => { + const mod = machineMod([[7, 0], [11, 2]]) + mod.contribute.forEach(entry => { entry.to = 'core_filters' }) + expect(dt2RegisteredFilters('two', mod)).toEqual([{ module: 'two', type: 7, standsFor: 0 }, { module: 'two', type: 11, standsFor: 2 }]) + expect(dt2RegisteredMachines('two', mod)).toEqual([]) + }) }) // With the owner's OS 1.17 file (never in the repository): MODWERK_DT2_STOCK=. @@ -123,6 +167,57 @@ 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('gives a registered filter type its stand-in\'s field and every other added number none, through one site', async () => { + const stock = sharc() + const plan = (await planDt2MachineParts(stock, [], [], [], [{ module: 'vowel', type: 7, standsFor: 1 }, { module: 'notch', type: 11, standsFor: 2 }]))! + const table = block(plan, DT2_BASE_SHARC.filterTable) + // Indices -128 to 255, so a stored 0xff or a negative word never reads outside the table. + expect(table.length).toBe(4 * 384) + expect(DT2_BASE_SHARC.filterTable + table.length).toBeLessThanOrEqual(DT2_BASE_SHARC.filterSlots) + const word = (k: number) => new DataView(table.buffer, table.byteOffset + 4 * (128 + k), 4).getUint32(0, true) + // Stock: Multi-Mode 1, Lowpass 4 3, Equalizer 2, Comb- 4, Legacy 5, Comb+ 6. + expect([0, 1, 2, 3, 4, 5].map(word)).toEqual([1, 3, 2, 4, 5, 6]) + expect(word(7)).toBe(3) + expect(word(11)).toBe(2) + for (const k of [-128, -1, 6, 8, 9, 10, 12, 126, 127, 128, 255]) expect(word(k)).toBe(0) + expect(plan.sites).toHaveLength(1) + // No machine: the machine parts stay out, so only the filter table and its site change. + expect(plan.allocations).toHaveLength(1) + await buildDt2RenderSection(stock, plan) + const other = (await planDt2MachineParts(stock, [], [], [], [{ module: 'vowel', type: 9, standsFor: 0 }]))! + expect(other.sites).toEqual(plan.sites) + }) + + it('replaces the filter site\'s relative jump with an absolute one under the same condition', () => { + // Stock 0x1c6c13 is `IF GE JUMP (PC, 0x2a4)` (type 8b: 0x07 in the top byte). The base's code is too far for a + // relative jump, so the site becomes the absolute form (type 8a: 0x06) with the same condition bits. + const stockSite = Uint8Array.of(0x22, 0x07, 0x00, 0x00, 0xa4, 0x02) // as the guard covers it + const ours = dt2FilterSiteEncoding(0xbe2180) + expect(ours[1]).toBe(0x06) + expect(ours[0]).toBe(stockSite[0]) // condition GE and the low bits of the top parcel + expect([ours[2], ours[3], ours[4], ours[5]]).toEqual([0xbe, 0x00, 0x80, 0x21]) + expect(sharc().length).toBeGreaterThan(0) + }) + + it('sends a routed filter type to its slot and calls the module\'s routine there', async () => { + const stock = sharc() + const vowel: Dt2SharcPart = { module: 'vowel', allocations: [{ address: 0x200d0000, bytes: new Uint8Array(8), code: true }], players: [], filters: [{ type: 9, entry: 0xbe8000 }], cost: 1000 } + const plan = (await planDt2MachineParts(stock, [], [vowel], [], [{ module: 'vowel', type: 9, standsFor: 0 }, { module: 'notch', type: 11, standsFor: 2 }]))! + const table = block(plan, DT2_BASE_SHARC.filterTable) + const word = (k: number) => new DataView(table.buffer, table.byteOffset + 4 * (128 + k), 4).getUint32(0, true) + expect(word(9)).toBe(7) // slot 0 + expect(word(11)).toBe(2) // no routine: its stand-in, Equalizer + expect(slot(plan, DT2_BASE_SHARC.filterSlots, 0)).toEqual(jump(0xbe8000)) + expect(plan.sites).toHaveLength(2) + // A filter-only set: the filter parts and the module's code, none of the machine parts. + expect(plan.allocations.map(item => item.address).sort()).toEqual( + [DT2_BASE_SHARC.filterTable, DT2_BASE_SHARC.filterSlots, DT2_BASE_SHARC.filterDispatcher, 0x200d0000].sort()) + const dispatcher = block(plan, DT2_BASE_SHARC.filterDispatcher) + expect(DT2_BASE_SHARC.filterDispatcher + dispatcher.length).toBeLessThanOrEqual(DT2_BASE_SHARC.filterEnd) + await buildDt2RenderSection(stock, plan) + await expect(planDt2MachineParts(stock, [], [vowel], [], [{ module: 'other', type: 9, standsFor: 0 }])).rejects.toThrow('does not register in core_filters') + }) + 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..29bdd15d06 100644 --- a/src/engine/elekloader/dt2-render-build.ts +++ b/src/engine/elekloader/dt2-render-build.ts @@ -2,9 +2,9 @@ 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, - type Dt2MachinePlayer, type Dt2RenderPlan, + buildDt2RenderSection, combineDt2Plans, DT2_ADDED_TYPES, DT2_FILTER_END, DT2_FIRST_ADDED_FILTER, DT2_FIRST_ADDED_TYPE, DT2_MACHINE_KNOBS_AT, + DT2_FILTER_SLOTS, DT2_MACHINE_TYPES_AT, planDt2FilterDispatch, planDt2FilterTable, planDt2FrameReceive, planDt2MachinePlayers, + planDt2MachineSelectors, unpackDt2SharcSection, type Dt2FilterRoutine, type Dt2MachinePlayer, type Dt2RenderPlan, } from '../elektron/dt2-sharc.ts' import { ELE3_DEVICES } from '../elektron/ele3.ts' import { parseElemod, type ParsedMod } from '../elektron/elemod.ts' @@ -50,6 +50,36 @@ export type Dt2SharcPart = { module: string allocations: { address: number; bytes: Uint8Array; code: boolean }[] players: Dt2MachinePlayer[] + /** Filter routines (`filters`: {type, entry}), each for a filter type the module registers in core_filters. */ + filters?: Dt2FilterRoutine[] + /** `cost`: the part's worst case in sound-chip instructions per 32-sample block over the stock work it replaces, at + * the voices it can really hold: a machine over a playing stock SAMPLE voice (about 3,600 a block), a filter over its + * stand-in's stock filter case, an effect all of its own. Required for a part with filter routines. */ + cost?: number +} + +/** One figure for everything modules add to the sound chip in a block: machine players, filter routines and effects + * count against it together (owner, 25 November 2026: the effect slot's cap; set again after a unit cycle count). */ +export const DT2_SHARC_BUDGET = 60_000 + +/** The set's declared sound-chip cost, refused past DT2_SHARC_BUDGET. A part with filter routines must declare its + * cost; a machine part released before the budget existed and declaring none is listed as uncounted. */ +export function dt2SharcCost(parts: readonly Dt2SharcPart[]): { total: number; uncounted: string[] } { + let total = 0 + const uncounted: string[] = [] + for (const part of parts) { + if (!part.cost) { + if (part.filters?.length) throw new Error(part.module + ': its filter routine declares no sound-chip cost above 0 (build.dt2_sharc cost)') + if (part.cost === 0) continue + uncounted.push(part.module) + continue + } + total += part.cost + } + if (total > DT2_SHARC_BUDGET) { + throw new Error('The chosen modules need ' + total + ' sound-chip instructions a block, past the ' + DT2_SHARC_BUDGET + ' they share') + } + return { total, uncounted } } /** A machine a module registers in the base's core_machines table: its type (7-10) and the stock type it stands for. */ @@ -67,6 +97,9 @@ export const DT2_BASE_SHARC = { stepSamples: 0x200c2c20, viewTrack: 0x200c2c64, view: 0x200c2c68, trackTypes: 0x200c2c00 + 4 * DT2_MACHINE_TYPES_AT, trackKnobs: 0x200c2c00 + 4 * DT2_MACHINE_KNOBS_AT, end: 0x200c3000, + // The effect slot's range (0x200c3000-0x200c4000, proposal #2146) lies between; then the filter types' parts. + // The table answers indices -128 to 255 (0x600 bytes), so the slots and dispatcher follow it. + filterTable: 0x200c4000, filterSlots: 0x200c4600, filterDispatcher: 0x200c4640, filterEnd: 0x200c4800, } const base64 = (text: string) => Uint8Array.from(atob(text), c => c.charCodeAt(0)) @@ -89,18 +122,28 @@ export function readDt2SharcPart(name: string, document: unknown): Dt2SharcPart 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') } + if ((address as number) < DT2_BASE_SHARC.filterEnd && (address as number) + bytes.length > DT2_BASE_SHARC.filterTable) { + throw new Error(name + ': its sound-chip code overlaps the base\'s filter parts') + } return { address: address as number, bytes, code } }) - const players = part.players.map(entry => { + const entries = (list: unknown[], what: string) => list.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') + if (!Number.isInteger(type) || !Number.isInteger(pc)) throw new Error(name + ': malformed ' + what) 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') + throw new Error(name + ': the ' + what + ' 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 } + const filters = (part as { filters?: unknown }).filters + if (filters !== undefined && !Array.isArray(filters)) throw new Error(name + ': malformed filter routine') + const cost = (part as { cost?: unknown }).cost + if (cost !== undefined && (!Number.isInteger(cost) || (cost as number) < 0)) throw new Error(name + ': malformed sound-chip cost') + return { + module: name, allocations, players: entries(part.players, 'machine player'), filters: entries(filters ?? [], 'filter routine'), + ...(cost === undefined ? {} : { cost: cost as number }), + } } /** The bytes of `section` in a mod, from its own hex parts (a record never copies stock bytes). */ @@ -116,7 +159,16 @@ function sectionBytes(mod: ParsedMod, section: string): Uint8Array | null { /** The machines a module registers: each core_machines entry is a pointer to its struct dt2_machine record * (mk2/machines.h), whose first two big-endian words are the type and the stock type it stands for. */ export function dt2RegisteredMachines(name: string, mod: ParsedMod): Dt2Machine[] { - return mod.contribute.filter(entry => entry.to === 'core_machines').map(entry => { + return dt2RegisteredRecords(name, mod, 'core_machines') +} + +/** The filter types a module registers in core_filters (struct dt2_filter, mk2/filters.h): the same two leading words. */ +export function dt2RegisteredFilters(name: string, mod: ParsedMod): Dt2Machine[] { + return dt2RegisteredRecords(name, mod, 'core_filters') +} + +function dt2RegisteredRecords(name: string, mod: ParsedMod, table: 'core_machines' | 'core_filters'): Dt2Machine[] { + return mod.contribute.filter(entry => entry.to === table).map(entry => { const reloc = entry.relocs.find(item => item.offset === 0 && item.type === 'abs32') let section: string | undefined, offset = reloc?.addend ?? 0 if (reloc?.target.startsWith('sym:')) { @@ -124,7 +176,7 @@ export function dt2RegisteredMachines(name: string, mod: ParsedMod): Dt2Machine[ if (symbol && symbol[0] !== 'abs') { section = symbol[0]; offset += symbol[1] } } else if (reloc?.target.startsWith('sec:')) section = reloc.target.slice(4) const bytes = section ? sectionBytes(mod, section) : null - if (!bytes || offset < 0 || offset + 8 > bytes.length) throw new Error(name + ': a core_machines entry whose record cannot be read') + if (!bytes || offset < 0 || offset + 8 > bytes.length) throw new Error(name + ': a ' + table + ' entry whose record cannot be read') const view = new DataView(bytes.buffer, bytes.byteOffset + offset, 8) return { module: name, type: view.getUint32(0), standsFor: view.getUint32(4) } }) @@ -135,8 +187,36 @@ export function dt2RegisteredMachines(name: string, mod: ParsedMod): Dt2Machine[ * receiver (the sound chip then stays stock). Types 7-10 get the selector of the stock type each stands for. */ export async function planDt2MachineParts( sharc: Uint8Array, machines: readonly Dt2Machine[], parts: readonly Dt2SharcPart[], frameReceivers: readonly number[] = [], + filters: readonly Dt2Machine[] = [], ): Promise { - if (!machines.length && !parts.length && !frameReceivers.length) return null + dt2SharcCost(parts) + const filterTypes = filters.map(filter => filter.type) + if (new Set(filterTypes).size !== filterTypes.length) throw new Error('Two modules register the same filter type') + for (const filter of filters) { + if (!Number.isInteger(filter.type) || filter.type < DT2_FIRST_ADDED_FILTER || filter.type >= DT2_FILTER_END) { + throw new Error(filter.module + ': filter type ' + filter.type + ' is not one of 7-126') + } + if (!Number.isInteger(filter.standsFor) || filter.standsFor < 0 || filter.standsFor > 5) { + throw new Error(filter.module + ': filter type ' + filter.type + ' stands for ' + filter.standsFor + ', not a stock filter type') + } + } + const routines = parts.flatMap(part => (part.filters ?? []).map(routine => { + if (!filters.some(filter => filter.module === part.module && filter.type === routine.type)) { + throw new Error(part.module + ': a filter routine for type ' + routine.type + ', which it does not register in core_filters') + } + return routine + })).sort((a, b) => a.type - b.type) + if (routines.length > DT2_FILTER_SLOTS) throw new Error('More than ' + DT2_FILTER_SLOTS + ' filter routines in one set') + const stockFields = [1, 3, 2, 4, 5, 6] // the stock filter table's words (checked by hash in planDt2FilterTable) + const filterPlan = filters.length ? combineDt2Plans( + await planDt2FilterTable(sharc, DT2_BASE_SHARC.filterTable, filters, routines.map(r => r.type)), + routines.length ? await planDt2FilterDispatch(sharc, DT2_BASE_SHARC.filterDispatcher, DT2_BASE_SHARC.filterSlots, routines, + routines.map(r => stockFields[filters.find(f => f.type === r.type)!.standsFor])) : null, + ) : null + const machineParts = parts.filter(part => part.players.length || (part.allocations.length && !part.filters?.length)) + if (!machines.length && !machineParts.length && !frameReceivers.length) { + return combineDt2Plans(filterPlan, ...parts.map(part => ({ allocations: part.allocations.map(({ address, bytes }) => ({ address, bytes })) }))) + } 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') @@ -159,14 +239,16 @@ export async function planDt2MachineParts( 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 })) }))) + return combineDt2Plans(selectors, dispatcher, receive, filterPlan, ...parts.map(part => ({ allocations: part.allocations.map(({ address, bytes }) => ({ address, bytes })) }))) } /** The selected packages' machines 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 parsed = documents.map(({ name, document }) => ({ name, mod: parseElemod(document as Record, name) })) + const machines = parsed.flatMap(({ name, mod }) => dt2RegisteredMachines(name, mod)) + const filters = parsed.flatMap(({ name, mod }) => dt2RegisteredFilters(name, mod)) const parts = documents.map(({ name, document }) => readDt2SharcPart(name, document)).filter((part): part is Dt2SharcPart => part !== null) - return { machines, parts } + return { machines, parts, filters } } /** A finished kit build with the base's sound-chip parts and the selected modules', checked by the preflight with that @@ -175,9 +257,9 @@ export function readDt2MachineSet(documents: readonly { name: string; document: * 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, parts, filters } = readDt2MachineSet(documents) + if (!machines.length && !parts.length && !filters.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, [], filters) 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..1ef4848ef4 100644 --- a/src/engine/elektron/dt2-sharc.ts +++ b/src/engine/elektron/dt2-sharc.ts @@ -222,6 +222,144 @@ export async function planDt2MachineSelectors(stock: Uint8Array, tableAddress: n return { sites: [{ address: SELECTOR_SITE, guard: SELECTOR_GUARD, instruction: instruction(0x0f00 | I3, tableAddress / 4) }], allocations } } +// Added filter types: 7 and up, each a fixed number a module claims (kits save it); 127 is past the last. +export const DT2_FIRST_ADDED_FILTER = 7, DT2_FILTER_END = 127 +const STOCK_FILTERS = 6 + +// The filter-type lookup (in the track setup, short-word PC 0x1c26df) loads the base of the OS's six-word table that +// maps a track's filter type (0-5) to the per-voice filter field the voice loop dispatches on (0x1c6c10; 0: none, 1-6 +// a stock filter routine). The index is the track's word at 0x255990 (`M0 = DM(I1, M4)` at 0x1c26c5), used as it is: +// nothing bounds it, so a higher type reads past the table and a negative one before it. The base points the lookup +// at a table in its own L2 that answers every index from -128 to 255, whatever the ColdFire sends for a stored byte +// (the kit load keeps 0xff as stock does): the six stock words, read from the owner's verified stock section when a +// build is composed, then for each registered added type the field of the stock type it stands for, and 0 (no filter) +// for every other index, so no stray number reaches the filter dispatcher. Only the stock table's address, length +// and SHA-256 are kept here. +const FILTER_TABLE_SITE = 0x28000000 + 2 * 0x1c26df +const FILTER_TABLE_SITE_GUARD = '3a695e102cc6d47f610f4884407ddf01bff13903ab77f02a5d9635cc127ef12d' +const FILTER_TABLE = 0x28000000 + 0x2567a0 // the stock table's loader byte address (normal word 0x2567a0) +const FILTER_TABLE_GUARD = '9380757de997ed5969421c960384a2d271ea79101e90ae53823c6ddf99243ce7' // its 24 bytes +const I4 = 0x14 +/** The words below index 0 and from index 0 that the base's filter table answers: indices -128 to 255. */ +const FILTER_TABLE_BELOW = 128, FILTER_TABLE_ABOVE = 256 +export const DT2_FILTER_TABLE_BYTES = 4 * (FILTER_TABLE_BELOW + FILTER_TABLE_ABOVE) + +/** An added filter type and the stock type (0-5) it stands for. */ +export type Dt2FilterType = { type: number; standsFor: number } + +/** A plan fragment giving each registered added filter type its stand-in's per-voice filter field, placed at + * `tableAddress` in free L2, with the lookup pointed at it. A type in `routed` (at most DT2_FILTER_SLOTS, in slot + * order) gets field 7 + its slot instead, which the voice loop sends to the base's filter dispatcher. */ +export async function planDt2FilterTable(stock: Uint8Array, tableAddress: number, filters: readonly Dt2FilterType[], routed: readonly number[] = []): Promise { + if (await sha256Hex(stock) !== STOCK_SECTION) throw new Error('Unsupported Digitakt II SHARC image') + if (new Set(filters.map(f => f.type)).size !== filters.length || filters.some(f => + !Number.isInteger(f.type) || f.type < DT2_FIRST_ADDED_FILTER || f.type >= DT2_FILTER_END || + !Number.isInteger(f.standsFor) || f.standsFor < 0 || f.standsFor >= STOCK_FILTERS)) { + throw new Error('Invalid filter type') + } + if (await sha256Hex(readStored(stock, FILTER_TABLE_SITE, 6)) !== FILTER_TABLE_SITE_GUARD) throw new Error('SHARC filter table site guard mismatch') + const stored = readStored(stock, FILTER_TABLE, 4 * STOCK_FILTERS) + if (await sha256Hex(stored) !== FILTER_TABLE_GUARD) throw new Error('SHARC filter table guard mismatch') + const table = new Uint8Array(DT2_FILTER_TABLE_BYTES) + const zero = 4 * FILTER_TABLE_BELOW // index 0's byte offset; every word not set below stays 0 (no filter) + table.set(stored, zero) + for (const { type, standsFor } of filters) table.set(stored.subarray(4 * standsFor, 4 * standsFor + 4), zero + 4 * type) + if (routed.length > DT2_FILTER_SLOTS || routed.some(type => !filters.some(f => f.type === type))) throw new Error('Invalid filter routine') + routed.forEach((type, k) => new DataView(table.buffer).setUint32(zero + 4 * type, FILTER_FIELD_SLOTS + k, true)) + const allocations = [{ address: tableAddress, bytes: table }] + checkAllocations(allocations) + // Type 17a, I4 = index 0's normal-word address (L2 byte address / 4). + return { sites: [{ address: FILTER_TABLE_SITE, guard: FILTER_TABLE_SITE_GUARD, instruction: instruction(0x0f00 | I4, (tableAddress + zero) / 4) }], allocations } +} + +// A module filter's own routine. The voice loop's pass 3 (0x1c6c0b-0x1c6ec6) reads each voice's filter field; below 7 +// it jumps through the stock case table (0: no filter; 1-6 a stock routine, called as a compiled function with R4 at +// that filter's per-voice state, R8 and R12 at the voice's 32 samples, R15 as a stack argument, then the case's tail +// pops it and goes on at 0x1c6eb7), and 7 or more jumps straight to 0x1c6eb7 (the site below). The base turns that one +// branch into a jump to its filter dispatcher, so stock fields never reach base code. Fields 7 to 10 are the four +// slots; the dispatcher calls the slot's routine exactly as the stock case of its stand-in calls the stock routine +// (with that stand-in's per-voice state in R4), then returns through the tail every stock case uses. +export const DT2_FILTER_SLOTS = 4 +const FILTER_FIELD_SLOTS = 7 +const FILTER_SITE = 0x28000000 + 2 * 0x1c6c13 +const FILTER_SITE_GUARD = '2321e702bdf2ccdca5e0ca716efa1417ceda63e6e956bb2f2ef6eee3866e39af' +const FILTER_NEXT_VOICE = 0x1c6eb7 // the loop's tail, where every stock case ends and a field of 7 or more goes +const FILTER_CASE_TAIL = 0x1c6eb4 // I7 = modify(I7, 2): pops the stack argument, then 0x1c6eb7 +const VOICE_BUFFER = 0x8045c3c0 // I0 as the stock code sets it before the case jump +/** Each stock field's per-voice state in R4, as its case computes it (field 1, Multi-Mode, before the case jump). */ +const FILTER_STATE: Record = { + 1: 'R1 = I6\n R0 = 5\n R1 = R1 - R0\n I4 = R1\n R1 = DM(M5, I4)\n R2 = I15\n R4 = R1 + R2', + 2: 'R1 = I6\n R0 = 4\n R1 = R1 - R0\n I4 = R1\n R1 = DM(M5, I4)\n R2 = I14\n R4 = R1 + R2', + 3: 'R1 = I6\n R0 = 3\n R1 = R1 - R0\n I4 = R1\n R1 = DM(M5, I4)\n R2 = I11\n R4 = R1 + R2', + 4: 'R4 = I10', + 5: 'R1 = I6\n R0 = 6\n R1 = R1 - R0\n I4 = R1\n R1 = DM(M5, I4)\n R2 = I8\n R4 = R1 + R2', + 6: 'R4 = I10', +} + +/** A module filter's own routine: its added type and the program counter (short word) of its entry in L2. */ +export type Dt2FilterRoutine = { type: number; entry: number } + +function filterDispatcherSource(codeAddress: number, slotsAddress: number, fields: readonly number[]): string { + const slot = (k: number) => programCounter(slotsAddress) + k * SLOT_BYTES / 2 + const stub = (k: number) => `stub${k}: + R12 = I3 + R8 = R12 + I0 = ${VOICE_BUFFER} + ${FILTER_STATE[fields[k]]} + DM(I7, M7) = R15 // the stack argument the stock case passes, and the word above it (free stack) + DM(I7, M7) = R15 + CCALL ${slot(k)} + JUMP ${FILTER_CASE_TAIL}` + return ` +.code ${codeAddress} +dispatch: // R2: the voice's filter field, 7 or more + R1 = ${FILTER_FIELD_SLOTS + DT2_FILTER_SLOTS} + COMP(R2, R1) + IF GE JUMP ${FILTER_NEXT_VOICE} + R1 = ${FILTER_FIELD_SLOTS + 1} + COMP(R2, R1) + IF LT JUMP stub0 + IF EQ JUMP stub1 + R1 = ${FILTER_FIELD_SLOTS + 2} + COMP(R2, R1) + IF EQ JUMP stub2 + JUMP stub3 +${Array.from({ length: DT2_FILTER_SLOTS }, (_, k) => stub(k)).join('\n')} +empty: // an empty slot: no filter for that voice + CRET +` +} + +/** A plan fragment for module filter routines: the base's dispatcher at `codeAddress` (the same code for every set + * except which stock state each slot passes), the four slots at `slotsAddress` and the site. `routines` are in slot + * order with the field of the stock type each stands for (`fields`, 1-6, from the stock table). */ +export async function planDt2FilterDispatch( + stock: Uint8Array, codeAddress: number, slotsAddress: number, routines: readonly Dt2FilterRoutine[], fields: readonly number[], +): Promise { + if (await sha256Hex(stock) !== STOCK_SECTION) throw new Error('Unsupported Digitakt II SHARC image') + if (routines.length > DT2_FILTER_SLOTS || routines.length !== fields.length || + routines.some(r => !Number.isInteger(r.entry) || r.entry < L2_PROGRAM[0] || r.entry >= L2_PROGRAM[1]) || + fields.some(f => !(f in FILTER_STATE))) { + throw new Error('Invalid filter routine') + } + if (await sha256Hex(readStored(stock, FILTER_SITE, 6)) !== FILTER_SITE_GUARD) throw new Error('SHARC filter site guard mismatch') + const padded = Array.from({ length: DT2_FILTER_SLOTS }, (_, k) => fields[k] ?? 1) + const { blocks: code, symbols } = assembleSharc(filterDispatcherSource(codeAddress, slotsAddress, padded)) + if (code.length !== 1) throw new Error('Unexpected SHARC filter dispatcher layout') + const slots = new Uint8Array(SLOT_BYTES * DT2_FILTER_SLOTS) + for (let k = 0; k < DT2_FILTER_SLOTS; k++) slots.set(slotJump(routines[k]?.entry ?? symbols.get('empty')!), SLOT_BYTES * k) + const allocations = [{ address: codeAddress, bytes: code[0].bytes }, { address: slotsAddress, bytes: slots }] + checkAllocations(allocations) + // The site keeps its condition (GE, after the unsigned compare with 7) and gets the dispatcher as its target. + const site = assembleSharc(`.code ${0x20000000}\n IF GE JUMP ${symbols.get('dispatch')}`).blocks[0].bytes.subarray(0, 6) + return { sites: [{ address: FILTER_SITE, guard: FILTER_SITE_GUARD, instruction: Uint8Array.from(site) }], allocations } +} + +/** The site's stock instruction as this assembler encodes it, for a test that the encoding matches the stock bytes. */ +export function dt2FilterSiteEncoding(target: number): Uint8Array { + return Uint8Array.from(assembleSharc(`.code ${0x20000000}\n IF GE JUMP ${target}`).blocks[0].bytes.subarray(0, 6)) +} + // A registry slot is one 48-bit instruction at a fixed L2 address the base owns: the whole-image builder writes it // today, and a runtime loader can write or clear it later, without changing the base's code around it. const SLOT_BYTES = 6