From 1d435dd80c6d417de44a32f15fd8718a17b3407c Mon Sep 17 00:00:00 2001 From: Jacob Phono Thiessen Date: Sun, 22 Nov 2026 01:27:17 +0100 Subject: [PATCH 1/4] Freeze draft: grid-locked tape-like live loop engine with host tests Original fixed-point engine (freeze.c) for an FX2 loop that repeats every 1-8 of the track's own steps at 0.25x-1.0x tape speed, with JTR wander, POSITION scrub, GRAB/release fades and exact dry passthrough. Host gate: 53 checks under ASan/UBSan plus a ColdFire 54454 build with no runtime calls. Not runnable yet: needs the shared delay-ring hook proposed in DELAY_HOOK_PROPOSAL.md (owner decision). Tape Echo and Ghost Cut untouched. Co-Authored-By: Claude Opus 5.5 --- sdk/drafts/freeze/DELAY_HOOK_PROPOSAL.md | 86 +++ sdk/drafts/freeze/LICENSE | 30 + sdk/drafts/freeze/README.md | 74 +++ sdk/drafts/freeze/TESTING.md | 63 +++ sdk/drafts/freeze/freeze.c | 375 +++++++++++++ sdk/drafts/freeze/freeze.h | 92 ++++ sdk/drafts/freeze/manifest.py | 80 +++ sdk/drafts/freeze/octamod.module.json | 157 ++++++ sdk/drafts/freeze/qualification.example.json | 84 +++ .../freeze/resource-impact.example.json | 21 + sdk/drafts/freeze/test_freeze.c | 514 ++++++++++++++++++ sdk/drafts/freeze/test_freeze.py | 17 + sdk/drafts/freeze/unit.s | 17 + sdk/drafts/freeze/verify.py | 52 ++ 14 files changed, 1662 insertions(+) create mode 100644 sdk/drafts/freeze/DELAY_HOOK_PROPOSAL.md create mode 100644 sdk/drafts/freeze/LICENSE create mode 100644 sdk/drafts/freeze/README.md create mode 100644 sdk/drafts/freeze/TESTING.md create mode 100644 sdk/drafts/freeze/freeze.c create mode 100644 sdk/drafts/freeze/freeze.h create mode 100644 sdk/drafts/freeze/manifest.py create mode 100644 sdk/drafts/freeze/octamod.module.json create mode 100644 sdk/drafts/freeze/qualification.example.json create mode 100644 sdk/drafts/freeze/resource-impact.example.json create mode 100644 sdk/drafts/freeze/test_freeze.c create mode 100644 sdk/drafts/freeze/test_freeze.py create mode 100644 sdk/drafts/freeze/unit.s create mode 100644 sdk/drafts/freeze/verify.py diff --git a/sdk/drafts/freeze/DELAY_HOOK_PROPOSAL.md b/sdk/drafts/freeze/DELAY_HOOK_PROPOSAL.md new file mode 100644 index 0000000000..577f8a9ee5 --- /dev/null +++ b/sdk/drafts/freeze/DELAY_HOOK_PROPOSAL.md @@ -0,0 +1,86 @@ +# Proposal: a shared hook for the stock per-track delay ring + +Status: **proposal, needs the owner's decision.** Nothing here is in a base yet, and Freeze cannot run on a unit +until a base carries it. Written 22 November 2026 for Freeze; it changes nothing in Tape Echo. + +## Why + +The stock delay routine (0x400031a0, once a frame) owns a four-second ring per track (176,400 stereo frames at +`0x4f502c10 + track * 1411328`, uncached alias). It is the only memory on the unit that holds seconds of a track's +audio without borrowing sample memory, and it is free on any track whose FX2 is not DELAY. A tempo-locked loop of +3, 5 or 7 steps needs it: Ghost Cut's FX2 DSP ring holds about 353 ms, under one step at 120 BPM. + +Tape Echo (author and owner: repeat98) already takes the routine's seam for its own FX2 id with two detours: + +| Site | Length | What Tape Echo does there | +| --- | --- | --- | +| `0x40002f44` | 8 | resets its state with the stock ring reset (`te_cpu_reset`) | +| `0x4000361a` | 10 | per track, after the DMA read wait and next-track prefetch: runs its own filter/mix for its id, otherwise replays stock (`te_cpu_hook`) | + +The base itself already patches three other places in the same routine (`status.s`: `mw_delay_read0` 0x4000332a, +`mw_delay_read` 0x400035ba, `mw_delay_idle` 0x4000362a). A second module taking 0x4000361a is refused by the +one-owner-per-byte rule, and rightly. Since each track's FX2 runs one effect at a time, the ring is naturally shared +**per track by FX2 id**: exactly a take/call hook's job. + +## The hooks + +Add at the end of `sdk/machines/octatrack/events.json` on `base/octatrack-next` (index 62 and 63 on the draft as of +22 November 2026, whose last is 61 `ev_audio_frame_prepare`; `pr:ready` claims them on the board): + +**62 `ev_delay_track`**, call hook, site `0x4000361a`, length 10 (Tape Echo's guard: +`44c264b0c51850739e6cc12dc26e78557067c3998a3fae1ba32b6bc0f337e49e`). Runs per track at the seam. The base builds +one record from the stock frame and calls handlers in `order`; the first that returns nonzero takes the track. + +```c +struct modwerk_delay_track { + uint32_t abi; /* 1 */ + uint32_t track; /* 0..7 */ + uint32_t fx2_id; /* the effect id this track's FX2 runs (setup byte 7) */ + const uint8_t *page1; /* the staged FX2 page-1 halfwords; a knob is the high byte (k[0], k[2] .. k[10]) */ + const uint8_t *page2; /* the track's FX2 page-2 bytes for this frame (to be located: see below) */ + const volatile int32_t *ring; /* the track's ring, uncached */ + uint32_t write; /* ring frame this block's record is written to; <= 176400 - 16 */ + int32_t *audio; /* 16 interleaved stereo frames, in and out */ + int32_t *record; /* 16 interleaved stereo frames the routine then writes to the ring */ + uint32_t tempo24; /* 0x8000181c, BPM x 24 */ + uint8_t running; /* the track's run flag, 0x80006500 + track */ + uint8_t tick; /* the track's sequencer tick, 0x800064f0 + track */ + uint8_t scale; /* the track's scale index 0..6 (Euclid's pattern/track lookup) */ + uint8_t reserved; +}; +int f(struct modwerk_delay_track *t); /* nonzero: this handler took the track */ +``` + +When a handler takes the track the base does what Tape Echo's adapter does today and nothing a module must know: +it toggles the stock scratch buffers (`0x800000e8 ^= 0x40003626`), clears the four EMAC accumulators before the +call, advances the stock filter's state iterator (`0x80006180 += 68`), and rejoins `0x4000377a` for the stock DMA +write of `record`. Otherwise it replays the displaced instructions and returns to 0x40003624. A taken call also +restarts `status.s`'s quiet count, as a seam call before it does now. Order bands: 40-69, one effect id each; +a handler returns nonzero **only** for its own id. Context: the frame interrupt; short, no blocking call, EMAC +state as found, C convention. + +**63 `ev_delay_reset`**, call hook, site `0x40002f44`, length 8 (guard +`4c0570fc6ef0682508e64de2367e111c27f895b6b78e58c300b3f2e7b8010118`), `void f(void)`, notify: every handler runs +when stock resets the rings. Freeze does not need it (its state resets on effect entry), Tape Echo does. + +## Who moves + +- **Tape Echo** keeps its two detours until its author moves it onto the hooks: a `pending-migration` entry in + `sdk/machines/octatrack/compatibility.json` names Tape Echo, the two sites and the hooks, with `until`. Its + `te_cpu_frame` already has the shape of a handler (it reads exactly these values from the stack). Nobody but its + author changes it. +- **Freeze** subscribes to 62 at order 50 and takes only its own id. Its handler is a dozen lines: decode the knobs + into `FzParams`, the grid into `FzGrid` (`freeze_step_q4(tempo24, scale)`), call `freeze_process`. + +## Open before it can ship + +1. The owner decides the hooks (and their ABI) and adds them to the cumulative base draft. +2. Where the FX2 **page-2** bytes are at the seam. Euclid reads them from the frame record + (`0x80000110 + (0x800000e0 & 1) * 512`, track * 64, bytes 48-53 for FX2) in the frame hook; whether that record + is current at the delay seam has to be checked in `ot_emu`. Until then Freeze's FADE and SEAM would be fixed. +3. Whether the tick byte also moves on swung steps as the trig plays (Deja Vu measured it lands within 0.01 step + of the trigs without swing). The host tests model swing as a delayed tick; `ot_emu` must confirm it. +4. The effect id: the USB base assigns module effect ids at install, so `fx2_id` is compared against the id the + loader gives Freeze, not a pinned one. +5. CPU: Freeze reads up to two heads (about 34 uncached words each a block) plus 32 words to write the ring back + while holding. Not measured; see TESTING.md. diff --git a/sdk/drafts/freeze/LICENSE b/sdk/drafts/freeze/LICENSE new file mode 100644 index 0000000000..2ab3bd96b9 --- /dev/null +++ b/sdk/drafts/freeze/LICENSE @@ -0,0 +1,30 @@ +MIT License + +Copyright (c) 2026 jacobphono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +This licence covers this module's own source code and documentation only. It +does not extend to any Elektron Music Machines firmware, which is not +distributed here and remains the property of its copyright holder. Nothing in +this module is endorsed by, supported by, or affiliated with Elektron. +Octatrack and Elektron are trademarks of Elektron Music Machines MAV AB, used +only to identify the hardware this module targets. diff --git a/sdk/drafts/freeze/README.md b/sdk/drafts/freeze/README.md new file mode 100644 index 0000000000..0ab32136e2 --- /dev/null +++ b/sdk/drafts/freeze/README.md @@ -0,0 +1,74 @@ +# Freeze + +Version 0.1.0 · by @jacobphono · **a draft: not runnable on a unit yet.** The engine and its host tests exist; +the base hook it needs does not ([DELAY_HOOK_PROPOSAL.md](DELAY_HOOK_PROPOSAL.md)). Nothing here has run on an +Octatrack or in `ot_emu`. + +## Overview + +Freeze is an FX2 effect that holds the last few seconds of a track and plays them back as a slow, low, tape-like +loop that repeats every 1 to 8 of the track's own steps. Odd lengths (3, 5, 7) drift against a 16-step pattern +and come back into line every 48, 80 or 112 steps; two tracks with different lengths run on their own. While it is +not holding, the track passes through bit for bit. + +## Controls + +| Page | Control | Range, default | What it does | +| --- | --- | --- | --- | +| 1 | STEP | 1-8, 5 | Loop length in track steps. A change lands when the current loop ends. | +| 1 | SPIN | 0.25x-1.0x, 0.5x (64) | Tape speed of the held audio: slower is lower. FUNC+turn stops at 0.25x, 0.5x and 1.0x. A move glides like a motor. | +| 1 | JTR | 0-127, 0 | Slow, bounded tape wander (about 1.2 % of the speed at 127, so the same pitch drift at every SPIN) and a small drift of where each loop starts. The loop length never changes. | +| 1 | POS | 0-127, 0 | Where in the held audio the loop reads: 0 the newest, 127 the oldest. A move scrubs there at up to 1/8 of the tape speed. | +| 1 | GRAB | OFF/HOLD, OFF | HOLD captures at the track's next step; OFF lets go at the next step. Lockable per step. | +| 1 | MIX | 0-127, 127 | How much of the loop replaces the track while holding: 127 loop only. | +| 2 | FADE | 0-127, 20 | Grab and release crossfade, 6 ms to 1.1 s. | +| 2 | SEAM | 0-127, 64 | Length of the crossfade where the loop returns to its start, 1/256 to 1/2 of the loop. | + +## How it works + +- While not holding, Freeze writes the track's dry signal into the track's stock four-second delay ring (the ring + stock DELAY uses; it is idle on a track whose FX2 is not DELAY) and leaves the audio untouched. +- GRAB at the next step stops recording: the ring's own frames are written back, so the history survives any + length of hold. A tape head reads it at SPIN. Every STEP track steps the loop returns to its start through a + crossfade from the running head into a second head that has been reading the audio just before the start, so the + audible period is exactly STEP steps (the tests check one cycle against the next and that nothing repeats at half + the period). +- **Timing is the track's own** ([sequencing.md](../../../docs/module-guides/sequencing.md)): a step is the moment + the track's sequencer tick (`0x800064f0 + track`) reaches 1, just after the step's trig, so track speed, tempo and + swing come from the sequencer. The tempo word and the track scale give only the nominal step length used to plan + the crossfade. There is no clock of Freeze's own. A step is detected per 16-sample block, so a loop start may sit + up to 0.36 ms off the exact step. +- STOP lets go and fades to dry. A STEP change lands at the end of the current loop; a tempo change from the next + loop on. PLAY does not restart a loop: Freeze counts steps, not positions in the pattern. +- If the held audio is too short for the loop at the chosen SPIN (slow tempo, slow track speed, 8 steps), SPIN is + lowered to what fits. GRAB waits until at least 4,096 frames (93 ms) have been recorded since the effect was + chosen or last released. + +## Compatibility and limitations + +- **Blocked:** needs the base hook `ev_delay_track` ([proposal](DELAY_HOOK_PROPOSAL.md)). Tape Echo takes the same + stock site today with its own detours; Freeze does not touch it and does not depend on it. +- FX2 only, like stock DELAY (it uses the track's delay ring). On a track whose FX2 is Freeze, stock DELAY and + Tape Echo are not on that track's FX2 by definition, so the ring is Freeze's. +- Linear interpolation: at fractional speeds the held audio loses some top end (strongest at 0.5x). Hermite + interpolation is the planned improvement once CPU is measured. +- The equal-power seam lifts strongly correlated audio (a sustained tone that lines up across the seam) by up to + 2.8 dB in the middle of the seam; uncorrelated material dips 0.24 dB. +- The held loop is runtime state: it is not saved with the project and is gone after a power cycle. +- CPU is not measured. While holding, Freeze reads up to two tape heads and writes the ring back. + +## Tests and measurements + +Host tests only: see [TESTING.md](TESTING.md). `python3 -B sdk/drafts/freeze/verify.py`. + +## Authorship and licences + +Original code by jacobphono, written with Claude Code (Anthropic) under the MIT licence in LICENSE. The musical +brief came from a behavioural reference written independently by Codex for this project. The idea of a looper whose +jitter slowly changes the loop comes from a look at a Reaktor ensemble's control descriptions; no Reaktor code, +structure, artwork, samples or names are used. The crossfaded two-head tape loop and smooth-random wander are +long-published, general techniques. No Elektron firmware, code or tables are included. + +## Screens and audio + +None yet. A synthetic audition render is made with `verify.py --audition `; it is not hardware audio. diff --git a/sdk/drafts/freeze/TESTING.md b/sdk/drafts/freeze/TESTING.md new file mode 100644 index 0000000000..c680fe9c76 --- /dev/null +++ b/sdk/drafts/freeze/TESTING.md @@ -0,0 +1,63 @@ +# Freeze testing + +Only what was run and seen. Engine source as in this branch, 22 November 2026, macOS host (Apple clang), +m68k-elf-gcc 16.2.0. + +## Host gate: `python3 -B sdk/drafts/freeze/verify.py` + +Builds `test_freeze.c` (which includes `freeze.c`) with `-fsanitize=undefined,address -fno-sanitize-recover=all +-Werror`, runs it, then cross-compiles `freeze.c` with Tape Echo's ColdFire flags (`-mcpu=54454 -msoft-float -O3 +-ffreestanding ...`) and refuses any undefined symbol. Result: **53 of 53 checks passed, no sanitizer report; +ColdFire object 6,242 bytes of text, no runtime-library calls.** + +The harness models the adapter: a ring written 16 frames a block as the stock DMA does, and a sequencer whose tick +byte reaches 1 once per track step (the ticks per step of each track speed; swing delays the odd steps' tick). + +| Test | Result | +| --- | --- | +| `lerp` and `mulq15` over INT32_MIN..INT32_MAX and every fraction edge (294 + 35 cases) | within 4 and 1 LSB, no UB | +| GRAB OFF, 20,000 blocks of noise | bit-exact dry; the ring receives the dry input | +| Period, low-passed noise, SPIN 0.5x: N = 1, 3, 5, 7, 8 at 120 BPM; 5 at 90 BPM; 5 at 2x and 3 at 1/2x track speed | each cycle against the next: correlation 1.000; at half the period 0.06 or less | +| A 5-step and a 7-step track at once, own state and ring | 7 and 5 cycles in 35 steps; both restart together there | +| SPIN 0, 64, 127 on 1 kHz | 250.6, 501.1, 999.6 Hz | +| JTR 127 on 1 kHz at 0.5x, 50 ms windows over 40 steps | 490.0-510.0 Hz; 10 cycles in 51 steps (period unchanged) | +| POSITION 0 vs 127 (input level encodes time) | 127 reads 2.87 s older audio | +| Full four-second history at 30 BPM, 8 steps, SPIN 0.25x, JTR 127, POSITION swept 0-127-0 | no read past the held history (deepest 84,298 of 176,272 frames); POSITION range 2.36 s; only held input levels heard | +| Swing 25 % of a step, N = 3 | 10 cycles in 30 steps | +| Tempo 120 to 90 while holding | next period 36,750 samples, as expected | +| Hold for 10 s (the write head laps the ring twice) | ring history bit-identical | +| Release, FADE 20 | back to bit-exact dry | +| GRAB on from entry | waits for 4,096 frames, then holds | +| STOP while holding | fades to dry | +| Dirty entry: state 0xa5, ring full of full-scale garbage, 0.5 s of history, DC 0.1 input | peak 0.137 (two equal heads in a seam: 0.1375); no garbage heard | +| 110 Hz sine through grab, seams, SPIN, POSITION and STEP moves, release, JTR 64 | largest sample step 0.0039 FS, the sine's own | + +What these do not show: anything about the real sequencer bytes (the tick model is an assumption, see +DELAY_HOOK_PROPOSAL.md), the real ring or DMA, CPU time, or how it sounds. The audition render +(`verify.py --audition`) is synthetic: two copies of a synthetic pad, 5 and 7 steps, SPIN 0.5x, JTR 40. + +A finding on the behavioural reference this brief came with (`polyspin_reference.py`, not in this repository): its +two heads half a period apart with sin² gains repeat every **half** period. Run on its own model, N = 5 at 120 BPM +gave correlation 1.000 at both P and P/2. Freeze repeats only at P. + +## Sound quality + +Not tested: no `npm run fx:audit` renders (aliasing, clipping, DC, mono sum, idle). They need the native +harness and a base with the hook. Known by design: linear interpolation loses top end at fractional SPIN, and the +seam lifts correlated audio up to 2.8 dB (README). + +## On the unit + +Not tested. Not runnable: no base carries the hook. + +## Emulator + +Not tested. + +## Stock flows + +Not tested. + +## Performance + +Not measured. No `evidence/performance.json` yet. diff --git a/sdk/drafts/freeze/freeze.c b/sdk/drafts/freeze/freeze.c new file mode 100644 index 0000000000..877e3163f3 --- /dev/null +++ b/sdk/drafts/freeze/freeze.c @@ -0,0 +1,375 @@ +/* Freeze engine: see freeze.h and README.md. Original Modwerk code (MIT). + * + * The idea in one paragraph: while Freeze is not holding, the track's dry + * signal passes untouched and is written to the track's delay ring. GRAB, at + * the track's next step, stops writing (the ring's own frames are written back + * so history survives) and starts a tape head reading the held audio at SPIN + * (0.25x..1.0x, slower and lower). Every N track steps the head goes back to + * the start of the loop. The return is a crossfade from the running head into + * a second head that has been reading the audio just before the loop start, + * timed to arrive at the start exactly when the N-step cycle ends, so the + * audible period is N track steps. Cycles restart on the track's own steps, + * read from its sequencer tick, so they follow tempo, track speed and swing. + * POSITION slews the read point back through the held audio like a scrubbed + * tape; JTR adds a bounded, slow wander of the read point and a small drift of + * each cycle's start. Neither changes the period. */ +#include "freeze.h" + +#define FZ_HALF 32768 + +static const uint16_t fz_spin[128] = { + 4096,4141,4186,4231,4277,4324,4371,4419,4467,4515,4565,4614,4664,4715,4767,4819, + 4871,4924,4978,5032,5087,5142,5198,5255,5312,5370,5428,5487,5547,5607,5668,5730, + 5793,5856,5919,5984,6049,6115,6182,6249,6317,6386,6455,6526,6597,6668,6741,6814, + 6889,6964,7039,7116,7194,7272,7351,7431,7512,7594,7677,7760,7845,7930,8016,8104, + 8192,8283,8374,8467,8561,8655,8751,8848,8946,9045,9145,9246,9348,9452,9556,9662, + 9769,9877,9986,10097,10208,10321,10435,10551,10668,10786,10905,11026,11148,11271,11396,11522, + 11649,11778,11908,12040,12173,12308,12444,12582,12721,12862,13004,13148,13293,13440,13589,13739, + 13891,14045,14200,14358,14516,14677,14839,15004,15170,15337,15507,15679,15852,16027,16205,16384, +}; + +uint32_t freeze_spin_q14(unsigned value) { return fz_spin[value > 127 ? 127 : value]; } + +uint32_t freeze_step_q4(uint32_t tempo24, unsigned scale_index) { + static const uint8_t scales[7] = {3, 4, 6, 8, 12, 24, 48}; + unsigned scale = scales[scale_index < 7 ? scale_index : 2]; + if (tempo24 < 720) tempo24 = 720; /* 30 BPM */ + if (tempo24 > 7200) tempo24 = 7200; /* 300 BPM */ + /* One 1x step is 44100 * 60 / (BPM * 4) = 2,646,000 * 6 / tempo24 samples; + * x16 and the scale: at most 2,646,000 * 48 * 16 / 720 = 2,822,400. */ + return 2646000u * 16u / tempo24 * scale; +} + +/* x * g / 32768 for 0 <= g <= 32768, exact for every 32-bit x, in 32-bit + * multiplies only (no 64-bit runtime call on the ColdFire). */ +static int32_t mulq15(int32_t x, int32_t g) { + int32_t hi = (x >> 16) * g * 2; + uint32_t lo = ((uint32_t)x & 0xffffu) * (uint32_t)g; + return hi + (int32_t)(lo >> 15); +} + +static int32_t clamp64(int64_t v) { + if (v > 0x7fffffffLL) return 0x7fffffff; + if (v < -0x7fffffffLL - 1) return (int32_t)0x80000000u; + return (int32_t)v; +} + +/* a + (b - a) * f / 2^14, the halving keeps b - a inside 32 bits. */ +static int32_t lerp(int32_t a, int32_t b, uint32_t f14) { + /* The true result lies between a and b, but 2 * m alone can pass the + * int32 range (a = INT32_MIN, b = INT32_MAX): add in modulo-2^32 + * arithmetic, whose wrapped result is exactly the in-range value. */ + int32_t m = mulq15((b >> 1) - (a >> 1), (int32_t)(f14 << 1)); + return (int32_t)((uint32_t)a + ((uint32_t)m << 1)); +} + +static uint32_t rand32(FzState *s) { + uint32_t x = s->rng; + x ^= x << 13; x ^= x >> 17; x ^= x << 5; + return s->rng = x; +} + +/* Equal-power-like crossfade curve (3x - x^3) / 2 on Q15; at 0.5 it gives + * 0.6875, so two uncorrelated heads dip 0.24 dB in the middle of a seam. */ +static int32_t seam_curve(uint32_t x) { + if (x >= FZ_HALF) return FZ_HALF; + uint32_t x3 = ((x * x) >> 15) * x >> 15; + return (int32_t)((3u * x - x3) >> 1); +} + +/* Parabolic sine of a 32-bit phase, Q15. */ +static int32_t slow_sine(uint32_t phase) { + uint32_t h = (phase >> 16) & 0x7fffu; /* 0..32767 in the half */ + int32_t y = (int32_t)((h * (32768u - h)) >> 13); /* 0..32768 */ + return (phase & 0x80000000u) ? -y : y; +} + +static void read_frame(const volatile int32_t *ring, uint32_t anchor, uint32_t age, + int32_t *l, int32_t *r) { + uint32_t i = age >> FZ_Q, f = age & (FZ_ONE - 1); + uint32_t a = anchor + FZ_RING - 1u - i; /* age i: the newer frame */ + if (a >= FZ_RING) a -= FZ_RING; + uint32_t b = a ? a - 1u : FZ_RING - 1u; /* age i + 1, older */ + *l = lerp(ring[2 * a], ring[2 * b], f); + *r = lerp(ring[2 * a + 1], ring[2 * b + 1], f); +} + +static uint32_t fade_samples(unsigned fade) { return 256u + 3u * fade * fade; } + +/* JTR's largest wander, Q14 frames: 6.5 ms at 1.0x, scaled with the rate so + * the pitch wander is the same fraction (about 1.2 %) at every SPIN. */ +static uint32_t jitter_q14(unsigned jitter, uint32_t spin) { + return (288u * jitter / 127u) * spin; +} + +/* Plans a cycle: its period, seam, the most SPIN the held audio allows, and + * where on the young edge a cycle may start. */ +static void plan_cycle(FzState *s, const FzParams *p, const FzGrid *g, uint32_t want_spin) { + unsigned steps = p->step < FZ_MAX_STEPS ? p->step + 1u : FZ_MAX_STEPS; + uint32_t step = g->step_q4 >> 4; + if (step < 64) step = 64; + s->cycle_steps = (uint8_t)steps; + s->period = step * steps; + s->seam_len = s->period * (p->seam + 1u) >> 8; + if (s->seam_len < 256) s->seam_len = 256; + if (s->seam_len > s->period / 2) s->seam_len = s->period / 2; + if (s->seam_len > 65536u) s->seam_len = 65536u; + /* Everything a cycle consumes grows with the rate: the loop itself, a + * step of slack for a late (swung) step, the seam's pre-roll and JTR's + * start drift. JTR's wander and the two guards do not. */ + uint32_t jmax = 288u * p->jitter / 127u; + uint32_t fixed = 2u * FZ_GUARD + 2u * jmax + 2u; + uint32_t denom = s->period + step + s->seam_len + s->period / 4u * p->jitter / 127u; + uint32_t cap = s->avail > fixed ? ((s->avail - fixed) << FZ_Q) / denom : 0; + s->spin_cap = cap; + uint32_t sp = want_spin > s->spin ? want_spin : s->spin; /* a glide may still be faster */ + if (sp > cap) sp = cap; + s->base_min = (FZ_GUARD << FZ_Q) + jitter_q14(p->jitter, sp) * 2u + + sp * (s->period + step); + s->reserve_old = (FZ_GUARD << FZ_Q) + jitter_q14(p->jitter, sp) * 2u + + sp * s->seam_len + sp * (s->period / 4u * p->jitter / 127u); +} + +static uint32_t pos_range(const FzState *s) { + uint32_t top = s->avail << FZ_Q; + uint32_t used = s->base_min + s->reserve_old; + return top > used ? top - used : 0; +} + +/* The running head fades out; a new head starts `pre` samples before the + * cycle's end at the matching distance before the new start, so it reaches + * the start when the cycle ends. */ +static void start_seam(FzState *s, const FzParams *p, uint32_t pre) { + uint32_t sp = s->spin; + uint32_t drift_max = sp * (s->period / 4u * p->jitter / 127u); + uint32_t drift = (rand32(s) >> 16) * (drift_max >> 16); /* 0..drift_max */ + uint32_t start = s->base_min + drift + sp * pre; + uint32_t len = pre > 512 ? pre : 512; + if (len > 65536u) len = 65536u; /* keeps the gain ramp in 32 bits */ + FzHead *old = &s->head[s->main_head]; + FzHead *nu = &s->head[s->main_head ^ 1u]; + if (old->active) { old->fading_out = 1; old->fade_pos = 0; old->fade_len = len; } + nu->active = 1; nu->fading_out = 0; nu->fade_pos = 0; nu->fade_len = len; + nu->age = start; nu->gain = 0; + s->main_head ^= 1u; + s->seamed = 1; +} + +static void begin_cycle(FzState *s, const FzParams *p, const FzGrid *g, uint32_t want) { + plan_cycle(s, p, g, want); + if (s->spin > s->spin_cap) s->spin = s->spin_cap; + s->t = 0; + s->steps_in_cycle = 0; + s->seamed = 0; +} + +static void clear(FzState *s, unsigned tick, unsigned running, uint32_t identity) { + uint32_t *w = (uint32_t *)s; + for (unsigned i = 0; i < sizeof(*s) / 4u; ++i) w[i] = 0; + s->active = 1; + s->rng = 0x6d2b79f5u ^ (0x9e3779b9u * (identity + 1u)); + s->lfo = identity * 0x20000000u; + s->prev_tick = (uint8_t)tick; + s->prev_running = (uint8_t)running; +} + +static void start_hold(FzState *s, const FzParams *p, const FzGrid *g, uint32_t write, uint32_t want) { + s->anchor = write; + s->avail = s->valid; + s->head[0].active = s->head[1].active = 0; + s->spin = want; + begin_cycle(s, p, g, want); + s->pos_off = s->pos_target = (pos_range(s) / 127u) * p->position; + /* The first head starts exactly at the cycle start: no seam to cross. */ + FzHead *h = &s->head[0]; + h->active = 1; h->fading_out = 0; h->fade_pos = h->fade_len = 0; + h->gain = FZ_HALF; h->age = s->base_min; + s->main_head = 0; + s->seamed = 0; + s->held = 1; + s->armed_grab = 0; + s->env_target = 1u << 30; +} + +void freeze_process(FzState *s, const FzParams *p, const FzGrid *g, + const volatile int32_t *ring, uint32_t write, + int32_t *audio, int32_t *record) { + if (!s->active) clear(s, g->tick, g->running, write / FZ_FRAMES); + if (write > FZ_RING - FZ_FRAMES) write = 0; + uint32_t want = freeze_spin_q14(p->spin); + unsigned mix = p->mix > 127 ? 127 : p->mix; + int32_t mix_q15 = mix == 127 ? FZ_HALF : (int32_t)(mix * 258u); + + if (p->fade != s->fade_param || !s->env_step) { + s->fade_param = p->fade; + s->env_step = (1u << 30) / fade_samples(p->fade > 127 ? 127 : p->fade); + } + + /* The track's step: its tick reaching 1, once per track step. */ + unsigned boundary = g->running && g->tick == 1 && s->prev_tick != 1; + s->prev_tick = g->tick; + s->prev_running = g->running; + unsigned grab = p->grab != 0; + + if (!g->running) { + /* STOP returns to dry: the hold ends and fades out. */ + s->held = 0; s->armed_grab = 0; s->env_target = 0; + } else if (boundary) { + if (grab && !s->held) { + if (s->env) { /* still fading out: catch it again */ + s->held = 1; s->env_target = 1u << 30; + } else if (s->valid >= 4096u) { + start_hold(s, p, g, write, want); + boundary = 0; /* the grab step starts cycle one */ + } else { + s->armed_grab = 1; /* not enough audio yet: next step */ + } + } else if (!grab && s->held) { + s->held = 0; s->env_target = 0; + } + } + unsigned playing = s->held || s->env; + + if (playing) { + if (boundary) { + ++s->steps_in_cycle; + if (s->steps_in_cycle >= (unsigned)(p->step < FZ_MAX_STEPS ? p->step + 1u : FZ_MAX_STEPS)) { + if (!s->seamed) { plan_cycle(s, p, g, want); start_seam(s, p, 0); } + ++s->cycles; + begin_cycle(s, p, g, want); + } + } else if (s->t > s->period + (g->step_q4 >> 4)) { + /* No step came for a step past the cycle's end (STOP while + * fading out): keep the head inside the audio. */ + if (!s->seamed) start_seam(s, p, 0); + begin_cycle(s, p, g, want); + } + /* Rate glide: a SPIN move slides the tape like a motor. */ + uint32_t target = want < s->spin_cap ? want : s->spin_cap; + int32_t dsp = ((int32_t)target - (int32_t)s->spin) / 64; + if (!dsp && target != s->spin) dsp = target > s->spin ? 1 : -1; + s->spin = (uint32_t)((int32_t)s->spin + dsp); + if (!s->seamed && s->t + FZ_FRAMES > s->period - s->seam_len) { + uint32_t pre = s->period > s->t ? s->period - s->t : 0; + start_seam(s, p, pre); + } + } + + /* Offsets shared by both heads: POSITION slews (a scrub, at most 1/8 of + * the rate per sample) and JTR wanders slowly. */ + uint32_t off0 = s->pos_off + s->jit_off; + if (playing) { + uint32_t range = pos_range(s); + uint32_t ptarget = (range / 127u) * (p->position > 127 ? 127 : p->position); + /* Q14 ages reach 2.89e9: work in unsigned distances, never int32. */ + uint32_t lim = s->spin * 2u; /* at most 32,768 a block */ + if (s->pos_off > range) s->pos_off = range; + if (ptarget > s->pos_off) { + uint32_t d = ptarget - s->pos_off, move = d / 32u; + if (!move) move = 1; + if (move > lim) move = lim; + s->pos_off += move; + } else if (ptarget < s->pos_off) { + uint32_t d = s->pos_off - ptarget, move = d / 32u; + if (!move) move = 1; + if (move > lim) move = lim; + s->pos_off -= move; + } + s->lfo += 483068u; /* 0.31 Hz in blocks */ + if (++s->cell_clock >= 2048u) { /* a new random value every 0.74 s */ + s->cell_clock = 0; + s->cell_from = s->cell_to; + s->cell_to = (int32_t)(rand32(s) >> 17) - 16384; /* Q15 -0.5..0.5 */ + s->cell_to *= 2; + } + uint32_t x = s->cell_clock << 4; /* Q15 */ + uint32_t ss = (x * x >> 15) * (3u * 32768u - 2u * x) >> 15; /* smoothstep */ + int32_t rnd = s->cell_from + (((s->cell_to - s->cell_from) >> 1) * (int32_t)ss >> 14); + int32_t v = (13107 * slow_sine(s->lfo) + 19661 * rnd) >> 15; /* -1..1 */ + uint32_t jmax = jitter_q14(p->jitter, s->spin); + s->jit_off = ((jmax >> 8) * (uint32_t)(32768 + v)) >> 7; + } + uint32_t off1 = s->pos_off + s->jit_off; + /* A block's offset change is bounded (POSITION 32,768 + JTR's slow + * wander), so the signed per-sample step is small; the walk itself is + * done modulo 2^32 and lands on off1. */ + uint32_t dabs = off1 >= off0 ? off1 - off0 : off0 - off1; + uint32_t dstep = dabs / FZ_FRAMES; + uint32_t doff = off1 >= off0 ? dstep : 0u - dstep; + + /* Record: the dry input, or while holding, the ring's own frames. */ + unsigned preserve = s->held || s->env; + if (preserve) { + for (unsigned i = 0; i < 2u * FZ_FRAMES; ++i) record[i] = ring[2u * write + i]; + } else { + for (unsigned i = 0; i < 2u * FZ_FRAMES; ++i) record[i] = audio[i]; + s->valid += FZ_FRAMES; + if (s->valid > FZ_RING - 2u * FZ_GUARD) s->valid = FZ_RING - 2u * FZ_GUARD; + } + + if (!playing && !s->env_target) return; /* exact dry */ + + /* Head gains at this block's edges. */ + int32_t g0[2], gs[2]; + for (unsigned h = 0; h < 2; ++h) { + FzHead *hd = &s->head[h]; + if (!hd->active) { g0[h] = gs[h] = 0; continue; } + if (!hd->fade_len) { g0[h] = FZ_HALF; gs[h] = 0; continue; } + uint32_t a = hd->fade_pos, b = a + FZ_FRAMES; + if (b > hd->fade_len) b = hd->fade_len; + uint32_t xa = a * 32768u / hd->fade_len; /* fade_len <= 65536 */ + uint32_t xb = b * 32768u / hd->fade_len; + int32_t ga = seam_curve(xa), gb = seam_curve(xb); + if (hd->fading_out) { ga = seam_curve(FZ_HALF - xa); gb = seam_curve(FZ_HALF - xb); } + g0[h] = ga; gs[h] = (gb - ga) / (int32_t)FZ_FRAMES; + } + + uint32_t lo = FZ_GUARD << FZ_Q; + uint32_t hi = s->avail > FZ_GUARD ? (s->avail - FZ_GUARD) << FZ_Q : lo; + uint32_t off = off0; + for (unsigned i = 0; i < FZ_FRAMES; ++i) { + int64_t wl = 0, wr = 0; + for (unsigned h = 0; h < 2; ++h) { + FzHead *hd = &s->head[h]; + if (!hd->active) continue; + uint32_t age = hd->age + off; + if (age < hd->age) age = hi; /* wrapped: past the old edge */ + if (age < lo) age = lo; + if (age > hi) age = hi; + int32_t l, r; + read_frame(ring, s->anchor, age, &l, &r); + int32_t gain = g0[h] + gs[h] * (int32_t)i; + if (gain < 0) gain = 0; + if (gain > FZ_HALF) gain = FZ_HALF; + wl += mulq15(l, gain); + wr += mulq15(r, gain); + hd->age = hd->age > s->spin + lo ? hd->age - s->spin : lo; + } + off += doff; + /* Wet envelope, per sample. */ + if (s->env < s->env_target) { + s->env = s->env_target - s->env > s->env_step ? s->env + s->env_step : s->env_target; + } else if (s->env > s->env_target) { + s->env = s->env - s->env_target > s->env_step ? s->env - s->env_step : s->env_target; + } + int32_t w = mulq15((int32_t)(s->env >> 15), mix_q15); /* Q15 wet amount */ + int32_t dl = audio[2 * i], dr = audio[2 * i + 1]; + audio[2 * i] = clamp64((int64_t)mulq15(dl, FZ_HALF - w) + mulq15(clamp64(wl), w)); + audio[2 * i + 1] = clamp64((int64_t)mulq15(dr, FZ_HALF - w) + mulq15(clamp64(wr), w)); + } + for (unsigned h = 0; h < 2; ++h) { + FzHead *hd = &s->head[h]; + if (!hd->active || !hd->fade_len) continue; + hd->fade_pos += FZ_FRAMES; + if (hd->fade_pos >= hd->fade_len) { + if (hd->fading_out) hd->active = 0; + else { hd->fade_len = 0; hd->gain = FZ_HALF; } + } + } + s->t += FZ_FRAMES; + if (!s->held && !s->env) { + /* Release finished: drop the heads, record again from here. */ + s->head[0].active = s->head[1].active = 0; + s->valid = 0; + } +} diff --git a/sdk/drafts/freeze/freeze.h b/sdk/drafts/freeze/freeze.h new file mode 100644 index 0000000000..9d15726aa7 --- /dev/null +++ b/sdk/drafts/freeze/freeze.h @@ -0,0 +1,92 @@ +/* Freeze: a grid-locked, tape-like live loop for one Octatrack track. + * + * Original Modwerk code (MIT, see LICENSE). Freestanding fixed-point C: no + * floating point, heap, runtime library or division in the per-sample path. + * The same source builds natively (FZ_HOST) for the host tests and, once the + * base carries the shared delay-ring hook (DELAY_HOOK_PROPOSAL.md), for the + * ColdFire. It never reads or writes anything but the arguments it is given. + * + * Audio words are the stock delay path's 32-bit stereo words. The ring is the + * stock per-track four-second delay ring (176,400 stereo frames). */ +#ifndef MODWERK_FREEZE_H +#define MODWERK_FREEZE_H +#include + +#define FZ_FRAMES 16u /* one stock delay-routine block */ +#define FZ_RING 176400u /* stereo frames in one track's ring */ +#define FZ_GUARD 64u /* frames kept clear of both history edges */ +#define FZ_Q 14 /* fractional bits of a ring age */ +#define FZ_ONE (1u << FZ_Q) /* SPIN 1.0x, one frame */ +#define FZ_MAX_STEPS 8u + +/* Controls, each 0..127 as the Octatrack stores them (STEP: 0..7 = 1..8). */ +typedef struct { + uint8_t step, spin, jitter, position, grab, mix, fade, seam; +} FzParams; + +/* The track's own sequencer timing, read by the adapter every block: + * running: the track is playing; tick: the track's sequencer tick byte, which + * reaches 1 once per track step, just after the step's trig (so it carries + * track speed, swing and micro timing as the sequencer plays them); + * step_q4: the nominal length of one track step in samples x 16, from the + * tempo word and the track's scale (freeze_step_q4). */ +typedef struct { + uint8_t running, tick; + uint16_t reserved; + uint32_t step_q4; +} FzGrid; + +typedef struct { + uint32_t age; /* Q14 frames back from the anchor (newest held frame) */ + int32_t gain, gain_step; /* Q15 at block edges, interpolated per sample */ + uint32_t fade_pos, fade_len; /* seam crossfade progress in samples */ + uint8_t active, fading_out, reserved[2]; +} FzHead; + +typedef struct { + uint32_t active; /* 0 on effect entry: everything below is reset */ + uint32_t valid; /* contiguous frames written since entry/resume */ + uint32_t anchor; /* ring frame just after the newest held frame */ + uint32_t avail; /* held frames usable behind the anchor */ + uint32_t held, armed_grab; /* holding; GRAB waits for the next step */ + uint32_t env, env_step; /* Q30 wet envelope and its per-sample ramp */ + uint32_t env_target; + uint32_t fade_param; /* FADE value the ramp was computed for */ + uint8_t prev_tick, prev_running, steps_in_cycle, cycle_steps; + uint32_t t; /* samples since the cycle started */ + uint32_t period; /* nominal cycle length in samples */ + uint32_t seam_len; /* crossfade length in samples */ + uint32_t seamed; /* this cycle's seam has started */ + uint32_t spin; /* Q14 current playback rate (glides) */ + uint32_t spin_cap; /* Q14 most the held history allows */ + uint32_t base_min; /* Q14 youngest age a cycle may start at */ + uint32_t reserve_old; /* Q14 frames reserved on the old edge */ + uint32_t pos_off, pos_target; /* Q14 POSITION offset toward older audio */ + uint32_t jit_off; /* Q14 slow tape-wander offset, 0..2J */ + uint32_t rng, lfo, cell_clock; + int32_t cell_from, cell_to; /* smooth random values, Q15 */ + uint32_t cycles; /* completed cycles while held (tests) */ + FzHead head[2]; + uint32_t main_head; +} FzState; + +/* One 16-frame block. + * audio : 16 interleaved stereo frames, the track's signal in and out. + * record: 16 interleaved stereo frames the caller then writes to the ring at + * `write` (the stock DMA write). Freeze fills it with the dry input, + * or, while it holds, with the ring's own frames so history survives. + * ring : the track's ring, FZ_RING frames, read only here. + * write : the ring frame this block's record will be written to; at most + * FZ_RING - FZ_FRAMES. */ +void freeze_process(FzState *s, const FzParams *p, const FzGrid *g, + const volatile int32_t *ring, uint32_t write, + int32_t *audio, int32_t *record); + +/* Nominal track-step length in samples x 16 from the tempo word (BPM x 24) + * and the track scale index 0..6 (2x, 3/2x, 1x, 3/4x, 1/2x, 1/4x, 1/8x). */ +uint32_t freeze_step_q4(uint32_t tempo24, unsigned scale_index); + +/* SPIN 0..127 as a Q14 rate: 0.25x at 0, 0.5x at 64, 1.0x at 127. */ +uint32_t freeze_spin_q14(unsigned value); + +#endif diff --git a/sdk/drafts/freeze/manifest.py b/sdk/drafts/freeze/manifest.py new file mode 100644 index 0000000000..3459b3ad79 --- /dev/null +++ b/sdk/drafts/freeze/manifest.py @@ -0,0 +1,80 @@ +"""Freeze -- a grid-locked, tape-like live loop on FX2 (engine: freeze.c; blocked on DELAY_HOOK_PROPOSAL.md). + +The skeleton below is the scaffold's, kept until the hook exists; unit.s is not the engine. + +THE SKELETON OF A COLDFIRE MODULE: code the build links and places for +you, reached from stock code by detours you name by SYMBOL. +`npm run module:new` made this draft under sdk/drafts/. It builds as it is: +`npm run module:dev -- ` tries it on your unit over USB, and +`npm run module:doctor -- --draft ` checks it. + +sdk/octatrack/modules/repitch/ is a finished one (one linked unit, detours, +pokes); sdk/octatrack/modules/quantizer/ another (units built from the +author's source, kept under upstream/). sdk/octabam/docs/remixer/MODULES.md +"Declaring a ColdFire module" is the guide; sdk/octabam/docs/remixer/PLACEMENT.md +says where the bytes go; docs/OCTATRACK_API.md lists the hooks. + +Say what the module is, which stock routines it changes, what is measured +and what is inferred. Delete every comment below once answered. +""" + +from remix.schema import Category, Proof, Gate, Detour, Kind, Linked, Module, Poke +from remix.stock_guard import stock_guard + +MODULE = Module( + # `name` MUST equal the directory name. `key` is the build identifier and + # appears in the build report, which other tools parse -- so it is API. + name="freeze", + key="FREEZE", + kind=Kind.CF_PATCH, # no DSP code, no chooser row + doc="Grid-locked tape-like live loop in the track delay ring; needs the proposed ev_delay_track hook.", + category=Category.TRACK, author="jacobphono", author_url="https://github.com/jacobphono", + proof=Proof.UNTESTED, proof_note="Engine host-tested only (verify.py); not runnable until a base carries ev_delay_track.", + + # ---- the code: GNU-as units, linked by the build ---------------------- + # ORDER IS LINK ORDER: a unit may reference symbols of units before it. + # `dram=True` puts the unit in the platform runtime (linked with every + # other DRAM unit in the remix, appended behind the loader, depacked at + # boot into the platform's 10 MB reserve at the bottom of the audio + # page arena -- where anything bigger than a few hundred bytes + # belongs; the unit gives up 10 MB of sample memory). `dram=False` places + # it in one of the OS image's free zero runs (~8 KB, shared by everyone) + # for code that must be ROM-resident. Sources are `.s` for m68k-elf-as; + # `cpu="5407"` and "5475" encode this ISA subset identically. + linked=( + Linked("unit", "modules/freeze/unit.s", dram=True), + # Building from someone else's repository? Add it as a submodule + # under modules//upstream and point `source` into it; the + # sources stay theirs and an update is a submodule bump. + # `reference=(addr, sha256)` re-links the unit at the AUTHOR'S own + # address on every build and compares, so a drift from the bytes + # they ratified fails loudly. + ), + + # ---- how stock code reaches it: detours, wired by symbol -------------- + # `site` is a stock instruction; `expect` its bytes (whole instructions, + # asserted before anything is written -- a site that has moved stops + # the build). `kind`: "jmp" for a stub that replays what it displaced + # and jumps on (the common case), "jsr" for a callable that returns, + # "lea" to rewrite a six-byte `lea abs.l,An`'s operand. `pad_to` nops + # the rest of a displaced span longer than six bytes. + detours=( + # Detour(0x400xxxxx, stock_guard(0x400xxxxx, 8, ""), "unit", "my_hook", + # "what this hook is for", kind="jsr", pad_to=None), + ), + + # ---- plain asserted rewrites ------------------------------------------ + pokes=( + # Poke(0x400xxxxx, expect=stock_guard(0x400xxxxx, 2, ""), + # write=bytes.fromhex("6012"), note="bne -> bra: never re-apply"), + ), + + gates=(Gate("modules/freeze/verify.py", remix_arg=False),), + + # A stock pointer array that needs more entries: TableGrow relocates it + # into free space with your symbols appended and repoints every + # reference. + # tables=(TableGrow("...", old=0x400xxxxx, count=16, + # symbols=(("unit", "my_row"),), + # refs=((0x400xxxxx, 0x400xxxxx),)),), +) diff --git a/sdk/drafts/freeze/octamod.module.json b/sdk/drafts/freeze/octamod.module.json new file mode 100644 index 0000000000..25b698c839 --- /dev/null +++ b/sdk/drafts/freeze/octamod.module.json @@ -0,0 +1,157 @@ +{ + "schemaVersion": 2, + "id": "freeze", + "key": "FREEZE", + "name": "Freeze", + "version": "0.1.0", + "category": "effects", + "author": { + "github": "jacobphono", + "credits": [ + "jacobphono" + ] + }, + "nativeManifest": "manifest.py", + "presentation": { + "label": "FREEZE", + "family": "Looper", + "summary": "Holds the last seconds of a track and replays them as a slow, low tape loop every 1 to 8 track steps.", + "overview": "While not holding, the track passes through unchanged and is recorded into its stock delay ring. GRAB captures at the next step; a tape head reads the held audio at SPIN and returns to the loop start every STEP track steps through a crossfade, so odd lengths drift against the pattern.", + "highlights": [ + "Loop lengths of 1 to 8 track steps, following tempo, track speed and swing", + "SPIN 0.25x to 1.0x, slower and lower like tape, 0.5x by default", + "JTR wanders the tape slowly without changing the loop length", + "POS scrubs back through about two seconds of held audio" + ], + "usage": [ + "Not runnable yet: it needs a base hook that is still a proposal (DELAY_HOOK_PROPOSAL.md)." + ] + }, + "controls": [ + { + "name": "STEP", + "default": 4, + "count": 8, + "doc": "loop length in track steps, 1 to 8; a change lands when the current loop ends", + "labels": [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ] + }, + { + "name": "SPIN", + "default": 64, + "count": 128, + "doc": "tape speed of the held audio, 0.25x to 1.0x, 0.5x at 64; slower is lower", + "labels": null + }, + { + "name": "JTR", + "default": 0, + "count": 128, + "doc": "slow bounded tape wander and loop-start drift; the loop length never changes", + "labels": null + }, + { + "name": "POS", + "default": 0, + "count": 128, + "doc": "where the loop reads in the held audio, newest at 0, oldest at 127", + "labels": null + }, + { + "name": "GRAB", + "default": 0, + "count": 2, + "doc": "HOLD captures at the next track step, OFF lets go at the next step", + "labels": [ + "OFF", + "HOLD" + ] + }, + { + "name": "MIX", + "default": 127, + "count": 128, + "doc": "how much of the loop replaces the track while holding", + "labels": null + }, + { + "name": "FADE", + "default": 20, + "count": 128, + "doc": "grab and release crossfade, 6 ms to 1.1 s", + "labels": null + }, + { + "name": "SEAM", + "default": 64, + "count": 128, + "doc": "crossfade where the loop returns to its start, 1/256 to 1/2 of the loop", + "labels": null + } + ], + "compatibility": { + "firmware": "1.40C", + "location": "FX2", + "conflicts": [], + "uiClaims": [], + "limitations": [ + "Not runnable: needs the base hook ev_delay_track, a proposal awaiting the owner (DELAY_HOOK_PROPOSAL.md).", + "Uses the track's stock four-second delay ring, so FX2 only.", + "Host tests only; nothing has run in ot_emu or on a unit, and CPU is not measured." + ], + "effectId": null + }, + "resources": { + "recorded": "Not measured", + "storage": { + "label": "Storage", + "display": "Not measured", + "value": null, + "unit": "unknown", + "method": "unmeasured", + "conditions": "No measurements exist yet. Add exact conditions and source evidence when available.", + "source": "TESTING.md" + }, + "processing": { + "label": "CPU / DSP load", + "display": "Not measured", + "value": null, + "unit": "unknown", + "method": "unmeasured", + "conditions": "No measurements exist yet. Add exact conditions and source evidence when available.", + "source": "TESTING.md" + } + }, + "tests": { + "report": "TESTING.md", + "summary": "Host tests only: 53 of 53 checks under ASan/UBSan and a clean ColdFire cross-compile (TESTING.md). Not run in ot_emu or on hardware.", + "hardwareStatus": "untested", + "evidenceRevision": "b8deefc88b2c3e5f3c6158e364eb741df1924e1d", + "gates": [ + "Worst-case cycles under parameter modulation and maximum load", + "Exact memory region and maximum-instance totals", + "Owner-reviewed real-hardware evidence with actual coverage and limitations" + ] + }, + "license": { + "spdx": "MIT", + "file": "LICENSE", + "declaration": "Original code by jacobphono, written with Claude Code, MIT. No Elektron firmware, code or tables; no Reaktor material." + }, + "media": [], + "access": { + "location": "FX2 chooser of an audio track, once a base carries the hook.", + "steps": [ + "Not available yet." + ], + "screenshots": [] + } +} diff --git a/sdk/drafts/freeze/qualification.example.json b/sdk/drafts/freeze/qualification.example.json new file mode 100644 index 0000000000..f24ba06cd4 --- /dev/null +++ b/sdk/drafts/freeze/qualification.example.json @@ -0,0 +1,84 @@ +{ + "moduleVersion": "0.1.0", + "sourceSha256": "REPLACE_WITH_NATIVE_SOURCE_SHA256", + "imageSha256": "REPLACE_WITH_LOCAL_TESTED_IMAGE_SHA256", + "cycles": [ + { + "processor": "dsp", + "worstCase": null, + "maxConfiguration": null, + "maxInstances": null, + "budget": null, + "unit": "cycles/sample", + "method": "emulator", + "conditions": { + "parameterExtremes": "Describe every minimum, maximum and branch boundary tested.", + "parameterModulation": "Describe simultaneous LFOs, p-locks, MIDI CC and scene sweeps; justify each inapplicable mechanism.", + "modeSwitching": "Describe repeated/interrupted mode, bypass and Part changes.", + "maxLoad": "Describe maximum voices/instances, both cores, FX slots, streaming and USB/MIDI load.", + "inputConditions": "Describe silence, impulses, full-scale inputs, feedback and other worst-case signal conditions." + }, + "report": "TESTING.md" + } + ], + "memory": { + "regions": [ + { + "name": "Replace with each code, state, table, buffer, stack/heap and padding allocation", + "space": "dsp-p", + "words": null, + "wordBits": 24, + "bytes": null, + "scope": "shared" + } + ], + "perInstanceBytes": null, + "sharedBytes": null, + "maxInstances": null, + "totalBytes": null, + "conditions": "State exact build options, alignment, accounting convention, allocator/stack bounds and reused stock/shared memory; justify every absent allocation class.", + "report": "TESTING.md" + }, + "hardware": { + "status": "pending", + "model": "MKII", + "testedOn": "YYYY-MM-DD", + "tester": "Your credited tester handle; no email", + "project": { + "name": "Your local stress project", + "sha256": "REPLACE_WITH_PROJECT_FINGERPRINT", + "recipe": "Record generator/tool revision and command, local source template fingerprint, sample recipe, all settings and modifications needed to reproduce this stress project. Keep the project/card/firmware local." + }, + "durationMinutes": null, + "audioTracks": 8, + "midiTracks": null, + "conditions": { + "parameterExtremes": "Describe every minimum, maximum and branch boundary tested.", + "parameterModulation": "Describe simultaneous LFOs, p-locks, MIDI CC and scene sweeps; justify each inapplicable mechanism.", + "modeSwitching": "Describe repeated/interrupted mode, bypass and Part changes.", + "maxLoad": "Describe maximum voices/instances, both cores, FX slots, streaming and USB/MIDI load.", + "inputConditions": "Describe silence, impulses, full-scale inputs, feedback and other worst-case signal conditions." + }, + "checks": { + "audioContinuity": "failed", + "transport": "failed", + "controls": "failed", + "memoryIntegrity": "failed", + "recovery": "failed" + }, + "report": "TESTING.md", + "maxInstances": null + }, + "documentation": { + "tutorial": { + "title": "Quick tutorial", + "steps": [ + "Explain setup and exactly where to select or enable the module.", + "Demonstrate the main controls with a useful example setting.", + "Explain what to hear/observe and how to stop, reset or bypass." + ] + }, + "screenshots": [], + "screenshotStyle": "black-and-white" + } +} diff --git a/sdk/drafts/freeze/resource-impact.example.json b/sdk/drafts/freeze/resource-impact.example.json new file mode 100644 index 0000000000..8f7457a054 --- /dev/null +++ b/sdk/drafts/freeze/resource-impact.example.json @@ -0,0 +1,21 @@ +{ + "conditions": "Describe the active workload, expensive modes, changing controls, instance count, and whether shared/stock allocations are included.", + "cpu": { + "level": null, + "basis": "source-estimate", + "rationale": "Choose minimal, low, moderate or high from source inspection or a documented workload comparison. Explain the ColdFire work and cite the record; do not invent a utilization percentage.", + "source": "TESTING.md" + }, + "dsp": { + "level": null, + "basis": "source-estimate", + "rationale": "Choose a relative demand tier covering the expensive DSP modes and modulation. Minimal needs an explanation of the small or absent added DSP path.", + "source": "TESTING.md" + }, + "memory": { + "level": null, + "basis": "source-estimate", + "rationale": "Choose a relative footprint tier covering code, state, tables and buffers. Distinguish shared reservations and reused stock buffers from extra per-instance memory.", + "source": "TESTING.md" + } +} diff --git a/sdk/drafts/freeze/test_freeze.c b/sdk/drafts/freeze/test_freeze.c new file mode 100644 index 0000000000..a732f89dbe --- /dev/null +++ b/sdk/drafts/freeze/test_freeze.c @@ -0,0 +1,514 @@ +/* Host tests for the Freeze engine (freeze.c). Build and run: + * cc -std=c99 -O2 -Wall -Wextra -fsanitize=undefined,address -fno-sanitize-recover=all test_freeze.c -lm -o test_freeze && ./test_freeze [out.wav] + * verify.py does exactly this. The harness models what the adapter will + * hand the engine: a track ring written 16 frames a block like the stock DMA, + * and a track sequencer whose tick byte reaches 1 once per track step (swing + * delays that moment on the swung steps). Floating point is used here only, + * for analysis; the engine has none. */ +/* Included, not linked, so the tests reach the engine's static helpers. */ +#include "freeze.c" +#include +#include +#include +#include + +#define SR 44100.0 +#define FS 2147483648.0 +static int failures, checks; +#define CHECK(cond, ...) do { ++checks; if (!(cond)) { ++failures; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0) + +/* ---- a simulated track ------------------------------------------------- */ +typedef struct { + FzState st; + FzParams p; + int32_t *ring; + uint32_t write; + double bpm; + unsigned scale; /* index 0..6 */ + double swing; /* 0..0.3 of a step: delay of odd (0-based) steps */ + unsigned running; + double clock; /* samples since PLAY */ + long steps_seen; /* track steps whose tick 1 has happened */ +} Track; + +static const unsigned ticks_per_step[7] = {3, 4, 6, 8, 12, 24, 48}; +static const double speed_mult[7] = {2.0, 1.5, 1.0, 0.75, 0.5, 0.25, 0.125}; + +static double step_samples(const Track *t) { return SR * 60.0 / (t->bpm * 4.0) / speed_mult[t->scale]; } + +static void track_init(Track *t, double bpm, unsigned step_value) { + memset(t, 0, sizeof *t); + t->ring = calloc(2 * FZ_RING, sizeof(int32_t)); + t->bpm = bpm; t->scale = 2; t->running = 1; + t->p.step = (uint8_t)step_value; t->p.spin = 64; t->p.jitter = 0; t->p.position = 0; + t->p.grab = 0; t->p.mix = 127; t->p.fade = 20; t->p.seam = 64; +} + +/* The track's tick byte at the start of the block beginning at `clock`. */ +static uint8_t tick_at(const Track *t, double clock) { + double step = step_samples(t); + long n = (long)floor(clock / step); + for (long k = n; k >= n - 1 && k >= 0; --k) { + double start = k * step + ((k & 1) ? t->swing * step : 0.0); + if (clock >= start) { + double into = (clock - start) / (step / ticks_per_step[t->scale]); + unsigned tk = (unsigned)into; + if (tk >= ticks_per_step[t->scale]) tk = ticks_per_step[t->scale] - 1u; /* a swung step starts late: the last tick lasts */ + return (uint8_t)((tk + 1u) % ticks_per_step[t->scale]); /* 1 right after the step */ + } + } + return 0; +} + +/* One 16-frame block: audio is in/out. Returns 1 when a step's tick 1 began in this block. */ +static int track_block(Track *t, int32_t *audio) { + FzGrid g = {0}; + g.running = (uint8_t)t->running; + g.tick = t->running ? tick_at(t, t->clock) : 0; + g.step_q4 = freeze_step_q4((uint32_t)lround(t->bpm * 24.0), t->scale); + int32_t record[2 * FZ_FRAMES]; + freeze_process(&t->st, &t->p, &g, t->ring, t->write, audio, record); + memcpy(&t->ring[2 * t->write], record, sizeof record); /* the stock DMA write */ + t->write += FZ_FRAMES; + if (t->write >= FZ_RING) t->write = 0; + if (t->running) t->clock += FZ_FRAMES; + return 0; +} + +/* ---- signals ------------------------------------------------------------ */ +static uint32_t lcg = 12345; +static double noise(void) { lcg = lcg * 1664525u + 1013904223u; return ((int32_t)lcg) / FS; } +static int32_t q(double x) { if (x > 0.999) x = 0.999; if (x < -0.999) x = -0.999; return (int32_t)lrint(x * FS); } + +/* Fills a block from a generator over absolute sample index n. */ +typedef double (*Gen)(long n, int ch); +static double gen_sine1k(long n, int ch) { (void)ch; return 0.25 * sin(2 * M_PI * 1000.0 * n / SR); } +static double gen_sine110(long n, int ch) { (void)ch; return 0.25 * sin(2 * M_PI * 110.0 * n / SR); } +static double gen_noise(long n, int ch) { (void)n; (void)ch; return 0.25 * noise(); } +/* Noise through a two-pole low-pass near 1.5 kHz: musical bandwidth, so a + * repeat read at a different fractional position still matches. */ +static double lp1, lp2; +static double gen_lpnoise(long n, int ch) { + (void)n; if (ch) return lp2; + lp1 += 0.19 * (noise() - lp1); lp2 += 0.19 * (lp1 - lp2); return lp2 * 2.0; +} +static double gen_time(long n, int ch) { (void)ch; return 0.9 * (double)(n % 400000) / 400000.0; } /* level = time */ + +static void fill(int32_t *a, long n0, Gen gen) { + for (unsigned i = 0; i < FZ_FRAMES; ++i) { a[2 * i] = q(gen(n0 + i, 0)); a[2 * i + 1] = q(gen(n0 + i, 1)); } +} + +/* Output index of the first cycle start inside the last captured run. */ +static long first_cycle_at; + +/* Runs `blocks` blocks, capturing the left output into out (may be NULL). */ +static void run(Track *t, long *n, long blocks, Gen gen, double *out) { + int32_t a[2 * FZ_FRAMES]; + if (out) first_cycle_at = -1; + for (long b = 0; b < blocks; ++b) { + fill(a, *n, gen); + uint32_t c = t->st.cycles; + track_block(t, a); + if (out && first_cycle_at < 0 && t->st.cycles != c) first_cycle_at = b * FZ_FRAMES; + if (out) for (unsigned i = 0; i < FZ_FRAMES; ++i) out[b * FZ_FRAMES + i] = a[2 * i] / FS; + *n += FZ_FRAMES; + } +} + + +static double seg_corr(const double *x, long a, long b, long n) { + double xy = 0, xx = 0, yy = 0; + for (long i = 0; i < n; ++i) { xy += x[a + i] * x[b + i]; xx += x[a + i] * x[a + i]; yy += x[b + i] * x[b + i]; } + return xx > 0 && yy > 0 ? xy / sqrt(xx * yy) : 0; +} + +/* Mean over cycles of the best match between the middle half of one cycle + * and the same stretch `lag` later, each pair aligned on its own within +-w + * samples (each cycle starts on the block where the track's tick reaches 1). */ +static double cycle_corr(const double *x, long len, long period, long lag, long w) { + double sum = 0; int count = 0; + for (long a = first_cycle_at + period / 4; a + lag + period / 2 + w < len; a += period) { + double best = -1; + for (long d = -w; d <= w; ++d) { double c = seg_corr(x, a, a + lag + d, period / 2); if (c > best) best = c; } + sum += best; ++count; + } + return count ? sum / count : 0; +} + +static double zero_cross_hz(const double *x, long len) { + long z = 0; + for (long i = 1; i < len; ++i) if ((x[i - 1] < 0) != (x[i] < 0)) ++z; + return z / 2.0 / (len / SR); +} + +static long blocks_for(double samples) { return (long)ceil(samples / FZ_FRAMES); } + +/* ---- tests -------------------------------------------------------------- */ +static void test_dry_exact(void) { + Track t; track_init(&t, 120, 4); + int32_t a[2 * FZ_FRAMES], in[2 * FZ_FRAMES]; + long n = 0; int exact = 1, rec = 1; + for (long b = 0; b < 20000; ++b) { + fill(a, n, gen_noise); memcpy(in, a, sizeof a); + uint32_t w = t.write; + track_block(&t, a); + if (memcmp(a, in, sizeof a)) exact = 0; + if (memcmp(&t.ring[2 * w], in, sizeof in)) rec = 0; + n += FZ_FRAMES; + } + CHECK(exact, "GRAB OFF must be bit-exact dry"); + CHECK(rec, "GRAB OFF must record the dry input to the ring"); +} + +/* Output of one held track at a steady state, for analysis. */ +static double *held_render(Track *t, Gen gen, double settle_steps, double steps, long *len) { + long n = 0; + run(t, &n, blocks_for(SR * 3.0), gen, NULL); /* three seconds of history */ + t->p.grab = 1; + run(t, &n, blocks_for(step_samples(t) * settle_steps), gen, NULL); + *len = blocks_for(step_samples(t) * steps) * FZ_FRAMES; + double *out = malloc(sizeof(double) * (size_t)*len); + run(t, &n, *len / FZ_FRAMES, gen, out); + return out; +} + +static void test_period(unsigned steps, double bpm, unsigned scale, double spin_ratio_expect) { + Track t; track_init(&t, bpm, steps - 1); t.scale = scale; + long len; + double *out = held_render(&t, gen_lpnoise, 2.0 * steps + 1, 4.0 * steps, &len); + long P = lround(step_samples(&t) * steps); + double cp = cycle_corr(out, len, P, P, 24), ch = cycle_corr(out, len, P, P / 2, 24), c1 = cycle_corr(out, len, P, lround(step_samples(&t)), 24); + printf(" N=%u %.0f BPM speed %.3gx: corr(P)=%.3f corr(P/2)=%.3f corr(1 step)=%.3f spin cap=%.3f\n", + steps, bpm, speed_mult[scale], cp, ch, c1, t.st.spin_cap / 16384.0); + CHECK(cp > 0.99, "N=%u: output must repeat every N track steps (corr %.3f)", steps, cp); + if (steps > 1) CHECK(fabs(ch) < 0.5, "N=%u: output must not repeat at half the period (corr %.3f)", steps, ch); + CHECK(fabs(t.st.spin / 16384.0 - spin_ratio_expect) < 0.01, "spin %.3f, expected %.3f", t.st.spin / 16384.0, spin_ratio_expect); + free(out); free(t.ring); +} + +static void test_two_instances(void) { + /* Tracks 5 and 7 steps at once, each with its own state and ring: after 35 + * steps they have done 7 and 5 cycles, and they line up again only there. */ + Track a, b; track_init(&a, 120, 4); track_init(&b, 120, 6); + long na = 0, nb = 0; + run(&a, &na, blocks_for(SR * 3), gen_noise, NULL); + run(&b, &nb, blocks_for(SR * 3), gen_sine110, NULL); + a.p.grab = b.p.grab = 1; + double step = step_samples(&a); + /* Advance to just after the grab step (one step), then 35 steps more. */ + long blocks = blocks_for(step * 36.5); + int32_t buf[2 * FZ_FRAMES]; + for (long k = 0; k < blocks; ++k) { + fill(buf, na, gen_noise); track_block(&a, buf); na += FZ_FRAMES; + fill(buf, nb, gen_sine110); track_block(&b, buf); nb += FZ_FRAMES; + } + printf(" 5-step and 7-step tracks over 35 steps: %u and %u cycles\n", a.st.cycles, b.st.cycles); + CHECK(a.st.cycles == 7, "5-step instance: %u cycles in 35 steps, expected 7", a.st.cycles); + CHECK(b.st.cycles == 5, "7-step instance: %u cycles in 35 steps, expected 5", b.st.cycles); + CHECK(a.st.t == b.st.t, "after 35 steps both cycles restart together (t %u vs %u)", a.st.t, b.st.t); + free(a.ring); free(b.ring); +} + +static void test_spin_pitch(void) { + const unsigned values[3] = {0, 64, 127}; + const double expect[3] = {250, 500, 1000}; + for (int k = 0; k < 3; ++k) { + Track t; track_init(&t, 120, 7); + t.p.spin = (uint8_t)values[k]; t.p.seam = 0; + long len; + double *out = held_render(&t, gen_sine1k, 1.2, 3.0, &len); + /* inside one cycle, away from the seam */ + double hz = zero_cross_hz(out, len / 2); + printf(" SPIN %3u: %.1f Hz from a 1 kHz input\n", values[k], hz); + CHECK(fabs(hz - expect[k]) < expect[k] * 0.02, "SPIN %u: %.1f Hz, expected %.0f", values[k], hz, expect[k]); + free(out); free(t.ring); + } +} + +static void test_jitter(void) { + Track t; track_init(&t, 120, 4); + t.p.jitter = 127; + long len; + double *out = held_render(&t, gen_sine1k, 11, 40, &len); + /* Pitch over 50 ms windows: bounded wander around 500 Hz. */ + long w = (long)(SR * 0.05); + double lo = 1e9, hi = 0; + for (long i = 0; i + w <= len; i += w) { + double hz = zero_cross_hz(out + i, w); + if (hz < lo) lo = hz; + if (hz > hi) hi = hz; + } + printf(" JTR 127: pitch over 50 ms windows %.1f..%.1f Hz (nominal 500), cycles %u in 51 steps\n", lo, hi, t.st.cycles); + CHECK(lo > 480 && hi < 520, "JTR wander must stay within 4 %% of the rate (%.1f..%.1f Hz)", lo, hi); + CHECK(hi - lo > 1.0, "JTR 127 must move the pitch at all (%.1f..%.1f)", lo, hi); + CHECK(t.st.cycles == 10, "JTR must not change the period: %u cycles in 51 steps, expected 10", t.st.cycles); + free(out); free(t.ring); +} + +static void test_position(void) { + double level[2]; + for (int k = 0; k < 2; ++k) { + Track t; track_init(&t, 120, 2); + t.p.position = (uint8_t)(k ? 127 : 0); + long len; + double *out = held_render(&t, gen_time, 8, 3, &len); + double sum = 0; for (long i = 0; i < len; ++i) sum += out[i]; + level[k] = sum / len; + free(out); free(t.ring); + } + /* The input level rises with time, so older audio is lower. */ + double age_s = (level[0] - level[1]) / 0.9 * 400000.0 / SR; + printf(" POSITION 127 reads %.2f s older audio than POSITION 0\n", age_s); + CHECK(age_s > 1.0, "POSITION must reach well back into the held audio (%.2f s)", age_s); +} + +static void test_preserve_and_release(void) { + Track t; track_init(&t, 120, 4); + long n = 0; + run(&t, &n, blocks_for(SR * 3), gen_noise, NULL); + t.p.grab = 1; + run(&t, &n, blocks_for(step_samples(&t) * 1.5), gen_noise, NULL); + CHECK(t.st.held, "GRAB must hold after the next step"); + int32_t *snap = malloc(2 * FZ_RING * sizeof(int32_t)); + memcpy(snap, t.ring, 2 * FZ_RING * sizeof(int32_t)); + run(&t, &n, blocks_for(SR * 10), gen_noise, NULL); /* the write head laps the ring twice */ + CHECK(!memcmp(snap, t.ring, 2 * FZ_RING * sizeof(int32_t)), "a hold must leave the ring's history intact"); + t.p.grab = 0; + run(&t, &n, blocks_for(step_samples(&t) * 1.2 + 256 + 3 * 20 * 20), gen_noise, NULL); + CHECK(!t.st.held && !t.st.env, "release must fade back to dry within FADE"); + int32_t a[2 * FZ_FRAMES], in[2 * FZ_FRAMES]; + fill(a, n, gen_noise); memcpy(in, a, sizeof a); track_block(&t, a); + CHECK(!memcmp(a, in, sizeof a), "after the release the track is bit-exact dry again"); + free(snap); free(t.ring); +} + +static void test_clicks(void) { + /* A 110 Hz sine: its largest step between samples is 0.25*2*pi*110/44100 + * = 0.0039 FS. Grab, cycles, seams, a SPIN move, a POSITION move, STEP + * changes and the release must never step more than a few times that. */ + Track t; track_init(&t, 120, 4); + t.p.jitter = 64; + long n = 0; + run(&t, &n, blocks_for(SR * 3), gen_sine110, NULL); + long total = blocks_for(SR * 12) * FZ_FRAMES; + double *out = malloc(sizeof(double) * (size_t)total); + long b = 0, blocks = total / FZ_FRAMES; + int32_t a[2 * FZ_FRAMES]; + for (; b < blocks; ++b) { + double s = b * FZ_FRAMES / SR; + t.p.grab = s > 0.3 && s < 10.0; + if (s > 3.0) t.p.spin = 100; + if (s > 5.0) t.p.position = 127; + if (s > 6.5) t.p.step = 2; + if (s > 8.0) t.p.step = 6; + fill(a, n, gen_sine110); track_block(&t, a); n += FZ_FRAMES; + for (unsigned i = 0; i < FZ_FRAMES; ++i) out[b * FZ_FRAMES + i] = a[2 * i] / FS; + } + double worst = 0; long at = 0; + for (long i = 1; i < total; ++i) { double d = fabs(out[i] - out[i - 1]); if (d > worst) { worst = d; at = i; } } + printf(" largest sample step through grab, seams, SPIN/POSITION/STEP moves and release: %.4f FS at %.2f s (sine's own 0.0039)\n", + worst, at / SR); + CHECK(worst < 0.0039 * 3.0, "a click: %.4f FS at %.3f s", worst, at / SR); + free(out); free(t.ring); +} + +static void test_swing_and_tempo(void) { + /* Swing delays the odd steps' ticks: cycles still count track steps. */ + Track t; track_init(&t, 120, 2); + t.swing = 0.25; + long n = 0; + run(&t, &n, blocks_for(SR * 3), gen_noise, NULL); + t.p.grab = 1; + run(&t, &n, blocks_for(step_samples(&t) * (1.5 + 30)), gen_noise, NULL); + printf(" swing 25 %% of a step, N=3: %u cycles in 30 steps\n", t.st.cycles); + CHECK(t.st.cycles == 10, "swung 3-step cycles: %u in 30 steps, expected 10", t.st.cycles); + + /* A tempo change while holding: the next cycle takes the new length. */ + Track u; track_init(&u, 120, 4); + long m = 0; + run(&u, &m, blocks_for(SR * 3), gen_noise, NULL); + u.p.grab = 1; + run(&u, &m, blocks_for(step_samples(&u) * 11.5), gen_noise, NULL); + u.bpm = 90; u.clock = 0; /* restart the model's grid at the new tempo */ + run(&u, &m, blocks_for(step_samples(&u) * 11), gen_noise, NULL); + double expect = 5 * SR * 60 / (90 * 4.0); + printf(" tempo 120 -> 90 while holding: period %u samples (expected %.0f)\n", u.st.period, expect); + CHECK(fabs(u.st.period - expect) < 2, "period after a tempo change: %u, expected %.0f", u.st.period, expect); + free(t.ring); free(u.ring); +} + +static void test_stop_and_short_history(void) { + Track t; track_init(&t, 120, 4); + long n = 0; + t.p.grab = 1; /* GRAB on from entry: too little audio yet */ + run(&t, &n, blocks_for(step_samples(&t) * 0.5), gen_noise, NULL); + CHECK(!t.st.held, "GRAB must wait for 4096 frames of history"); + run(&t, &n, blocks_for(SR * 1.0), gen_noise, NULL); + CHECK(t.st.held, "GRAB must hold once enough history exists"); + t.running = 0; + run(&t, &n, blocks_for(256 + 3 * 20 * 20 + 64), gen_noise, NULL); + CHECK(!t.st.held && !t.st.env, "STOP must fade back to dry"); + free(t.ring); +} + +static double gen_dc(long n, int ch) { (void)n; (void)ch; return 0.1; } + +static void test_dirty_entry(void) { + Track t; track_init(&t, 120, 6); + memset(&t.st, 0xa5, sizeof t.st); + t.st.active = 0; /* effect entry */ + for (uint32_t i = 0; i < 2 * FZ_RING; ++i) t.ring[i] = (int32_t)(i * 2654435761u); /* a previous effect's garbage */ + long n = 0; + t.p.jitter = 127; t.p.position = 127; t.p.spin = 127; + run(&t, &n, blocks_for(SR * 0.5), gen_dc, NULL); /* valid is only 0.5 s */ + t.p.grab = 1; + double *out = malloc(sizeof(double) * (size_t)blocks_for(SR * 4) * FZ_FRAMES); + run(&t, &n, blocks_for(SR * 4), gen_dc, out); + double peak = 0; long len = blocks_for(SR * 4) * FZ_FRAMES; + for (long i = 0; i < len; ++i) if (fabs(out[i]) > peak) peak = fabs(out[i]); + printf(" dirty entry, 0.5 s of history, SPIN 1.0x, POSITION/JTR 127: peak %.3f FS, spin cap %.3f\n", peak, t.st.spin_cap / 16384.0); + /* DC 0.1 in: two equal heads in a seam reach 0.1 * 2 * 0.6875 = 0.1375; the + * previous effect's full-scale garbage would be far above that. */ + CHECK(peak < 0.14, "garbage outside the valid history must never be heard (peak %.3f)", peak); + free(out); free(t.ring); +} + + +static void test_lerp_extremes(void) { + const int32_t v[] = {INT32_MIN, INT32_MIN + 1, -1, 0, 1, INT32_MAX - 1, INT32_MAX}; + const uint32_t f[] = {0, 1, 8191, 8192, 16382, 16383}; + int bad = 0; + for (unsigned i = 0; i < 7; ++i) for (unsigned j = 0; j < 7; ++j) for (unsigned k = 0; k < 6; ++k) { + double exact = (double)v[i] + ((double)v[j] - (double)v[i]) * f[k] / 16384.0; + double got = lerp(v[i], v[j], f[k]); + if (fabs(got - exact) > 4.0) { if (!bad) printf(" lerp(%d, %d, %u) = %.0f, exact %.1f\n", v[i], v[j], f[k], got, exact); ++bad; } + } + CHECK(!bad, "lerp is off by more than 4 LSB in %d of 294 extreme cases", bad); + const int32_t g[] = {0, 1, 16384, 32767, 32768}; + for (unsigned i = 0; i < 7; ++i) for (unsigned k = 0; k < 5; ++k) { + double exact = (double)v[i] * g[k] / 32768.0, got = mulq15(v[i], g[k]); + if (fabs(got - exact) > 1.0) ++bad; + } + CHECK(!bad, "mulq15 is off by more than 1 LSB at an extreme"); +} + +static void test_full_ring_position(void) { + /* A full four-second history (Q14 ages near 2.89e9), slow tempo so the + * loop is long, POSITION swept from 0 to 127 and back while held. */ + Track t; track_init(&t, 30, 7); + t.p.spin = 0; t.p.jitter = 127; + long n = 0; + run(&t, &n, blocks_for(SR * 5), gen_time, NULL); + CHECK(t.st.valid == FZ_RING - 2 * FZ_GUARD, "history full before the grab (%u)", t.st.valid); + t.p.grab = 1; + double step = step_samples(&t); + run(&t, &n, blocks_for(step * 1.2), gen_time, NULL); + CHECK(t.st.held, "held with a full ring"); + double maxage = 0, lo = 1e9, hi = -1e9; + long blocks = blocks_for(SR * 12); + int32_t a[2 * FZ_FRAMES]; + for (long b = 0; b < blocks; ++b) { + double s = b * FZ_FRAMES / SR; + t.p.position = (uint8_t)(s < 4 ? 127 * s / 4 : s < 8 ? 127 : 127 * (12 - s) / 4); + fill(a, n, gen_time); track_block(&t, a); n += FZ_FRAMES; + for (int h = 0; h < 2; ++h) if (t.st.head[h].active) { + double age = ((double)t.st.head[h].age + t.st.pos_off + t.st.jit_off) / 16384.0; + if (age > maxage) maxage = age; + } + double y = a[0] / FS; if (y < lo) lo = y; if (y > hi) hi = y; + } + printf(" full ring, 30 BPM, 8 steps: avail %u frames, deepest read %.0f frames (%.2f s), pos range %.2f s, output %.3f..%.3f\n", + t.st.avail, maxage, maxage / SR, pos_range(&t.st) / 16384.0 / SR, lo, hi); + CHECK(maxage <= t.st.avail - FZ_GUARD + 1, "a head read past the held history (%.0f > %u)", maxage, t.st.avail - FZ_GUARD); + CHECK(pos_range(&t.st) / 16384.0 / SR > 0.5, "POSITION must still reach back at least 0.5 s on a full ring"); + CHECK(lo >= -0.001 && hi <= 0.91, "only held input levels may be heard (%.3f..%.3f)", lo, hi); + free(t.ring); +} + +/* ---- audition ----------------------------------------------------------- */ +static double pad(long n, int ch) { + /* An original synthetic pad: a slow minor-seventh chord, detuned per channel. */ + static const double f[4] = {110.0, 130.81, 164.81, 196.0}; + double t = n / SR, y = 0; + for (int k = 0; k < 4; ++k) { + double det = 1.0 + (ch ? 0.0021 : -0.0017) * (k + 1); + double ph = fmod(f[k] * det * t, 1.0); + y += (2.0 * ph - 1.0) * 0.5 + sin(2 * M_PI * f[k] * det * t) * 0.5; + } + double swell = 0.6 + 0.4 * sin(2 * M_PI * 0.07 * t); + double chord = (n / (long)(SR * 2.0)) % 2 ? 1.0 : 1.12246; /* moves a tone every 2 s */ + (void)chord; + return 0.06 * y * swell; +} + +static void write_wav(const char *path, const float *lr, long frames) { + FILE *fp = fopen(path, "wb"); + if (!fp) { printf("cannot write %s\n", path); return; } + uint32_t data = (uint32_t)frames * 4u, riff = 36u + data, rate = 44100, brate = rate * 4u, fmt = 16; + uint16_t pcm = 1, chn = 2, align = 4, bits = 16; + fwrite("RIFF", 1, 4, fp); fwrite(&riff, 4, 1, fp); fwrite("WAVEfmt ", 1, 8, fp); + fwrite(&fmt, 4, 1, fp); fwrite(&pcm, 2, 1, fp); fwrite(&chn, 2, 1, fp); fwrite(&rate, 4, 1, fp); + fwrite(&brate, 4, 1, fp); fwrite(&align, 2, 1, fp); fwrite(&bits, 2, 1, fp); + fwrite("data", 1, 4, fp); fwrite(&data, 4, 1, fp); + for (long i = 0; i < 2 * frames; ++i) { double v = lr[i]; if (v > 1) v = 1; if (v < -1) v = -1; int16_t s = (int16_t)lrint(v * 32767); fwrite(&s, 2, 1, fp); } + fclose(fp); +} + +static void audition(const char *path) { + /* 16 s at 120 BPM: two tracks of the same pad, Freeze 5 steps and 7 steps, + * SPIN 0.5x, JTR 40; grab at 4 s (bar 3), release at 13 s. */ + Track a, b; track_init(&a, 120, 4); track_init(&b, 120, 6); + a.p.jitter = b.p.jitter = 40; a.p.fade = b.p.fade = 40; + long frames = blocks_for(SR * 16) * FZ_FRAMES; + float *lr = calloc((size_t)frames * 2, sizeof(float)); + int32_t ba[2 * FZ_FRAMES], bb[2 * FZ_FRAMES]; + for (long blk = 0; blk < frames / FZ_FRAMES; ++blk) { + long n = blk * FZ_FRAMES; double s = n / SR; + a.p.grab = b.p.grab = s > 4.0 && s < 13.0; + fill(ba, n, pad); fill(bb, n, pad); + track_block(&a, ba); track_block(&b, bb); + for (unsigned i = 0; i < FZ_FRAMES; ++i) { + lr[2 * (n + i)] = (float)((ba[2 * i] / FS) * 0.9 + (bb[2 * i] / FS) * 0.5); + lr[2 * (n + i) + 1] = (float)((ba[2 * i + 1] / FS) * 0.5 + (bb[2 * i + 1] / FS) * 0.9); + } + } + write_wav(path, lr, frames); + printf(" wrote %s (16 s: 5-step left, 7-step right, SPIN 0.5x, JTR 40, grab 4 s, release 13 s)\n", path); + free(lr); free(a.ring); free(b.ring); +} + +int main(int argc, char **argv) { + printf("Freeze host tests\n"); + printf("arithmetic:\n"); + test_lerp_extremes(); + test_dry_exact(); + printf("period lock (low-passed noise input, SPIN 0.5x):\n"); + test_period(3, 120, 2, 0.5); + test_period(5, 120, 2, 0.5); + test_period(7, 120, 2, 0.5); + test_period(8, 120, 2, 0.5); + test_period(1, 120, 2, 0.5); + test_period(5, 90, 2, 0.5); + test_period(5, 120, 0, 0.5); /* 2x track speed */ + test_period(3, 120, 4, 0.5); /* 1/2x track speed */ + printf("independent instances:\n"); + test_two_instances(); + printf("SPIN:\n"); + test_spin_pitch(); + printf("JTR:\n"); + test_jitter(); + printf("POSITION:\n"); + test_position(); + printf("swing and tempo:\n"); + test_swing_and_tempo(); + printf("hold, release, STOP, entry:\n"); + test_preserve_and_release(); + test_stop_and_short_history(); + test_dirty_entry(); + test_full_ring_position(); + printf("clicks:\n"); + test_clicks(); + if (argc > 1) audition(argv[1]); + printf("%d of %d checks passed\n", checks - failures, checks); + return failures ? 1 : 0; +} diff --git a/sdk/drafts/freeze/test_freeze.py b/sdk/drafts/freeze/test_freeze.py new file mode 100644 index 0000000000..d8a3a21f18 --- /dev/null +++ b/sdk/drafts/freeze/test_freeze.py @@ -0,0 +1,17 @@ +"""Runs Freeze's host gate (verify.py) under npm run sdk:check and module:doctor.""" +import pathlib +import runpy +import sys +import unittest + + +class FreezeHostGate(unittest.TestCase): + def test_gate(self): + sys.argv = [str(pathlib.Path(__file__).with_name('verify.py'))] + with self.assertRaises(SystemExit) as done: + runpy.run_path(sys.argv[0], run_name='__main__') + self.assertIn(done.exception.code, (0, 77)) + + +if __name__ == '__main__': + unittest.main() diff --git a/sdk/drafts/freeze/unit.s b/sdk/drafts/freeze/unit.s new file mode 100644 index 0000000000..886cafcc85 --- /dev/null +++ b/sdk/drafts/freeze/unit.s @@ -0,0 +1,17 @@ +| -- one linked unit. GNU as, ColdFire ISA A+ (m68k-elf-as). +| +| Symbols you `.global` here are what the manifest's Detours name. Absolute +| references to stock code are fine (`jsr (0x40001e50).l`); references to +| your own labels are resolved by the link wherever the build places this, +| so write `lea SYM:l,%a0` for a same-unit address you need as a pointer +| (a bare `lea SYM,%a0` assembles pc-relative -- correct, but four bytes +| shorter than a hand-assembled original if you are matching one). + .text + .global my_hook + +| A "jsr" detour lands here and expects an rts. A "jmp" detour's target +| must first REPLAY the instructions the six-byte jmp displaced, then jump +| back to site+6 (or wherever those instructions would have continued). +my_hook: + nop + rts diff --git a/sdk/drafts/freeze/verify.py b/sdk/drafts/freeze/verify.py new file mode 100644 index 0000000000..f7a947f069 --- /dev/null +++ b/sdk/drafts/freeze/verify.py @@ -0,0 +1,52 @@ +"""Freeze's gate: builds the engine's host tests with the address and undefined-behaviour +sanitizers and runs them, then cross-compiles the engine for the ColdFire with Tape Echo's +flags and refuses any runtime-library call. No firmware is involved. + + python3 -B sdk/drafts/freeze/verify.py [--audition out.wav] +""" +import pathlib +import shutil +import subprocess +import sys +import tempfile + +HERE = pathlib.Path(__file__).resolve().parent +CF_FLAGS = ['-mcpu=54454', '-msoft-float', '-O3', '-ffreestanding', '-fno-builtin', '-fno-common', + '-fno-jump-tables', '-fno-asynchronous-unwind-tables', '-fno-ident', '-fomit-frame-pointer'] + + +def main() -> int: + args = sys.argv[1:] + audition = args[args.index('--audition') + 1] if '--audition' in args else None + cc = shutil.which('cc') or shutil.which('clang') or shutil.which('gcc') + if not cc: + print('[SKIP] no host C compiler') + return 77 + with tempfile.TemporaryDirectory() as tmp: + exe = pathlib.Path(tmp) / 'test_freeze' + subprocess.run([cc, '-std=c99', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-fsanitize=undefined,address', '-fno-sanitize-recover=all', + str(HERE / 'test_freeze.c'), '-lm', '-o', str(exe)], check=True, cwd=HERE) + run = subprocess.run([str(exe)] + ([audition] if audition else []), cwd=HERE) + if run.returncode: + print('[FAIL] host tests') + return 1 + gcc = shutil.which('m68k-elf-gcc') + if not gcc: + print('[SKIP] ColdFire cross-compile: m68k-elf-gcc not installed') + else: + obj = pathlib.Path(tmp) / 'freeze.o' + subprocess.run([gcc, *CF_FLAGS, '-Wall', '-Wextra', '-Werror', '-c', str(HERE / 'freeze.c'), + '-o', str(obj)], check=True) + undefined = subprocess.run(['m68k-elf-nm', '-u', str(obj)], capture_output=True, text=True, + check=True).stdout.split() + if undefined: + print('[FAIL] the ColdFire engine needs runtime-library calls:', ' '.join(undefined)) + return 1 + print('[OK] ColdFire 54454 build: no runtime-library calls') + print('[OK] Freeze host gate') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From f70ba670e8f3eccab65957135421bc5327c95da6 Mon Sep 17 00:00:00 2001 From: Jacob Phono Thiessen Date: Sun, 22 Nov 2026 01:32:24 +0100 Subject: [PATCH 2/4] Freeze: name version 0.1.0 and its tested build in TESTING.md Co-Authored-By: Claude Opus 5.5 --- sdk/drafts/freeze/TESTING.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sdk/drafts/freeze/TESTING.md b/sdk/drafts/freeze/TESTING.md index c680fe9c76..a264d32445 100644 --- a/sdk/drafts/freeze/TESTING.md +++ b/sdk/drafts/freeze/TESTING.md @@ -1,7 +1,10 @@ # Freeze testing -Only what was run and seen. Engine source as in this branch, 22 November 2026, macOS host (Apple clang), -m68k-elf-gcc 16.2.0. +Only what was run and seen. + +**Version 0.1.0.** Tested build: the engine and tests in commit `1d435dd80` (`freeze.c`, `freeze.h`, +`test_freeze.c`, `verify.py`), 22 November 2026, macOS host (Apple clang) and m68k-elf-gcc 16.2.0. Host +tests only. 0.1.0 has no USB package and has not run in `ot_emu` or on a unit: **not tested on hardware.** ## Host gate: `python3 -B sdk/drafts/freeze/verify.py` From 8288f2b564224869bc13b97a9ea00f515312b29b Mon Sep 17 00:00:00 2001 From: Jacob Phono Thiessen Date: Sun, 22 Nov 2026 15:24:52 +0100 Subject: [PATCH 3/4] Freeze: latch STEP for the active loop --- sdk/drafts/freeze/freeze.c | 4 +-- sdk/drafts/freeze/freeze.h | 2 +- sdk/drafts/freeze/test_freeze.c | 49 ++++++++++++++++++++++++++++++++- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/sdk/drafts/freeze/freeze.c b/sdk/drafts/freeze/freeze.c index 877e3163f3..757b1964c8 100644 --- a/sdk/drafts/freeze/freeze.c +++ b/sdk/drafts/freeze/freeze.c @@ -233,8 +233,8 @@ void freeze_process(FzState *s, const FzParams *p, const FzGrid *g, if (playing) { if (boundary) { ++s->steps_in_cycle; - if (s->steps_in_cycle >= (unsigned)(p->step < FZ_MAX_STEPS ? p->step + 1u : FZ_MAX_STEPS)) { - if (!s->seamed) { plan_cycle(s, p, g, want); start_seam(s, p, 0); } + if (s->steps_in_cycle >= s->cycle_steps) { + if (!s->seamed) start_seam(s, p, 0); ++s->cycles; begin_cycle(s, p, g, want); } diff --git a/sdk/drafts/freeze/freeze.h b/sdk/drafts/freeze/freeze.h index 9d15726aa7..1920e61222 100644 --- a/sdk/drafts/freeze/freeze.h +++ b/sdk/drafts/freeze/freeze.h @@ -52,7 +52,7 @@ typedef struct { uint32_t env, env_step; /* Q30 wet envelope and its per-sample ramp */ uint32_t env_target; uint32_t fade_param; /* FADE value the ramp was computed for */ - uint8_t prev_tick, prev_running, steps_in_cycle, cycle_steps; + uint8_t prev_tick, prev_running, steps_in_cycle, cycle_steps; /* cycle_steps is latched until the next boundary */ uint32_t t; /* samples since the cycle started */ uint32_t period; /* nominal cycle length in samples */ uint32_t seam_len; /* crossfade length in samples */ diff --git a/sdk/drafts/freeze/test_freeze.c b/sdk/drafts/freeze/test_freeze.c index a732f89dbe..812d4d2049 100644 --- a/sdk/drafts/freeze/test_freeze.c +++ b/sdk/drafts/freeze/test_freeze.c @@ -66,13 +66,14 @@ static int track_block(Track *t, int32_t *audio) { g.running = (uint8_t)t->running; g.tick = t->running ? tick_at(t, t->clock) : 0; g.step_q4 = freeze_step_q4((uint32_t)lround(t->bpm * 24.0), t->scale); + int boundary = g.running && g.tick == 1 && t->st.prev_tick != 1; int32_t record[2 * FZ_FRAMES]; freeze_process(&t->st, &t->p, &g, t->ring, t->write, audio, record); memcpy(&t->ring[2 * t->write], record, sizeof record); /* the stock DMA write */ t->write += FZ_FRAMES; if (t->write >= FZ_RING) t->write = 0; if (t->running) t->clock += FZ_FRAMES; - return 0; + return boundary; } /* ---- signals ------------------------------------------------------------ */ @@ -312,6 +313,49 @@ static void test_clicks(void) { free(out); free(t.ring); } +static void test_step_change(unsigned initial, unsigned next) { + Track t; track_init(&t, 120, initial - 1); + long n = 0; + int32_t audio[2 * FZ_FRAMES]; + run(&t, &n, blocks_for(SR * 3), gen_sine110, NULL); + t.p.grab = 1; + for (long b = 0; b < blocks_for(step_samples(&t) * 2) && !t.st.held; ++b) { + fill(audio, n, gen_sine110); track_block(&t, audio); n += FZ_FRAMES; + } + CHECK(t.st.held && t.st.cycle_steps == initial, + "STEP %u -> %u: hold must start with %u steps", initial, next, initial); + if (!t.st.held) { free(t.ring); return; } + + unsigned steps = 0, first = 0, second = 0; + for (long b = 0; b < blocks_for(step_samples(&t) * (initial + next + 2)); ++b) { + fill(audio, n, gen_sine110); + int boundary = track_block(&t, audio); + n += FZ_FRAMES; + if (!boundary) continue; + ++steps; + if (steps == 1) { + CHECK(t.st.steps_in_cycle == 1 && t.st.cycles == 0, + "STEP %u -> %u: first held step must stay in the first cycle", initial, next); + t.p.step = (uint8_t)(next - 1); + } + if (t.st.cycles == 1 && !first) { + first = steps; + CHECK(t.st.cycle_steps == next, + "STEP %u -> %u: new length was not latched at the boundary", initial, next); + CHECK(t.st.period == (freeze_step_q4((uint32_t)lround(t.bpm * 24.0), t.scale) >> 4) * next, + "STEP %u -> %u: new period was not planned", initial, next); + } + if (t.st.cycles == 2) { second = steps; break; } + } + printf(" STEP %u -> %u after first step: cycle boundaries at steps %u and %u\n", + initial, next, first, second); + CHECK(first == initial, "STEP %u -> %u: first cycle ended at %u, expected %u", + initial, next, first, initial); + CHECK(second == initial + next, "STEP %u -> %u: second cycle ended at %u, expected %u", + initial, next, second, initial + next); + free(t.ring); +} + static void test_swing_and_tempo(void) { /* Swing delays the odd steps' ticks: cycles still count track steps. */ Track t; track_init(&t, 120, 2); @@ -499,6 +543,9 @@ int main(int argc, char **argv) { test_jitter(); printf("POSITION:\n"); test_position(); + printf("STEP changes:\n"); + test_step_change(5, 2); + test_step_change(2, 5); printf("swing and tempo:\n"); test_swing_and_tempo(); printf("hold, release, STOP, entry:\n"); From cfa93b49466942d7ee8b9ed4655ea67655f9c4d3 Mon Sep 17 00:00:00 2001 From: Jacob Phono Thiessen Date: Sun, 22 Nov 2026 15:26:23 +0100 Subject: [PATCH 4/4] Freeze: record STEP edge cases and pending unit checks --- sdk/drafts/freeze/TESTING.md | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/sdk/drafts/freeze/TESTING.md b/sdk/drafts/freeze/TESTING.md index a264d32445..613102fa45 100644 --- a/sdk/drafts/freeze/TESTING.md +++ b/sdk/drafts/freeze/TESTING.md @@ -2,16 +2,16 @@ Only what was run and seen. -**Version 0.1.0.** Tested build: the engine and tests in commit `1d435dd80` (`freeze.c`, `freeze.h`, -`test_freeze.c`, `verify.py`), 22 November 2026, macOS host (Apple clang) and m68k-elf-gcc 16.2.0. Host +**Version 0.1.0.** Tested build: the engine, header and tests in commit `8288f2b56`, with the unchanged +`verify.py` from `1d435dd80`, 22 November 2026, macOS host (Apple clang) and m68k-elf-gcc 16.2.0. Host tests only. 0.1.0 has no USB package and has not run in `ot_emu` or on a unit: **not tested on hardware.** ## Host gate: `python3 -B sdk/drafts/freeze/verify.py` Builds `test_freeze.c` (which includes `freeze.c`) with `-fsanitize=undefined,address -fno-sanitize-recover=all -Werror`, runs it, then cross-compiles `freeze.c` with Tape Echo's ColdFire flags (`-mcpu=54454 -msoft-float -O3 --ffreestanding ...`) and refuses any undefined symbol. Result: **53 of 53 checks passed, no sanitizer report; -ColdFire object 6,242 bytes of text, no runtime-library calls.** +-ffreestanding ...`) and refuses any undefined symbol. Result: **65 of 65 checks passed, no sanitizer report; +ColdFire object 6,116 bytes of text, no runtime-library calls.** The harness models the adapter: a ring written 16 frames a block as the stock DMA does, and a sequencer whose tick byte reaches 1 once per track step (the ticks per step of each track speed; swing delays the odd steps' tick). @@ -22,6 +22,8 @@ byte reaches 1 once per track step (the ticks per step of each track speed; swin | GRAB OFF, 20,000 blocks of noise | bit-exact dry; the ring receives the dry input | | Period, low-passed noise, SPIN 0.5x: N = 1, 3, 5, 7, 8 at 120 BPM; 5 at 90 BPM; 5 at 2x and 3 at 1/2x track speed | each cycle against the next: correlation 1.000; at half the period 0.06 or less | | A 5-step and a 7-step track at once, own state and ring | 7 and 5 cycles in 35 steps; both restart together there | +| STEP 5 to 2 after the first held step | first cycle ends at step 5; the next ends at step 7 (2 more steps) | +| STEP 2 to 5 after the first held step | first cycle ends at step 2; the next ends at step 7 (5 more steps) | | SPIN 0, 64, 127 on 1 kHz | 250.6, 501.1, 999.6 Hz | | JTR 127 on 1 kHz at 0.5x, 50 ms windows over 40 steps | 490.0-510.0 Hz; 10 cycles in 51 steps (period unchanged) | | POSITION 0 vs 127 (input level encodes time) | 127 reads 2.87 s older audio | @@ -32,7 +34,7 @@ byte reaches 1 once per track step (the ticks per step of each track speed; swin | Release, FADE 20 | back to bit-exact dry | | GRAB on from entry | waits for 4,096 frames, then holds | | STOP while holding | fades to dry | -| Dirty entry: state 0xa5, ring full of full-scale garbage, 0.5 s of history, DC 0.1 input | peak 0.137 (two equal heads in a seam: 0.1375); no garbage heard | +| Dirty entry: state 0xa5, ring full of full-scale garbage, 0.5 s of history, DC 0.1 input | peak 0.137 (two equal heads in a seam: 0.1375); no garbage reached the output | | 110 Hz sine through grab, seams, SPIN, POSITION and STEP moves, release, JTR 64 | largest sample step 0.0039 FS, the sine's own | What these do not show: anything about the real sequencer bytes (the tick model is an assumption, see @@ -43,6 +45,18 @@ A finding on the behavioural reference this brief came with (`polyspin_reference two heads half a period apart with sin² gains repeat every **half** period. Run on its own model, N = 5 at 120 BPM gave correlation 1.000 at both P and P/2. Freeze repeats only at P. +## Edge cases + +| Case | Why this change makes it a risk | How run | Result | +| --- | --- | --- | --- | +| STEP 5 to 2 after the first held step | The live knob used to end a five-step cycle at step two, before its planned seam. | `test_step_change(5, 2)` in the sanitized host gate; inspect both cycle boundaries and the new latched period. | **Pass, host:** boundaries at steps 5 and 7; the two-step setting applies only to the second cycle. | +| STEP 2 to 5 after the first held step | The live knob used to extend the current cycle beyond its planned seam. | `test_step_change(2, 5)` in the same gate. | **Pass, host:** boundaries at steps 2 and 7; the five-step setting applies only to the second cycle. | +| Short and long cycles, track speed and tempo | A changed length can exhaust the held ring or drift off the track grid. | Host period tests at 1, 3, 5, 7 and 8 steps, 90/120 BPM and 2x/0.5x track speed; full-ring test at 30 BPM. | **Pass, host:** consecutive cycles correlate at 1.000; the full-ring test stays in bounds. | +| STEP change with the real sequencer, swing and live tempo | The host fixture models the tick byte and swing; it cannot prove when the unit emits them. | After a shared delay hook and Freeze adapter exist, inspect the tick at the seam in `ot_emu`, then change STEP during a held loop on the unit at swung and changed tempo. | **Not run:** the base has no shared delay hook; there is no runnable Freeze package. | +| Two FX2 instances on opposite DSP cores beside stock effects and Tape Echo | State and the per-track ring must stay separate, while the stock site belongs to Tape Echo today. | Host test with simultaneous five- and seven-step instances; later use the shared hook for a unit trial on two tracks and check stock flows. | **Pass, host:** 7 and 5 cycles in 35 steps. **Not run on unit:** hook and adapter are absent. | +| GRAB release, STOP/PLAY, Part/project reload, Undo and power cycle | Runtime loop state and the base's package lifecycle may differ from the fixture. | Host release and STOP tests; after a package exists, run the test procedure and check the unit's actual playback and restoration. | **Pass, host:** release returns to exact dry and STOP fades out. **Not run on unit:** no package; Part/project, Undo and power cycle remain untested. | +| Maximum CPU load and real delay-ring bounds | Two read heads and ring preservation add work in the frame interrupt. | Host full-ring bounds test; later measure CPU and both cores on the unit at maximum modulation and two instances. | **Pass, host:** held-ring reads stay in bounds. **Not run on unit:** no adapter or CPU measurement. | + ## Sound quality Not tested: no `npm run fx:audit` renders (aliasing, clipping, DC, mono sum, idle). They need the native