Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Aurora: import your own samples as wavetables (#380)
Chris Laupama7a4f0af652ab
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8ff19e40..0b643dad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,27 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Custom wavetables in Nota Aurora** (specs/053): drop a WAV, FLAC or MP3 file on either+ oscillator, from the browser or the desktop, or pick **Import…** in its table drop-down.+ Aurora turns it into a table as follows:+ - a standard wavetable file, with a `clm ` frame size or a length that is a multiple of+ 2048, keeps its frames, up to 256;+ - a file of up to 4096 samples is taken as one cycle;+ - anything longer is cut into 16 frames, evenly spaced through it.+ Only the first 60 s are read. Stereo is mixed to mono, DC is removed and the table is+ normalised. A long file loads in the background. A silent or unreadable file is refused,+ with the reason under the oscillator.+ The table window draws the imported frames and follows the position each played note is+ at, as LFOs and envelopes move it. The drop-down switches between the imported table and+ the built-in ones and can remove the import. Import and remove are one undo step each,+ and notes that are sounding stop when you import. Imported tables are band-limited, so a+ bright table played high does not fold back. Each takes up to about 7 MB of memory.+ Projects save each table inside the bundle, once even when several oscillators share it,+ so a project opens with its tables even after the source file is gone. User presets carry+ their tables too. The project format is now 31. Older projects open unchanged; a project+ saved by this version needs this version or later to open.+ An Aurora inside a rack keeps its tables, but cannot import one yet. Built-in tables and+ factory presets sound exactly as before.- **XL for Nota EQ-8, Dynamic EQ-8, Lens and Auto Filter** (#540): the card's size toggle gains XL, which movesthe whole editor into a large panel above the device chain, as wide as the chain, with thegraph stretched to fill it. The card in the chain stays as a small 260 × 260 one that saysdiff --git a/FEATURES.md b/FEATURES.mdindex 3aaad42a..4907a593 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -783,7 +783,12 @@ audio effects after it keep running and keep their settings; saved with the projtwo envelopes, two tempo-syncable LFOs, an 8×7 mod matrix, 8 macros over 12destinations, pitch-bend (±2/±5/±12) and modulation wheels, output pan, a switchable FXchain (drive Tube/Tape/Fold with tone · chorus 1×/2×/4× · reverb Room/Hall/Plate with- size), Mono/Poly. 25 factory presets.+ size), Mono/Poly. Both oscillators sit side by side on the Osc tab, each with its own+ table window. **Custom wavetables**: drop a WAV, FLAC or MP3 on an oscillator, or pick+ **Import…** in its table drop-down. A wavetable file keeps up to 256 frames, a short file+ becomes one cycle, and a recording is cut into 16 frames. Tables are band-limited, are+ saved inside the project and in user presets, and the window follows the position each+ note plays. 25 factory presets.- **Nota Operator** — FM synth: 4 operators (wave, coarse ratio, fine detune, level andtheir own ADSR each), 11 algorithms with interactive diagrams and drag-to-reroute,feedback, a live harmonic spectrum, an LP/HP/BP filter with keyboard tracking, pitch-benddiff --git a/specs/053-aurora-one-card/contracts/c-abi.md b/specs/053-aurora-one-card/contracts/c-abi.mdindex c4e188cc..5296640b 100644--- a/specs/053-aurora-one-card/contracts/c-abi.md+++ b/specs/053-aurora-one-card/contracts/c-abi.md@@ -45,6 +45,10 @@ NOTA_API int32_t nota_aurora_table_from_frames(const float* frames, int32_t framNotaAuroraTable** out);NOTA_API int32_t nota_aurora_table_info(const NotaAuroraTable* t, NotaAuroraTableInfo* out);+/* The base frames (2048 × frames floats) into out; returns floats written, or the count when+ * out is null. Added in implementation: the app writes a fresh import to the bundle from+ * these, without decoding the file again (research R13). */+NOTA_API int64_t nota_aurora_table_frames(const NotaAuroraTable* t, float* out, int64_t cap);NOTA_API void nota_aurora_table_free(NotaAuroraTable* t);```@@ -59,8 +63,11 @@ NOTA_API int32_t nota_track_aurora_set_table(NotaEngine* e, int32_t track_id, inconst NotaAuroraTable* t, int32_t checkpoint);/* Remove the imported table from osc (one undo step); the oscillator plays its built-in. */NOTA_API int32_t nota_track_aurora_clear_table(NotaEngine* e, int32_t track_id, int32_t osc);-/* In place, lock-free: 1 = play the imported table, 0 = the built-in. No undo. */-NOTA_API int32_t nota_track_aurora_set_source(NotaEngine* e, int32_t track_id, int32_t osc, int32_t use_custom);+/* 1 = play the imported table, 0 = the built-in. checkpoint 1 = one undo step (republish,+ * as set_table; inside a parameter gesture the bank change merges into it, so a bank pick+ * that leaves the import undoes as one step), 0 = in place, lock-free, no undo (loads). */+NOTA_API int32_t nota_track_aurora_set_source(NotaEngine* e, int32_t track_id, int32_t osc, int32_t use_custom,+ int32_t checkpoint);/* Mark osc as missing (name shown as "Missing: <name>"); "" clears. No undo. */NOTA_API int32_t nota_track_aurora_set_missing(NotaEngine* e, int32_t track_id, int32_t osc, const char* name_utf8);```@@ -74,8 +81,9 @@ NOTA_API int32_t nota_track_aurora_table_info(const NotaEngine* e, int32_t trackNOTA_API int64_t nota_track_aurora_table_read(const NotaEngine* e, int32_t track_id, int32_t osc,float* out, int64_t cap);/* Drawing preview: rep_frames (≤ 16) evenly chosen frames then grid_frames (≤ 64) evenly chosen- * frames, each `points` (≤ 256) samples of the lowest mip level that keeps the shape, back to- * back. Returns floats written. */+ * frames, each `points` (≤ 256) values back to back. Each frame is a min / max outline of+ * its base level: points / 2 slices, each giving its min and max in the order they occur, so+ * a bright frame keeps its envelope (research R13). Returns floats written. */NOTA_API int32_t nota_track_aurora_table_preview(const NotaEngine* e, int32_t track_id, int32_t osc,int32_t rep_frames, int32_t grid_frames, int32_t points,float* out, int32_t cap);@@ -91,6 +99,9 @@ the layout given in [../data-model.md](../data-model.md) § Scope telemetry.## Rack chains (message thread)+> **Deferred** (research R13): not in this release. An Aurora inside a rack keeps its+> tables through the state blob, but its card cannot import or remove one yet.+These mirror `nota_rack_set_chain_sampler_sample` (`nota_engine.h:1801`). They carry the samesemantics, but address an Aurora in Instrument Rack chain `chain`, or on a Drum Rack pad:diff --git a/specs/053-aurora-one-card/contracts/state-blob.md b/specs/053-aurora-one-card/contracts/state-blob.mdindex 28110583..02d7d5ba 100644--- a/specs/053-aurora-one-card/contracts/state-blob.md+++ b/specs/053-aurora-one-card/contracts/state-blob.md@@ -6,7 +6,7 @@ follows at the **end** of the blob:```textoffset content-0 float32 × P parameters (P = kNumParams of the writer; 156 today)+0 float32 × P parameters (P = kNumParams of the writer; 162 today, 156 before #531)4P section (S bytes):char[4] "AWT1"u32 version = 1diff --git a/specs/053-aurora-one-card/data-model.md b/specs/053-aurora-one-card/data-model.mdindex 213a6352..ad0e34df 100644--- a/specs/053-aurora-one-card/data-model.md+++ b/specs/053-aurora-one-card/data-model.md@@ -72,6 +72,7 @@ load path.| 2 | Osc 1 table serial (0 = built-in) || 3 | Osc 2 table serial || 4 | active voices |+| 5 | sources: bit 0 set when Osc 1 plays its imported table, bit 1 for Osc 2 |## State blob trailerdiff --git a/specs/053-aurora-one-card/perf-baseline.md b/specs/053-aurora-one-card/perf-baseline.mdnew file mode 100644index 00000000..572932c9--- /dev/null+++ b/specs/053-aurora-one-card/perf-baseline.md@@ -0,0 +1,82 @@+# Performance record: 053-aurora-one-card++Baselines (T005) and results (T045) for SC-003 to SC-006.++## Where these numbers come from++**These are not acceptance numbers from the 036 reference machine (i7-12700).** They were+taken in a 4-core Linux container with no display. Each comparison below was run on that+same container, before and after, so the deltas mean something; the absolute values do+not carry over. The reference-machine runs (quickstart § 4 and § 5, with `pidstat`) are+still to do.++- Engine: Release. The UI was measured in a Release build of a headless Avalonia+ harness (Skia, 2× scale) that opens the fixture project, shows the device chain on the+ Osc tab of each Aurora in turn, and plays the loop.+- Fixtures: `--aurora-ui-fixture <dir> --builtin` writes `baseline.nota` (stamped format 27+ so the base build opens it). `--aurora-ui-fixture <dir>` writes `scenario.nota`, with+ 256-frame tables on both oscillators of all 4 Auroras. Both have LFOs on both positions+ and a 4-bar chord loop.+- **base**: the card before this feature (6b8a83e2), on `baseline.nota`.+ **feat-base**: this branch on `baseline.nota`. **feat-scen**: this branch on+ `scenario.nota` (the SC-003 scenario).+- **UI work**: wall time of the live tick (`RefreshSynthLive` plus the jobs it posts) per+ second, over 600 ticks at 60 Hz. It stands in for UI-thread %CPU.+ **Table paint**: one `AuroraTableView` rendered alone into a bitmap, 600 to 1200 samples.+ **Probe paint**: `NOTA_UI_PROBE=aurora`, measured in the tree.+ **Card build**: from the device-chain rebuild to the first frame, 12 switches.++## UI (SC-003, SC-004, SC-005)++| Run | UI work | Table paint p50 / p99 | Probe paint p99 | Card build → first frame p50 |+|-----|---------|-----------------------|-----------------|------------------------------|+| base, run 1 / 2 | 10.4 / 8.1 ms/s (1.0 / 0.8 % of a core) | 1.80 / 4.44, 1.80 / 3.70 ms | — | 204 / 205 ms |+| feat-base | 7.5 ms/s (0.75 %) | 0.46 / 1.26 ms | 1.46 ms | 191 ms |+| feat-scen | 7.9 ms/s (0.79 %) | 0.43 / 1.65 ms | 1.48 ms | 184 ms (probe: 115 ms to first paint) |++The first version of the imported view, with no cache, failed SC-004: feat-scen painted at+6.4 / 10.6 ms (p50 / p99) and the tick took 47 to 54 ms/s. That triggered T046. The view+now draws the window and the depth stack once into a bitmap, keyed by table serial, bank,+size, inset, dim, scale and ink colour, and paints only the lit frame on top each tick. The+lit index moves on a 64-step grid, so a paint happens only on a step.++- **SC-003 (≤ +2 points over today's card, ≤ 5 % in total)**: met in the container:+ 0.79 % against the base's 0.8 to 1.0 %.+- **SC-004 (≤ 2 ms p99 per paint)**: met: 1.5 to 1.65 ms.+- **SC-005 (≤ 100 ms card build)**: **not met here, and the unchanged card misses it too**+ (about 204 ms in this container). This feature is no slower than the base (184 to 191+ ms). It needs checking on the reference machine before it can be called.+- **FR-018 (no work while hidden)**: the tick that drives `RefreshSynthLive` is skipped+ while the device chain is not effectively visible (`MainWindow.axaml.cs`, the+ `IsEffectivelyVisible` gate), and the whole tick returns early while the window is+ minimised, unless the floating detail window is still showing. No table-view work runs+ in either state; the probe counts no paints.++## Audio (SC-006): `nota_perf`++Callgrind instructions for 4 s of render. These repeat exactly between runs, and they are+what the perf gate compares.++| Engine | Scenario | Instructions | vs base |+|--------|----------|--------------|---------|+| base (6b8a83e2) | `aurora-supersaw-2x` | 3 724 778 244 | — |+| this branch | `aurora-supersaw-2x` | 3 754 726 913 | +0.80 % |+| this branch | `aurora-imported-2x` | 4 056 732 784 | +8.0 % over built-in tables on this branch |++The rise on built-in tables is the snapshot read at the top of each block, plus the+per-oscillator custom-table check. It stays under the gate's 1 % limit. The imported+tables cost more because each read picks a mip level and reads a sized level. That stays+within SC-006's +10 %.++Wall time (ms of render per s of audio, 20 s, six rounds interleaved): base 60.2 to+71.1, this branch 64.6 to 69.6, imported 65.9 to 80.7. The fastest rounds were 60.2, 64.6+and 65.9. In this container that is 2.4× the 036 reference figure (about 28 ms/s), so only+the ratios carry over.++`aurora-imported-2x` reports "base error" against an engine without the table calls. The+harness looks those calls up at run time, so it still builds against the base header, and+the gate accepts that row.++Factory presets: the null gate in `--aurora-tables` renders each factory preset on this+branch and compares it with the stored built-in render. The residual is −240 dBFS, so the+renders are bit-identical.diff --git a/specs/053-aurora-one-card/research.md b/specs/053-aurora-one-card/research.mdindex 2fa819cd..7b9fc836 100644--- a/specs/053-aurora-one-card/research.md+++ b/specs/053-aurora-one-card/research.md@@ -294,3 +294,56 @@ with like (the same project shape on old and new cards).| Rack-hosted Aurora import goes through the proxy engine | Dedicated task, with rack-chain ABI variants || Preset JSON of about 2.8 MB for 256-frame tables | Acceptable. Tested for load time in quickstart § 3 || Built-in sound regression | The built-in branch stays untouched. The `--aurora-null` gate runs in the smoke test |++## R13. Changes made during implementation++Places where the plan proved wrong or too big, and the smaller choice taken instead.++- **Mip levels (R4)**. Halving the length at each level leaves level k with 2 samples per+ cycle of its top harmonic. The linear read then rolls the top octave off and folds part of+ it back (a C3 check measured −39 dB, against a −40 dB gate). The plan's clamp at k = 5+ also leaves 32 harmonics at C7, which alias. Now there are **ten levels**: level k keeps+ `1024 >> k` harmonics, its length is `clamp(4096 >> k, 256, 2048)` with level 0 at 2048,+ and that gives at least 4 samples per cycle. C3 measures −51 dB and the C7 alias check+ −73 dB. Memory is **3.5 × the base, about 7 MB per 256-frame table** (the plan said 4 MB).+ The CHANGELOG states it.+- **Mip pick per read, not per block**. Unison voices and Sync / Bend each step the+ phase at their own rate, so the level is picked per read, from that read's increment (with+ the warp bias). That costs one comparison loop, and it removes the R12 pitch-bend jump+ across a block. The `aurora-imported-2x` scenario costs +8 % over built-in tables,+ within SC-006 (perf-baseline.md).+- **Preview (R9)**. A plain resample of the base level drew bright frames as flat lines.+ The preview is now a **min / max outline** of the base level: `points / 2` slices, each+ emitting its min and max in the order they occur. Its shape matches what is heard at low+ pitch.+- **Drawing (R9)**. 17 cached geometries per paint still cost 6.4 / 10.6 ms (p50 / p99) in+ the container: SC-004 failed, so T046 applied. The view now renders the window chrome and+ the depth stack once into a `RenderTargetBitmap`, keyed by table serial, bank, size,+ inset, dim, render scale and ink colour, so a theme or scale change rebuilds it. Each+ paint draws only the lit frame on top. Built-in tables use the same path. Result: 0.43 /+ 1.65 ms. This reverses the "Alternatives" note in R9.+- **Rack chains (T040, T041) deferred**. An Aurora inside a rack keeps its tables: they+ travel in the instrument state blob, and the smoke test checks a group / ungroup round+ trip. But the rack card cannot import or remove a table yet, so the card hides **Import…**+ inside a rack. The chain ABI variants and the proxy forwarding are left for a follow-up.+- **ABI**. One extra call, `nota_aurora_table_frames`, copies a table's base frames out, so+ the app can write them to the project bundle without decoding the file again.+- **Handles**. Managed code holds table handles as `nint`, with `try / finally` around+ `AuroraTableFree`, not a `SafeHandle`. Each handle lives for one call chain.+- **Hash**. The table hash is a 128-bit pair of FNV-style mixes over the base frames. It+ needs no new dependency, and it is only used to dedupe bundle files, not for security.+- **`clm ` chunk**. A declared frame size is accepted only as a power of two from 256 to+ 4096. Any other value falls back to the 2048-multiple rule.+- **Measurement (R11)**. The runs were done in a 4-core container with a headless+ Avalonia harness, not with `pidstat` on the 036 machine. Each run was compared against+ the base card on the same container. SC-005 (100 ms) is missed **by the unchanged card+ too** there (about 204 ms). The feature is no slower (184 to 191 ms). The+ reference-machine run is still owed (perf-baseline.md).+- **UI fixture**. The baseline project is saved by this branch, then stamped+ `formatVersion: 27`, because nothing in it needs 28. That lets the base build open it.+- **Presets**. A preset saved with no tables (including Init) clears any imported table+ when applied in place, so applying a preset always gives the sound it was saved with.++- **Format renumbered (Oct 31).** develop took format v28 for sidechain parts (specs/050, #381), so the Aurora tables are format **v29**: `CurrentFormatVersion` 28 → 29 with a no-op `Migration(28)`. Where this spec says v28 for the tables, read v29.+- **Format renumbered again (Nov 5).** develop took format v29 for take lanes (specs/067), so the Aurora tables are format **v30**: `CurrentFormatVersion` 29 → 30 with a no-op `Migration(29)`. Where this spec says v28 or v29 for the tables, read v30.+- **Format renumbered again (Nov 10).** develop took format v30 for articulation maps (specs/085, #549), so the Aurora tables are format **v31**: `CurrentFormatVersion` 30 → 31 with a no-op `Migration(30)`. Where this spec says v28, v29 or v30 for the tables, read v31.diff --git a/specs/053-aurora-one-card/tasks.md b/specs/053-aurora-one-card/tasks.mdindex 7f643abe..2bed45d0 100644--- a/specs/053-aurora-one-card/tasks.md+++ b/specs/053-aurora-one-card/tasks.md@@ -34,11 +34,11 @@ its own.**Purpose**: The test harness, fixtures, the measurement probe, and the baseline numberstaken on the **unchanged** code.-- [ ] T001 Add `tests/Nota.SmokeTest/AuroraTableTests.cs` (SPDX header, empty test groups for conditioning, undo, state, project, preset, rack, scope). Register the `--aurora-tables` mode in `tests/Nota.SmokeTest/Program.cs`, next to `--aurora-null` (`Program.cs:536-551`), and add the group to the full run.-- [ ] T002 [P] Add `tests/Nota.SmokeTest/AuroraFixtures.cs` and the `--aurora-fixtures <dir>` mode. It writes the quickstart § 2 files (cycle-2048, table-64x2048 with a `clm ` chunk, table-300x2048, stereo vowel-2s FLAC, long-90s, silence, broken, x.aiff) through `tests/Nota.SmokeTest/WavWriter.cs` and the engine's encoder.-- [ ] T003 [P] Add the `--aurora-ui-fixture <dir> [--builtin]` mode in `tests/Nota.SmokeTest/AuroraFixtures.cs`. For now it writes the **v27 baseline** project: 4 Auroras, Formant / Chroma, LFO 1 → Osc 1 position, LFO 2 → Osc 2 position at 2 Hz, a 4-bar 6-note chord loop. The scenario variant is added in T043.-- [ ] T004 [P] Add the opt-in UI probe `src/managed/Nota.App/Diagnostics/UiProbe.cs`: `NOTA_UI_PROBE=aurora`, fixed rings of Stopwatch ticks, p50 / p99 to stderr every 10 s, no cost when off. Hook it into the current `src/managed/Nota.App/Controls/AuroraStack.cs` `Render`, and add a "card build → first paint" mark in `src/managed/Nota.App/DeviceChainView.Instruments.cs` (`:120-126`).-- [ ] T005 On the 036 reference machine, record the baselines in `specs/053-aurora-one-card/perf-baseline.md` (format of `specs/036-aurora-perf/baseline-env.md`): `nota_perf run aurora-supersaw-2x 30` twice, plus `pidstat` UI-thread %CPU, paint p99 and card build time with the T003 baseline fixture on the unchanged card (quickstart § 4 step 1).+- [x] T001 Add `tests/Nota.SmokeTest/AuroraTableTests.cs` (SPDX header, empty test groups for conditioning, undo, state, project, preset, rack, scope). Register the `--aurora-tables` mode in `tests/Nota.SmokeTest/Program.cs`, next to `--aurora-null` (`Program.cs:536-551`), and add the group to the full run.+- [x] T002 [P] Add `tests/Nota.SmokeTest/AuroraFixtures.cs` and the `--aurora-fixtures <dir>` mode. It writes the quickstart § 2 files (cycle-2048, table-64x2048 with a `clm ` chunk, table-300x2048, stereo vowel-2s FLAC, long-90s, silence, broken, x.aiff) through `tests/Nota.SmokeTest/WavWriter.cs` and the engine's encoder.+- [x] T003 [P] Add the `--aurora-ui-fixture <dir> [--builtin]` mode in `tests/Nota.SmokeTest/AuroraFixtures.cs`. For now it writes the **v27 baseline** project: 4 Auroras, Formant / Chroma, LFO 1 → Osc 1 position, LFO 2 → Osc 2 position at 2 Hz, a 4-bar 6-note chord loop. The scenario variant is added in T043.+- [x] T004 [P] Add the opt-in UI probe `src/managed/Nota.App/Diagnostics/UiProbe.cs`: `NOTA_UI_PROBE=aurora`, fixed rings of Stopwatch ticks, p50 / p99 to stderr every 10 s, no cost when off. Hook it into the current `src/managed/Nota.App/Controls/AuroraStack.cs` `Render`, and add a "card build → first paint" mark in `src/managed/Nota.App/DeviceChainView.Instruments.cs` (`:120-126`).+- [ ] T005 On the 036 reference machine, record the baselines in `specs/053-aurora-one-card/perf-baseline.md` (format of `specs/036-aurora-perf/baseline-env.md`): `nota_perf run aurora-supersaw-2x 30` twice, plus `pidstat` UI-thread %CPU, paint p99 and card build time with the T003 baseline fixture on the unchanged card (quickstart § 4 step 1). *(Partly done: base numbers taken in a container against the unchanged card, see perf-baseline.md; the reference-machine run is still owed.)***Checkpoint**: baselines recorded. Every later number is compared against them.@@ -49,34 +49,34 @@ taken on the **unchanged** code.**Purpose**: The engine table model, the hand-over to the audio thread, the state blob, theC ABI and interop. US1 does not need this phase and can start right after Phase 1.-- [ ] T006 Create `src/native/nota.engine/src/devices/instruments/AuroraTable.h` and `.cpp` (SPDX header): the immutable `AuroraTable` and `AuroraTableSet` types from data-model.md, with a serial counter. Add the .cpp to `src/native/nota.engine/CMakeLists.txt` (list at `:171`).-- [ ] T007 Implement `AuroraTable::buildFromFile` in `AuroraTable.cpp`:+- [x] T006 Create `src/native/nota.engine/src/devices/instruments/AuroraTable.h` and `.cpp` (SPDX header): the immutable `AuroraTable` and `AuroraTableSet` types from data-model.md, with a serial counter. Add the .cpp to `src/native/nota.engine/CMakeLists.txt` (list at `:171`).+- [x] T007 Implement `AuroraTable::buildFromFile` in `AuroraTable.cpp`:- `decodeAudioFile` (`src/media/AudioFile.cpp:73`), mono mix, the 60 s cap;- classification (a) `clm ` chunk or a multiple of 2048, at most 256 frames, (b) at most4096 samples as one cycle by FFT resample, (c) 16 zero-crossing-aligned windows(research R3);- typed errors (contracts/c-abi.md).-- [ ] T008 Implement conditioning in `AuroraTable.cpp`: DC removal per frame, the 32-sample equal-power seam blend for (c), per-table normalisation to peak 1.0, refusal below −60 dBFS, and `buildFromFrames` (no re-conditioning).-- [ ] T009 Implement mip levels k = 0…5 by FFT truncation with signalsmith-linear `RealFFT` (as in `src/dsp/primitives/SpectrumAnalyzer.h:18`), and the 128-bit content hash of the base level, in `AuroraTable.cpp`.-- [ ] T010 In `src/native/nota.engine/src/devices/instruments/WavetableSynth.h/.cpp`, add:+- [x] T008 Implement conditioning in `AuroraTable.cpp`: DC removal per frame, the 32-sample equal-power seam blend for (c), per-table normalisation to peak 1.0, refusal below −60 dBFS, and `buildFromFrames` (no re-conditioning).+- [x] T009 Implement mip levels k = 0…5 by FFT truncation with signalsmith-linear `RealFFT` (as in `src/dsp/primitives/SpectrumAnalyzer.h:18`), and the 128-bit content hash of the base level, in `AuroraTable.cpp`. *(Done as ten levels with at least 4 samples per cycle; research R13.)*+- [x] T010 In `src/native/nota.engine/src/devices/instruments/WavetableSynth.h/.cpp`, add:- a `SnapshotHistory<const AuroraTableSet>` member and `std::atomic<uint8_t> useCustom_[2]`;- a `RenderScope` in `render()`, and a `live()` read next to the block snapshot (`WavetableSynth.cpp:330-345`);- `clone()` (`:246-252`) sharing the set and flags;- message-thread setters `setTable`, `clearTable`, `setSource`, `setMissing`.-- [ ] T011 In `WavetableSynth.h/.cpp`, add `readMorphSized` and `oscStackCustom`, with the mip pick per voice per block (unison detune and warp bias, research R4). Call it only when `useCustom_` is set and a table is present; leave the built-in `oscStack` / `readMorph` calls at `:497-500` untouched.-- [ ] T012 In `WavetableSynth.cpp`, implement the state trailer v1 in `getState` / `setState` (`:227-244`) per contracts/state-blob.md, with an `includeTables` flag. A blob with no table, flag or missing name stays byte-identical.-- [ ] T013 In `WavetableSynth.h/.cpp`, implement `scopeRead` (5 floats, data-model.md § Scope telemetry, the Keys pattern `Keys.h:199-215`): relaxed atomics written once per block, holding the played position of the most recently started sounding voice.-- [ ] T014 In `src/native/nota.engine/src/engine/Engine.h` and `Engine_Devices.cpp`, add:+- [x] T011 In `WavetableSynth.h/.cpp`, add `readMorphSized` and `oscStackCustom`, with the mip pick per voice per block (unison detune and warp bias, research R4). Call it only when `useCustom_` is set and a table is present; leave the built-in `oscStack` / `readMorph` calls at `:497-500` untouched.+- [x] T012 In `WavetableSynth.cpp`, implement the state trailer v1 in `getState` / `setState` (`:227-244`) per contracts/state-blob.md, with an `includeTables` flag. A blob with no table, flag or missing name stays byte-identical.+- [x] T013 In `WavetableSynth.h/.cpp`, implement `scopeRead` (5 floats, data-model.md § Scope telemetry, the Keys pattern `Keys.h:199-215`): relaxed atomics written once per block, holding the played position of the most recently started sounding voice.+- [x] T014 In `src/native/nota.engine/src/engine/Engine.h` and `Engine_Devices.cpp`, add:- `auroraSetTable` (checkpoint → clone + `republishWithTrack`; otherwise in place through the history), `auroraClearTable`, `auroraSetSource`, `auroraSetMissing`;- `auroraTableInfo`, `auroraTableRead`, `auroraTablePreview`, `auroraState`.Model them on `setRhythmVoiceSample` (`Engine_Devices.cpp:328-343`).-- [ ] T015 Declare the contracts/c-abi.md functions in `src/native/nota.engine/include/nota/nota_engine.h`. Implement the builders in `src/native/nota.engine/src/abi/nota_engine_import.cpp` and the track functions in `src/native/nota.engine/src/abi/nota_engine_track.cpp`.-- [ ] T016 [P] Add managed interop:+- [x] T015 Declare the contracts/c-abi.md functions in `src/native/nota.engine/include/nota/nota_engine.h`. Implement the builders in `src/native/nota.engine/src/abi/nota_engine_import.cpp` and the track functions in `src/native/nota.engine/src/abi/nota_engine_track.cpp`.+- [x] T016 [P] Add managed interop:- `src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs` (`[LibraryImport]`, `NotaAuroraTableInfo` struct);- `NotaEngine.Tracks.cs` wrappers, with a `SafeHandle` for `NotaAuroraTable*`;- `src/managed/Nota.Application/Engine/IAudioEngine.cs` members;- any test fakes that implement `IAudioEngine`.-- [ ] T017 In `tests/Nota.SmokeTest/AuroraTableTests.cs`, add the regression tests: an Aurora with no table gives a byte-identical `getState` (compare against the 156-float layout); a factory preset after the change still passes `--aurora-null` (`AuroraNullTests.cs`).+- [x] T017 In `tests/Nota.SmokeTest/AuroraTableTests.cs`, add the regression tests: an Aurora with no table gives a byte-identical `getState` (compare against the 156-float layout); a factory preset after the change still passes `--aurora-null` (`AuroraNullTests.cs`).**Checkpoint**: the engine can hold, play, save and report a custom table. Built-in sound is bit-identical.@@ -113,42 +113,42 @@ C ABI and interop. US1 does not need this phase and can start right after Phase### Tests for User Story 2 (write first; they fail before the implementation)-- [ ] T025 [P] [US2] In `AuroraTableTests.cs`, add the conditioning tests:+- [x] T025 [P] [US2] In `AuroraTableTests.cs`, add the conditioning tests:- each of rules (a) / (b) / (c) gives the expected frame count, using the T002 fixtures;- the 256-frame clamp and the 60 s cap set their flags;- silence gives `ERR_SILENT`; AIFF / broken files give `ERR_FORMAT` / `ERR_DECODE`;- each frame's mean is below 1e-6; the table peak equals 1.0;- the loop seam jump is at most the median step for (c).-- [ ] T026 [P] [US2] In `AuroraTableTests.cs`, add the undo and source tests: `set_table(checkpoint 1)`, then undo restores the previous table info and redo re-applies it; `clear_table` is one step; `set_source` toggles with no undo entry and keeps the voices active.-- [ ] T027 [P] [US2] In `AuroraTableTests.cs`, add the state tests:+- [x] T026 [P] [US2] In `AuroraTableTests.cs`, add the undo and source tests: `set_table(checkpoint 1)`, then undo restores the previous table info and redo re-applies it; `clear_table` is one step; `set_source` toggles with no undo entry and keeps the voices active.+- [x] T027 [P] [US2] In `AuroraTableTests.cs`, add the state tests:- the trailer round-trips through `getState` / `setState` (contracts/state-blob.md);- a blob without a trailer clears the tables;- an unknown trailer version is ignored;- `clone()`, track duplicate, device copy/paste, and an Instrument Rack chain / Drum Rack pad round trip keep the table (`RackNestingTests.cs` style).-- [ ] T028 [P] [US2] In `AuroraTableTests.cs`, add the render tests: an imported 2048-sample saw cycle and the built-in Analog at frame 0 differ by less than −40 dB at C3 (sanity); with Warp Off at C7 the alias energy of a bright 64-frame table is at most −60 dB relative to the fundamental (FR-011).-- [ ] T029 [P] [US2] In `AuroraTableTests.cs`, add the project tests:+- [x] T028 [P] [US2] In `AuroraTableTests.cs`, add the render tests: an imported 2048-sample saw cycle and the built-in Analog at frame 0 differ by less than −40 dB at C3 (sanity); with Warp Off at C7 the alias energy of a bright 64-frame table is at most −60 dB relative to the fundamental (FR-011).+- [x] T029 [P] [US2] In `AuroraTableTests.cs`, add the project tests:- save, reopen and render bit-identically (SC-007);- two Auroras with the same table give one `samples/<hash>.wav`;- with a deleted sample, the load warns, `table_info.missing` is 1 and the built-in plays;- v27 projects load unchanged and migrate to 28.-- [ ] T030 [P] [US2] In `AuroraTableTests.cs`, add the preset tests: a user preset carries `AuroraTables` and restores the frames exactly; a factory preset clears custom tables; the preset apply is one undo group.+- [x] T030 [P] [US2] In `AuroraTableTests.cs`, add the preset tests: a user preset carries `AuroraTables` and restores the frames exactly; a factory preset clears custom tables; the preset apply is one undo group.### Implementation for User Story 2-- [ ] T031 [US2] Create `src/managed/Nota.Application/Instruments/Aurora/AuroraTableImporter.cs` (SPDX header):+- [x] T031 [US2] Create `src/managed/Nota.Application/Instruments/Aurora/AuroraTableImporter.cs` (SPDX header):- check the extension against `SampleIndex.AudioExtensions` (`src/managed/Nota.Infrastructure/SampleStore/SampleIndex.cs:20-21`);- run `AuroraTableBuild` on a `Task`, then apply on the UI thread with `AuroraSetTable(checkpoint: true)`;- return a typed result (Ok / Shortened / FirstFrames / Unreadable / Format / Silent).-- [ ] T032 [US2] In `AuroraInstrumentCard.cs`, make each column a drop target (`BrowserView.IsAcceptableDrag` / `DroppedItems`, Rhythm pattern `RhythmInstrumentCard.cs:220-235`, ignoring MIDI files and presets). Add an `Import…` file picker filtered to `*.wav;*.flac;*.mp3` (Rhythm `:205-218`, without AIFF / OGG). Both call T031.-- [ ] T033 [US2] In `AuroraInstrumentCard.cs`, extend each type drop-down with the imported table's name (a check mark on the active source, via `AuroraSetSource`), `Remove imported table` (`AuroraClearTable`), and the dimmed built-in value while the imported table is active (FR-010).-- [ ] T034 [US2] In `src/managed/Nota.App/Controls/AuroraTableView.cs`, add the imported source: fetch `AuroraTablePreview` once per (track, osc, serial) into a shared cache; the "n/N" caption; "1 frame"; the drag-over ring and Loading / Error (4 s) / Missing states (contracts/ui-osc-tab.md).-- [ ] T035 [US2] In `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs` (`InstrumentDto` `:316-341`), add `WavetableDto` and `InstrumentDto.Wavetables`. Bump `CurrentFormatVersion` to 28 in `ProjectService.cs:40`, with its doc line, and append the no-op v27→v28 `Migration` in `ProjectMigrations.cs`.-- [ ] T036 [US2] In `ProjectService.cs`, make the save of kind 5 (`:150-153`) store `AuroraState(includeTables: false)`, write each table as float32 `clm ` WAV under `samples/<hash>.wav` via `BundleContent`, and fill `Wavetables` (contracts/persistence.md).-- [ ] T037 [US2] In `ProjectService.cs`, make the load of kind 5 (`:637` area) apply the blob, then for each `WavetableDto` call `nota_file_decode_mono` → `AuroraTableFromFrames` → `AuroraSetTable(checkpoint: false)` → `AuroraSetSource`. On failure, add the warning text from contracts/persistence.md and call `AuroraSetMissing`.-- [ ] T038 [US2] In `src/managed/Nota.Infrastructure/Persistence/BundleContent.cs` and `ProjectHistory.cs`, pin `Wavetables` samples in `PinnedBinaries` / `PruneUnreferenced` so that version history and pruning keep them.-- [ ] T039 [P] [US2] In `src/managed/Nota.Infrastructure/Persistence/PresetModel.cs` and `PresetService.cs`, add `PresetAuroraTable` and `AuroraTables`. Write it in save (`PresetService.cs:62` area) and apply it after the parameters (`:274`, `:313-324` pattern), clearing tables when it is absent.-- [ ] T040 [US2] Add the rack-chain variants (contracts/c-abi.md § Rack chains) in `src/native/nota.engine/src/engine/Engine_Devices.cpp`, `src/abi/nota_engine_rack.cpp`, `nota_engine.h`, and managed interop `NativeMethods.Rack.cs` / `NotaEngine.Rack.cs` / `IAudioEngine.cs`.-- [ ] T041 [US2] In `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs` (proxy engine, `:211`), forward the Aurora table calls to the chain variants, so an Aurora card opened inside a rack can import, switch source and remove.+- [x] T032 [US2] In `AuroraInstrumentCard.cs`, make each column a drop target (`BrowserView.IsAcceptableDrag` / `DroppedItems`, Rhythm pattern `RhythmInstrumentCard.cs:220-235`, ignoring MIDI files and presets). Add an `Import…` file picker filtered to `*.wav;*.flac;*.mp3` (Rhythm `:205-218`, without AIFF / OGG). Both call T031.+- [x] T033 [US2] In `AuroraInstrumentCard.cs`, extend each type drop-down with the imported table's name (a check mark on the active source, via `AuroraSetSource`), `Remove imported table` (`AuroraClearTable`), and the dimmed built-in value while the imported table is active (FR-010).+- [x] T034 [US2] In `src/managed/Nota.App/Controls/AuroraTableView.cs`, add the imported source: fetch `AuroraTablePreview` once per (track, osc, serial) into a shared cache; the "n/N" caption; "1 frame"; the drag-over ring and Loading / Error (4 s) / Missing states (contracts/ui-osc-tab.md).+- [x] T035 [US2] In `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs` (`InstrumentDto` `:316-341`), add `WavetableDto` and `InstrumentDto.Wavetables`. Bump `CurrentFormatVersion` to 28 in `ProjectService.cs:40`, with its doc line, and append the no-op v27→v28 `Migration` in `ProjectMigrations.cs`.+- [x] T036 [US2] In `ProjectService.cs`, make the save of kind 5 (`:150-153`) store `AuroraState(includeTables: false)`, write each table as float32 `clm ` WAV under `samples/<hash>.wav` via `BundleContent`, and fill `Wavetables` (contracts/persistence.md).+- [x] T037 [US2] In `ProjectService.cs`, make the load of kind 5 (`:637` area) apply the blob, then for each `WavetableDto` call `nota_file_decode_mono` → `AuroraTableFromFrames` → `AuroraSetTable(checkpoint: false)` → `AuroraSetSource`. On failure, add the warning text from contracts/persistence.md and call `AuroraSetMissing`.+- [x] T038 [US2] In `src/managed/Nota.Infrastructure/Persistence/BundleContent.cs` and `ProjectHistory.cs`, pin `Wavetables` samples in `PinnedBinaries` / `PruneUnreferenced` so that version history and pruning keep them.+- [x] T039 [P] [US2] In `src/managed/Nota.Infrastructure/Persistence/PresetModel.cs` and `PresetService.cs`, add `PresetAuroraTable` and `AuroraTables`. Write it in save (`PresetService.cs:62` area) and apply it after the parameters (`:274`, `:313-324` pattern), clearing tables when it is absent.+- [ ] T040 [US2] Add the rack-chain variants (contracts/c-abi.md § Rack chains) in `src/native/nota.engine/src/engine/Engine_Devices.cpp`, `src/abi/nota_engine_rack.cpp`, `nota_engine.h`, and managed interop `NativeMethods.Rack.cs` / `NotaEngine.Rack.cs` / `IAudioEngine.cs`. *(Deferred, research R13: racks keep tables via the state blob; import inside a rack is hidden.)*+- [ ] T041 [US2] In `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs` (proxy engine, `:211`), forward the Aurora table calls to the chain variants, so an Aurora card opened inside a rack can import, switch source and remove. *(Deferred with T040.)***Checkpoint**: US2 complete. T025–T030 pass; quickstart § 2 and § 3 pass.@@ -160,11 +160,11 @@ C ABI and interop. US1 does not need this phase and can start right after Phase**Independent Test**: quickstart § 4 and § 5 on the reference machine, compared with the T005 baselines.-- [ ] T042 [P] [US3] In `tests/perf/nota_perf.cpp`, add the `aurora-imported-2x` scenario next to `aurora-supersaw-2x` (`:195`, `:254`): the same load, with both oscillators on generated 256-frame tables.-- [ ] T043 [P] [US3] In `tests/Nota.SmokeTest/AuroraFixtures.cs`, extend `--aurora-ui-fixture` with the v28 scenario project (256-frame generated tables on both oscillators of all 4 Auroras).-- [ ] T044 [US3] Check that no table-view work runs while the device panel is hidden or the window is minimised (FR-018). Gate `RefreshSynthLive` / the probe in `src/managed/Nota.App/DeviceChainView.Instruments.cs` if needed; the probe should show 0 paints (quickstart § 4 step 4).-- [ ] T045 [US3] Run quickstart § 4 and § 5 twice on the reference machine. Record UI-thread %CPU, paint p50 / p99, card build time and `nota_perf` numbers in `specs/053-aurora-one-card/perf-baseline.md`, against T005.-- [ ] T046 [US3] Only if T045 misses a budget: profile (`perf record` on the UI thread, or `dotnet-trace`). Fix in `AuroraTableView.cs` / `AuroraInstrumentCard.cs` (geometry cache, invalidation gate) or in `oscStackCustom`, then re-run T045. The budgets themselves are not loosened.+- [x] T042 [P] [US3] In `tests/perf/nota_perf.cpp`, add the `aurora-imported-2x` scenario next to `aurora-supersaw-2x` (`:195`, `:254`): the same load, with both oscillators on generated 256-frame tables.+- [x] T043 [P] [US3] In `tests/Nota.SmokeTest/AuroraFixtures.cs`, extend `--aurora-ui-fixture` with the v28 scenario project (256-frame generated tables on both oscillators of all 4 Auroras).+- [x] T044 [US3] Check that no table-view work runs while the device panel is hidden or the window is minimised (FR-018). Gate `RefreshSynthLive` / the probe in `src/managed/Nota.App/DeviceChainView.Instruments.cs` if needed; the probe should show 0 paints (quickstart § 4 step 4).+- [ ] T045 [US3] Run quickstart § 4 and § 5 twice on the reference machine. Record UI-thread %CPU, paint p50 / p99, card build time and `nota_perf` numbers in `specs/053-aurora-one-card/perf-baseline.md`, against T005. *(Partly done: container runs in perf-baseline.md, with SC-003/SC-004/SC-006 met there; reference-machine run still owed.)*+- [x] T046 [US3] Only if T045 misses a budget: profile (`perf record` on the UI thread, or `dotnet-trace`). Fix in `AuroraTableView.cs` / `AuroraInstrumentCard.cs` (geometry cache, invalidation gate) or in `oscStackCustom`, then re-run T045. The budgets themselves are not loosened.**Checkpoint**: SC-003 to SC-006 recorded as met.@@ -176,9 +176,9 @@ C ABI and interop. US1 does not need this phase and can start right after Phase**Independent Test**: LFO 1 → Position at 1 Hz with a held note: the lit frame travels once a second. With no note, it rests at the set Position and repaints stop.-- [ ] T047 [P] [US4] In `AuroraTableTests.cs`, add the scope tests: with LFO 1 routed to Position and a held note, `nota_track_instrument_scope` floats [0] / [1] move over 1 s and stay in 0..1; with no voice they are −1; [2] / [3] change on `set_table`.-- [ ] T048 [US4] In `AuroraInstrumentCard.cs`, read the 5-float scope on every tick **before** the `ParamsMoved` gate (`:151-166`). Push the played position to both `AuroraTableView`s (the set Position when −1). Refetch the preview when a serial changes. Leave the readouts and graphs gated as today.-- [ ] T049 [US4] In `AuroraTableView.cs`, use the 64-frame lit grid of the preview for imported tables (built-ins: the 16 frames), and quantise the lit index so repaints happen only on a grid step.+- [x] T047 [P] [US4] In `AuroraTableTests.cs`, add the scope tests: with LFO 1 routed to Position and a held note, `nota_track_instrument_scope` floats [0] / [1] move over 1 s and stay in 0..1; with no voice they are −1; [2] / [3] change on `set_table`.+- [x] T048 [US4] In `AuroraInstrumentCard.cs`, read the 5-float scope on every tick **before** the `ParamsMoved` gate (`:151-166`). Push the played position to both `AuroraTableView`s (the set Position when −1). Refetch the preview when a serial changes. Leave the readouts and graphs gated as today.+- [x] T049 [US4] In `AuroraTableView.cs`, use the 64-frame lit grid of the preview for imported tables (built-ins: the 16 frames), and quantise the lit index so repaints happen only on a grid step.**Checkpoint**: US4 complete. Re-run T045 with live follow active; it is part of the SC-003 scenario.@@ -186,12 +186,12 @@ C ABI and interop. US1 does not need this phase and can start right after Phase## Phase 7: Polish & Cross-Cutting Concerns-- [ ] T050 [P] Add a `CHANGELOG.md` `[Unreleased]` entry: both oscillators on the Osc tab, custom wavetable import (formats, rules, limits), project format 28, and that held notes stop on import.-- [ ] T051 [P] Update `FEATURES.md` with the nota-features skill.-- [ ] T052 [P] Update the user manual (EN + RU) page `instruments/aurora` with the nota-docs skill (`src/managed/Nota.App/NotaDocs.cs:23` lists it).-- [ ] T053 [P] Check that every new file has the two-line SPDX header (`AuroraTable.h/.cpp`, `AuroraTableView.cs`, `AuroraTableImporter.cs`, `UiProbe.cs`, `AuroraFixtures.cs`, `AuroraTableTests.cs`), and that `LICENSES/third-party.md` needs no change (no new dependency).-- [ ] T054 Run `scripts/build-linux.sh` (and `scripts/build.sh` on macOS) and the whole of quickstart.md. Re-check the plan's Constitution Check and the spec's Nota Compliance Checklist.-- [ ] T055 Run `/speckit-converge` until it reports **Converged**.+- [x] T050 [P] Add a `CHANGELOG.md` `[Unreleased]` entry: both oscillators on the Osc tab, custom wavetable import (formats, rules, limits), project format 28, and that held notes stop on import.+- [x] T051 [P] Update `FEATURES.md` with the nota-features skill.+- [ ] T052 [P] Update the user manual (EN + RU) page `instruments/aurora` with the nota-docs skill (`src/managed/Nota.App/NotaDocs.cs:23` lists it). *(Not done here: the manual lives in the sibling nota-docs repo, outside this worktree.)*+- [x] T053 [P] Check that every new file has the two-line SPDX header (`AuroraTable.h/.cpp`, `AuroraTableView.cs`, `AuroraTableImporter.cs`, `UiProbe.cs`, `AuroraFixtures.cs`, `AuroraTableTests.cs`), and that `LICENSES/third-party.md` needs no change (no new dependency).+- [x] T054 Run `scripts/build-linux.sh` (and `scripts/build.sh` on macOS) and the whole of quickstart.md. Re-check the plan's Constitution Check and the spec's Nota Compliance Checklist. *(Linux: `CI=true scripts/build-linux.sh` to SMOKE TEST PASSED and SCAN SCALE PASSED; macOS not run here.)*+- [ ] T055 Run `/speckit-converge` until it reports **Converged**. *(Not run in this pass.)*---diff --git a/src/managed/Nota.App/Controls/AuroraStack.cs b/src/managed/Nota.App/Controls/AuroraStack.csdeleted file mode 100644index d6f790fb..00000000--- a/src/managed/Nota.App/Controls/AuroraStack.cs+++ /dev/null@@ -1,168 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.-//-// Nota Aurora's wavetable window: the 16 single-cycle frames drawn as a skewed 3-D stack,-// the frame Position sits on in bright neutral ink and the rest fading back into the well — "position-// is a place in a stack, not a number". The shapes come from the same additive recipe as-// WavetableSynth::harmAmp (a low harmonic count → representative, not sample-exact).-//-// The recipe is fixed per bank, so all four banks' frames are computed ONCE per process-// and shared by every card: rebuilding them inside Render cost thirty thousand sines and-// a thousand line segments on every one of the thirty ticks a second the device panel-// runs, which is what made switching to an Aurora track stutter. Render now draws each-// frame as a single geometry, and Set only invalidates when the picture actually changes.-// The Osc tab shows two of these at once (specs/053), so the sixteen geometries are also-// kept between paints and rebuilt only when the bank, the size or the inset changes: a-// repaint for a new lit frame is sixteen DrawGeometry calls and nothing else.--using System;-using System.Threading;-using Avalonia;-using Avalonia.Controls;-using Avalonia.Media;--namespace Nota.App;--internal sealed class AuroraStack : Control-{- private const int Banks = 4, Frames = 16, N = 96, HarmMax = 28;-- private static readonly IBrush Lit = NotaPalette.VizInk;- private static readonly IBrush Dim = NotaPalette.TextDisabled;- // Four depth steps from the back of the stack to the front, so the stack reads as- // depth rather than as sixteen equal lines.- private static readonly IBrush[] Depth =- {- NotaPalette.Wash(NotaPalette.VizInk, 0x28), NotaPalette.Wash(NotaPalette.VizInk, 0x40),- NotaPalette.Wash(NotaPalette.VizInk, 0x60), NotaPalette.Wash(NotaPalette.VizInk, 0x88),- };-- private static readonly Pen[] DepthPens = MakePens(Depth);- private static readonly Pen[] DimPens = MakePens(new[] { Dim, Dim, Dim, Dim });- private static readonly Pen HotPen = new(Lit, 1.7, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round);- private static Pen[] MakePens(IBrush[] brushes)- {- var p = new Pen[brushes.Length];- for (int i = 0; i < brushes.Length; i++) p[i] = new Pen(brushes[i], 1, lineJoin: PenLineJoin.Round);- return p;- }-- // [bank][frame][sample] — built on first use, read-only afterwards.- private static readonly double[][][] Shapes = new double[Banks][][];- private static readonly object ShapeLock = new();-- private int _bank = -1, _active = -1;- private bool _dim;-- // The geometry cache: the frames as laid out for (bank, size, inset).- private readonly StreamGeometry?[] _geo = new StreamGeometry?[Frames];- private int _geoBank = -1;- private double _geoW = -1, _geoH = -1, _geoInset = -1;-- /// <summary>Space kept clear at the top of the window for a caption drawn over it.</summary>- public double TopInset { get; set; }-- /// <summary>Greys the whole stack (the oscillator it belongs to is switched off).</summary>- public bool Dimmed- {- get => _dim;- set { if (_dim == value) return; _dim = value; InvalidateVisual(); }- }-- public AuroraStack() { ClipToBounds = true; }-- /// <summary>Point the window at a bank and a position. Only a change of bank or of the- /// frame the position lands on redraws — a knob moving inside one frame does not.</summary>- public void Set(int bank, double pos)- {- int b = Math.Clamp(bank, 0, Banks - 1);- int a = Math.Clamp((int)Math.Round(Math.Clamp(pos, 0, 1) * (Frames - 1)), 0, Frames - 1);- if (b == _bank && a == _active) return;- _bank = b; _active = a;- InvalidateVisual();- }-- private static double HarmAmp(int bank, double t, int n) => bank switch- {- 0 => n == 1 ? 1.0 : t / n,- 1 => (n % 2 == 1) ? (n == 1 ? 1.0 : t / n) : 0.0,- 2 => Math.Exp(-Sq((n - (1 + t * 16.0)) / (2.0 + t * 3.0))) + (n == 1 ? 0.15 : 0.0),- _ => (1.0 / n) * Math.Abs(Math.Cos(Math.PI * n * (0.25 + 0.75 * t))),- };- private static double Sq(double x) => x * x;-- private static double[][] Bank(int bank)- {- var got = Volatile.Read(ref Shapes[bank]);- if (got is not null) return got;- lock (ShapeLock)- {- if (Shapes[bank] is { } already) return already;- var frames = new double[Frames][];- Span<double> amp = stackalloc double[HarmMax + 1];- for (int f = 0; f < Frames; f++)- {- double t = (double)f / (Frames - 1);- // The recipe depends on (bank, frame), not on the sample: evaluate the- // harmonic amplitudes once and only sum the ones that carry anything.- for (int n = 1; n <= HarmMax; n++) amp[n] = HarmAmp(bank, t, n);- var buf = new double[N];- double peak = 1e-6;- for (int j = 0; j < N; j++)- {- double ph = 2 * Math.PI * j / N, acc = 0;- for (int n = 1; n <= HarmMax; n++) if (amp[n] > 1e-4) acc += amp[n] * Math.Sin(n * ph);- buf[j] = acc;- peak = Math.Max(peak, Math.Abs(acc));- }- for (int j = 0; j < N; j++) buf[j] /= peak;- frames[f] = buf;- }- Volatile.Write(ref Shapes[bank], frames);- return frames;- }- }-- public override void Render(DrawingContext ctx)- {- double w = Bounds.Width, h = Bounds.Height;- if (w <= 2 || h <= 2 || _bank < 0) return;- NotaGraph.Window(ctx, new Rect(0, 0, w, h));-- // The stack is skewed up-and-right: frame 0 sits bottom-front, frame 15 top-back,- // sized so every frame's centre ± amplitude stays inside the window.- const double padX = 9, padY = 7;- double top = padY + TopInset;- double waveW = (w - padX * 2) * 0.70, skewX = (w - padX * 2) * 0.30 / (Frames - 1);- double amp = (h - top - padY) * 0.15;- double cyBottom = h - padY - amp, cyTop = top + amp;- if (cyBottom <= cyTop) return;-- var pens = _dim ? DimPens : DepthPens;- var hot = _dim ? DimPens[^1] : HotPen;-- if (_geoBank != _bank || _geoW != w || _geoH != h || _geoInset != TopInset)- {- var frames = Bank(_bank);- for (int f = 0; f < Frames; f++)- {- var buf = frames[f];- double ox = padX + f * skewX;- double cy = cyBottom - (cyBottom - cyTop) * f / (Frames - 1);- var geo = new StreamGeometry();- using (var g = geo.Open())- {- g.BeginFigure(new Point(ox, cy - buf[0] * amp), false);- for (int j = 1; j <= N; j++)- g.LineTo(new Point(ox + (double)j / N * waveW, cy - buf[j % N] * amp));- }- _geo[f] = geo;- }- _geoBank = _bank; _geoW = w; _geoH = h; _geoInset = TopInset;- }-- // Back to front, so a nearer frame overlaps the one behind it.- for (int f = Frames - 1; f >= 0; f--)- ctx.DrawGeometry(null, f == _active ? hot : pens[f * Depth.Length / Frames], _geo[f]!);- }-}diff --git a/src/managed/Nota.App/Controls/AuroraTableView.cs b/src/managed/Nota.App/Controls/AuroraTableView.csnew file mode 100644index 00000000..204542b7--- /dev/null+++ b/src/managed/Nota.App/Controls/AuroraTableView.cs@@ -0,0 +1,314 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Aurora's table window, one per oscillator on the Osc tab (specs/053): the table's+// frames drawn as a skewed 3-D stack, the frame the oscillator plays in bright neutral ink+// and the rest fading back into the well — "position is a place in a stack, not a number".+//+// Two sources. A built-in bank is drawn from the same additive recipe as+// WavetableSynth::harmAmp (a low harmonic count → representative, not sample-exact); the+// recipe is fixed per bank, so all four banks' frames are computed ONCE per process and+// shared by every card. An imported table is drawn from the engine's preview of it (up to+// 16 frames for the stack and a 64-step grid for the lit frame, fetched once per table and+// shared by every window that shows it).+//+// Cost. The device panel ticks thirty times a second and the Osc tab shows two of these, so+// the window and its stack are drawn once into a bitmap at the screen's scale, kept until+// the source, the size, the inset, the dim state or the theme changes; the lit frame's+// geometry is cached per grid step. A repaint is therefore one bitmap and one line, and one+// only happens when the lit step, the source, the dim state or the drop ring changes — a+// knob moving inside one step does not.++using System;+using System.Threading;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Media;+using Avalonia.Media.Imaging;++namespace Nota.App;++internal sealed class AuroraTableView : Control+{+ private const int Banks = 4, Frames = 16, N = 96, HarmMax = 28;++ private static readonly IBrush Lit = NotaPalette.VizInk;+ private static readonly IBrush Dim = NotaPalette.TextDisabled;+ // Four depth steps from the back of the stack to the front, so the stack reads as+ // depth rather than as sixteen equal lines.+ private static readonly IBrush[] Depth =+ {+ NotaPalette.Wash(NotaPalette.VizInk, 0x28), NotaPalette.Wash(NotaPalette.VizInk, 0x40),+ NotaPalette.Wash(NotaPalette.VizInk, 0x60), NotaPalette.Wash(NotaPalette.VizInk, 0x88),+ };++ private static readonly Pen[] DepthPens = MakePens(Depth);+ private static readonly Pen[] DimPens = MakePens(new[] { Dim, Dim, Dim, Dim });+ private static readonly Pen HotPen = new(Lit, 1.7, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round);+ private static Pen[] MakePens(IBrush[] brushes, PenLineJoin join = PenLineJoin.Round)+ {+ var p = new Pen[brushes.Length];+ for (int i = 0; i < brushes.Length; i++) p[i] = new Pen(brushes[i], 1, lineJoin: join);+ return p;+ }++ // [bank][frame][sample] — built on first use, read-only afterwards.+ private static readonly double[][][] Shapes = new double[Banks][][];+ private static readonly object ShapeLock = new();++ private int _bank = -1, _active = -1;+ private bool _dim, _drag;++ // The imported source: a preview of up to 16 stack frames and a 64-step lit grid.+ public sealed record Preview(float[] Data, int Rep, int Grid, int Points, int Frames);+ private Preview? _imp;+ private uint _serial;+ private readonly StreamGeometry?[] _gridGeo = new StreamGeometry?[64];+ private uint _geoSerial;+ private static readonly Pen DragPen = new(NotaPalette.Accent, 1.5);+ // An imported frame's outline zigzags where the frame holds fast cycles; bevel joins+ // stroke it at a fraction of the cost of round ones and look the same at this size.+ private static readonly Pen[] ImpDepthPens = MakePens(Depth, PenLineJoin.Bevel);+ private static readonly Pen[] ImpDimPens = MakePens(new[] { Dim, Dim, Dim, Dim }, PenLineJoin.Bevel);+ private static readonly Pen ImpHotPen = new(Lit, 1.7, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Bevel);++ // Previews by table serial, shared by every window (a serial is never reused).+ private static readonly System.Collections.Generic.Dictionary<uint, Preview> PreviewCache = new();+ private static readonly System.Collections.Generic.Queue<uint> PreviewOrder = new();++ /// <summary>The preview for a table serial, fetched with <paramref name="fetch"/> the first+ /// time any window asks for it.</summary>+ public static Preview? PreviewFor(uint serial, Func<Preview?> fetch)+ {+ if (serial == 0) return null;+ if (PreviewCache.TryGetValue(serial, out var p)) return p;+ p = fetch();+ if (p is null) return null;+ PreviewCache[serial] = p;+ PreviewOrder.Enqueue(serial);+ while (PreviewOrder.Count > 32) PreviewCache.Remove(PreviewOrder.Dequeue());+ return p;+ }++ // The geometry cache: the frames as laid out for (bank, size, inset).+ private readonly StreamGeometry?[] _geo = new StreamGeometry?[Frames];+ private int _geoBank = -1;+ private double _geoW = -1, _geoH = -1, _geoInset = -1;++ /// <summary>Space kept clear at the top of the window for a caption drawn over it.</summary>+ public double TopInset { get; set; }++ /// <summary>Greys the whole stack (the oscillator it belongs to is switched off).</summary>+ public bool Dimmed+ {+ get => _dim;+ set { if (_dim == value) return; _dim = value; InvalidateVisual(); }+ }++ public AuroraTableView() { ClipToBounds = true; }++ /// <summary>The orange inner ring that says a dropped file would land here.</summary>+ public bool DragOver+ {+ get => _drag;+ set { if (_drag == value) return; _drag = value; InvalidateVisual(); }+ }++ /// <summary>Point the window at a built-in bank and a position. Only a change of bank or+ /// of the frame the position lands on redraws — a knob moving inside one frame does not.</summary>+ public void Set(int bank, double pos)+ {+ int b = Math.Clamp(bank, 0, Banks - 1);+ int a = Math.Clamp((int)Math.Round(Math.Clamp(pos, 0, 1) * (Frames - 1)), 0, Frames - 1);+ if (_imp is null && b == _bank && a == _active) return;+ _imp = null; _serial = 0;+ _bank = b; _active = a;+ InvalidateVisual();+ }++ /// <summary>Point the window at an imported table (its serial and preview) and a position,+ /// quantised to the preview's lit grid: only a change of step redraws.</summary>+ public void SetImported(uint serial, Preview preview, double pos)+ {+ int steps = Math.Max(1, preview.Grid);+ int a = Math.Clamp((int)Math.Round(Math.Clamp(pos, 0, 1) * (steps - 1)), 0, steps - 1);+ if (_imp is not null && serial == _serial && a == _active) return;+ _imp = preview; _serial = serial; _active = a;+ InvalidateVisual();+ }++ private static double HarmAmp(int bank, double t, int n) => bank switch+ {+ 0 => n == 1 ? 1.0 : t / n,+ 1 => (n % 2 == 1) ? (n == 1 ? 1.0 : t / n) : 0.0,+ 2 => Math.Exp(-Sq((n - (1 + t * 16.0)) / (2.0 + t * 3.0))) + (n == 1 ? 0.15 : 0.0),+ _ => (1.0 / n) * Math.Abs(Math.Cos(Math.PI * n * (0.25 + 0.75 * t))),+ };+ private static double Sq(double x) => x * x;++ private static double[][] Bank(int bank)+ {+ var got = Volatile.Read(ref Shapes[bank]);+ if (got is not null) return got;+ lock (ShapeLock)+ {+ if (Shapes[bank] is { } already) return already;+ var frames = new double[Frames][];+ Span<double> amp = stackalloc double[HarmMax + 1];+ for (int f = 0; f < Frames; f++)+ {+ double t = (double)f / (Frames - 1);+ // The recipe depends on (bank, frame), not on the sample: evaluate the+ // harmonic amplitudes once and only sum the ones that carry anything.+ for (int n = 1; n <= HarmMax; n++) amp[n] = HarmAmp(bank, t, n);+ var buf = new double[N];+ double peak = 1e-6;+ for (int j = 0; j < N; j++)+ {+ double ph = 2 * Math.PI * j / N, acc = 0;+ for (int n = 1; n <= HarmMax; n++) if (amp[n] > 1e-4) acc += amp[n] * Math.Sin(n * ph);+ buf[j] = acc;+ peak = Math.Max(peak, Math.Abs(acc));+ }+ for (int j = 0; j < N; j++) buf[j] /= peak;+ frames[f] = buf;+ }+ Volatile.Write(ref Shapes[bank], frames);+ return frames;+ }+ }++ // The window and its stack, drawn once (see the header) and the key it was drawn for.+ private RenderTargetBitmap? _bg;+ private (uint Serial, int Bank, double W, double H, double Inset, bool Dim, double Scale, Color Ink) _bgKey;++ public override void Render(DrawingContext ctx)+ {+ long t0 = UiProbe.Start();+ UiProbe.FirstPaint();+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 2 || h <= 2 || (_bank < 0 && _imp is null)) return;+ double scale = TopLevel.GetTopLevel(this)?.RenderScaling ?? 1.0;+ var ink = (Depth[^1] as ISolidColorBrush)?.Color ?? default; // follows the theme+ var key = (_imp is null ? 0u : _serial, _imp is null ? _bank : -1, w, h, TopInset, _dim, scale, ink);+ if (_bg is null || key != _bgKey)+ {+ _bg?.Dispose();+ _bg = new RenderTargetBitmap(new PixelSize((int)Math.Ceiling(w * scale), (int)Math.Ceiling(h * scale)),+ new Vector(96 * scale, 96 * scale));+ using (var bc = _bg.CreateDrawingContext())+ {+ NotaGraph.Window(bc, new Rect(0, 0, w, h));+ if (_imp is { } bimp) RenderImported(bc, bimp, w, h, stack: true);+ else RenderBuiltIn(bc, w, h, stack: true);+ }+ _bgKey = key;+ }+ ctx.DrawImage(_bg, new Rect(0, 0, w, h));+ if (_imp is { } imp) RenderImported(ctx, imp, w, h, stack: false);+ else RenderBuiltIn(ctx, w, h, stack: false);+ if (_drag)+ ctx.DrawRectangle(null, DragPen, new RoundedRect(new Rect(0, 0, w, h).Deflate(1.25), NotaGraph.Radius));+ UiProbe.EndPaint(t0);+ }++ // The stack's layout: skewed up-and-right, frame 0 bottom-front and the last top-back,+ // sized so every frame's centre ± amplitude stays inside the window.+ private readonly record struct Layout(double PadX, double WaveW, double SkewSpan, double Amp, double CyBottom, double CyTop)+ {+ public double Ox(double d) => PadX + d * SkewSpan;+ public double Cy(double d) => CyBottom - (CyBottom - CyTop) * d;+ }++ private Layout? Lay(double w, double h)+ {+ const double padX = 9, padY = 7;+ double top = padY + TopInset;+ double amp = (h - top - padY) * 0.15;+ double cyBottom = h - padY - amp, cyTop = top + amp;+ if (cyBottom <= cyTop) return null;+ return new Layout(padX, (w - padX * 2) * 0.70, (w - padX * 2) * 0.30, amp, cyBottom, cyTop);+ }++ private static StreamGeometry Wave(Layout l, double d, ReadOnlySpan<double> buf, double ampScale = 1)+ {+ double ox = l.Ox(d), cy = l.Cy(d), amp = l.Amp * ampScale;+ int n = buf.Length;+ var geo = new StreamGeometry();+ using (var g = geo.Open())+ {+ g.BeginFigure(new Point(ox, cy - buf[0] * amp), false);+ for (int j = 1; j <= n; j++)+ g.LineTo(new Point(ox + (double)j / n * l.WaveW, cy - buf[j % n] * amp));+ }+ return geo;+ }++ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)+ {+ base.OnDetachedFromVisualTree(e);+ _bg?.Dispose();+ _bg = null;+ }++ // stack: the frames in their depth inks (into the bitmap); otherwise the lit frame alone.+ private void RenderBuiltIn(DrawingContext ctx, double w, double h, bool stack)+ {+ if (Lay(w, h) is not { } l) return;+ var pens = _dim ? DimPens : DepthPens;+ var hot = _dim ? DimPens[^1] : HotPen;+ if (_geoSerial != 0 || _geoBank != _bank || _geoW != w || _geoH != h || _geoInset != TopInset)+ {+ var frames = Bank(_bank);+ for (int f = 0; f < Frames; f++) _geo[f] = Wave(l, (double)f / (Frames - 1), frames[f]);+ _geoBank = _bank; _geoSerial = 0; _geoW = w; _geoH = h; _geoInset = TopInset;+ }+ // Back to front, so a nearer frame overlaps the one behind it; the lit one on top.+ if (stack)+ for (int f = Frames - 1; f >= 0; f--) ctx.DrawGeometry(null, pens[f * Depth.Length / Frames], _geo[f]!);+ else if (_active is >= 0 and < Frames)+ ctx.DrawGeometry(null, hot, _geo[_active]!);+ }++ private void RenderImported(DrawingContext ctx, Preview p, double w, double h, bool stack)+ {+ if (Lay(w, h) is not { } l) return;+ var pens = _dim ? ImpDimPens : ImpDepthPens;+ var hot = _dim ? ImpDimPens[^1] : ImpHotPen;+ int pts = p.Points, rep = Math.Min(p.Rep, Frames);+ ReadOnlySpan<double> Frame(int index)+ {+ var buf = new double[pts];+ for (int j = 0; j < pts; j++) buf[j] = p.Data[index * pts + j];+ return buf;+ }+ if (rep <= 1)+ {+ // One cycle: the cycle itself, front and centre, in the lit ink.+ if (_geoSerial != _serial || _geoW != w || _geoH != h || _geoInset != TopInset)+ {+ var single = new Layout(l.PadX, w - l.PadX * 2, 0, l.Amp, (l.CyBottom + l.CyTop) / 2, (l.CyBottom + l.CyTop) / 2);+ _geo[0] = Wave(single, 0, Frame(0), 2.6);+ Array.Clear(_gridGeo);+ _geoSerial = _serial; _geoBank = -1; _geoW = w; _geoH = h; _geoInset = TopInset;+ }+ if (!stack) ctx.DrawGeometry(null, hot, _geo[0]!);+ return;+ }+ if (_geoSerial != _serial || _geoW != w || _geoH != h || _geoInset != TopInset)+ {+ for (int f = 0; f < rep; f++) _geo[f] = Wave(l, (double)f / (rep - 1), Frame(f));+ Array.Clear(_gridGeo);+ _geoSerial = _serial; _geoBank = -1; _geoW = w; _geoH = h; _geoInset = TopInset;+ }+ if (stack)+ {+ for (int f = rep - 1; f >= 0; f--) ctx.DrawGeometry(null, pens[f * Depth.Length / rep], _geo[f]!);+ return;+ }+ // The lit frame comes from the finer grid, at its own depth in the stack.+ int grid = Math.Max(1, p.Grid), a = Math.Clamp(_active, 0, grid - 1);+ _gridGeo[a] ??= Wave(l, grid > 1 ? (double)a / (grid - 1) : 0, Frame(rep + a));+ ctx.DrawGeometry(null, hot, _gridGeo[a]!);+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Instruments/AuroraInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/AuroraInstrumentCard.csindex 72d81ec0..eff80e33 100644--- a/src/managed/Nota.App/DeviceCards/Instruments/AuroraInstrumentCard.cs+++ b/src/managed/Nota.App/DeviceCards/Instruments/AuroraInstrumentCard.cs@@ -8,7 +8,10 @@// Centre six tabs:// Osc — both oscillators side by side (specs/053), each with its own// table window, table and warp-mode drop-downs, on switch and six-// knobs; the sub and the unison stack share a row under them.+// knobs; the sub and the unison stack share a row under them. Each+// oscillator takes a dropped or picked audio file as its table+// (WAV / FLAC / MP3), and its window follows the position the+// newest sounding voice plays.// Filter — the selected filter's response as a drag pad, with its type,// slope, cutoff, resonance, env / LFO / key amounts and where each// source (Osc 1 / Osc 2 / Sub) is sent.@@ -39,6 +42,7 @@ using Avalonia.Controls;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;+using Avalonia.Platform.Storage;using Nota.Application;using static Nota.App.DeviceCardKit;using Nota.Application.Localization;@@ -51,6 +55,9 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardpublic string Subtitle => "Wavetable";public double CardWidth => 700;+ // The synth's scope (WavetableSynth::kScopeN): live follow and table serials first, the+ // envelope telemetry after them.+ private const int WavetableScopeN = 6;private const double WheelsW = 56, RailW = 186, TabH = 20, StatusH = 18, BodyH = 186;private static readonly string[] TabNames = { "Osc", "Filter", "Env", "LFO", "Mod", "FX" };@@ -130,8 +137,27 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardint tab = 0, railTab = 0, fsel = 0; // Osc · Global · Filter 1// One table window per oscillator: both are on screen together (specs/053).- var stacks = new AuroraStack[2];- for (int o = 0; o < 2; o++) stacks[o] = new AuroraStack { VerticalAlignment = VerticalAlignment.Stretch, MinHeight = 40 };+ var stacks = new AuroraTableView[2];+ for (int o = 0; o < 2; o++) stacks[o] = new AuroraTableView { VerticalAlignment = VerticalAlignment.Stretch, MinHeight = 40 };+ // Imported tables (specs/053): what each oscillator holds, re-read when its serial or+ // its source changes, or a parameter moves (an undo, a preset), plus a passing note (loading, an error, a shortened file) for the caption.+ var tinfo = new AuroraTableInfo[2];+ bool canImport = engine.TryGetAuroraTableInfo(track, 0, out tinfo[0]); // false inside a rack chain+ if (canImport) engine.TryGetAuroraTableInfo(track, 1, out tinfo[1]);+ var knownSerial = new[] { tinfo[0].Serial & 0xFFFFFF, tinfo[1].Serial & 0xFFFFFF };+ var note = new string?[2];+ var noteUntil = new DateTime[2];+ var loading = new bool[2];+ var dragging = new bool[2];+ var capUpdates = new Action?[2];+ var scope = new float[WavetableScopeN];+ bool Imported(int o) => tinfo[o].HasTable && tinfo[o].UseCustom;+ void ReloadInfo(int o)+ {+ if (!canImport) return;+ engine.TryGetAuroraTableInfo(track, o, out tinfo[o]);+ knownSerial[o] = tinfo[o].Serial & 0xFFFFFF;+ }var oscDimmed = new List<Control>[] { new(), new() }; // what an off oscillator greysvar filtGraph = new VoltFilter(engine, track) { VerticalAlignment = VerticalAlignment.Stretch, MinHeight = 60, Spectrum = new FilterSpectrum(engine, track) };var env1 = new VoltEnv(engine, track) { VerticalAlignment = VerticalAlignment.Stretch, MinHeight = 50 };@@ -164,15 +190,45 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardprimed = true;return moved;}+ // Every tick, before the gate: where the newest sounding voice reads each table+ // (the set Position when nothing sounds), and whether a table changed underneath+ // (an undo, a preset). The windows repaint only when their lit step moves.+ void Follow()+ {+ int n = engine.InstrumentScope(track, scope);+ for (int o = 0; o < 2; o++)+ {+ bool stale = n >= 4 && (uint)scope[2 + o] != knownSerial[o]+ || n >= 6 && ((((int)scope[5] >> o) & 1) != 0) != tinfo[o].UseCustom;+ if (canImport && stale) { ReloadInfo(o); capUpdates[o]?.Invoke(); }+ if (note[o] is not null && DateTime.UtcNow > noteUntil[o]) { note[o] = null; capUpdates[o]?.Invoke(); }+ double pos = n >= 2 && scope[o] >= 0 ? scope[o] : G(o == 0 ? "position" : "osc2position");+ if (Imported(o) && AuroraTableView.PreviewFor(tinfo[o].Serial, () => FetchPreview(o)) is { } pv)+ stacks[o].SetImported(tinfo[o].Serial, pv, pos);+ else+ stacks[o].Set(Sel(o == 0 ? "table" : "osc2table", 4), pos);+ }+ }+ AuroraTableView.Preview? FetchPreview(int o)+ {+ int frames = tinfo[o].Frames;+ if (frames <= 0) return null;+ int rep = Math.Min(frames, 16), grid = Math.Min(frames, 64);+ const int points = 96;+ var data = engine.AuroraTablePreview(track, o, rep, grid, points);+ return data.Length == (rep + grid) * points ? new AuroraTableView.Preview(data, rep, grid, points, frames) : null;+ }void Refresh(bool force){- if (!ParamsMoved() && !force) return;+ long t0 = UiProbe.Start();+ Follow();+ if (!ParamsMoved() && !force) { UiProbe.EndTick(t0); return; }+ // A parameter moved underneath (an undo, a preset, another card): the table info+ // may have changed with it, so read it again before the readouts use it.+ for (int o = 0; o < 2; o++) { ReloadInfo(o); capUpdates[o]?.Invoke(); }applyFilter();for (int o = 0; o < 2; o++)- {- stacks[o].Set(Sel(o == 0 ? "table" : "osc2table", 4), G(o == 0 ? "position" : "osc2position"));stacks[o].Dimmed = G(o == 0 ? "osc1on" : "osc2on") < 0.5f;- }env1.Refresh(); env2.Refresh();lfoStrip.Set(Sel("lfo1shape", 4), LfoCycles(0), G("lfo1depth"));// Undim first so the readouts paint over the real colours, not ones saved while the@@ -186,6 +242,7 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardif (G(o == 0 ? "osc1on" : "osc2on") < 0.5f)foreach (var c in oscDimmed[o]) Inactive.Set(c, true, interactive: true);hint.Text = Hint();+ UiProbe.EndTick(t0);}void Touch() => Refresh(true);@@ -470,6 +527,149 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardreturn box;}+ // ---- imported tables (specs/053) ---------------------------------------------+ // A position as the frame it lands on, out of the table the oscillator plays.+ string PosText(int o, float pos)+ {+ if (!Imported(o)) return FrameText(pos);+ int frames = Math.Max(1, tinfo[o].Frames);+ return frames == 1 ? Loc.T("device.aurora.one_frame") : $"{1 + (int)Math.Round(pos * (frames - 1))}/{frames}";+ }+ void Note(int o, string text, double seconds = 4)+ {+ note[o] = text.Length == 0 ? null : text;+ noteUntil[o] = DateTime.UtcNow.AddSeconds(seconds);+ capUpdates[o]?.Invoke();+ }+ async void Import(int o, string path)+ {+ if (!canImport || loading[o]) return;+ loading[o] = true; capUpdates[o]?.Invoke();+ AuroraImportResult r;+ try { r = await AuroraTableImporter.ImportAsync(engine, track, o, path); }+ finally { loading[o] = false; }+ ReloadInfo(o);+ Note(o, r.Message);+ if (r.Loaded) ctx.NotifyChanged();+ Touch();+ }+ async void PickFile(Control anchor, int o)+ {+ if (TopLevel.GetTopLevel(anchor) is not { } top) return;+ var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions+ {+ Title = Loc.F("device.aurora.import_a_wavetable_into_osc", o + 1), AllowMultiple = false,+ FileTypeFilter = new[] { new FilePickerFileType(Loc.T("common.audio")) { Patterns = new[] { "*.wav", "*.flac", "*.mp3" } } },+ });+ if (files.Count > 0 && files[0].TryGetLocalPath() is { } p) Import(o, p);+ }+ void AcceptDrops(Control target, int o)+ {+ if (!canImport) return;+ DragDrop.SetAllowDrop(target, true);+ void Hover(bool on) { dragging[o] = on; stacks[o].DragOver = on; capUpdates[o]?.Invoke(); }+ DragDrop.AddDragOverHandler(target, (_, e) =>+ {+ if (!BrowserView.IsAcceptableDrag(e)) return;+ e.DragEffects = DragDropEffects.Copy; Hover(true); ctx.HideDropGlow(); e.Handled = true;+ });+ DragDrop.AddDragLeaveHandler(target, (_, _) => Hover(false));+ DragDrop.AddDropHandler(target, (_, e) =>+ {+ Hover(false);+ foreach (var it in BrowserView.DroppedItems(e))+ if (it.Kind is not (Nota.Presentation.BrowserItemKind.MidiFile or Nota.Presentation.BrowserItemKind.Preset+ or Nota.Presentation.BrowserItemKind.Project)+ && it.Path is { Length: > 0 } p && AuroraTableImporter.IsSupported(p))+ {+ Import(o, p);+ break;+ }+ e.Handled = true;+ });+ }++ // The table drop-down: the four banks, then (when the oscillator can hold one) the+ // imported table by name, Import… and Remove. While the imported table plays, the+ // bank row it would fall back to is shown greyed (FR-010).+ Control TableDrop(int o, string id, string learn)+ {+ const int n = 4;+ var name = Mono("", TextPrimary, NotaType.RowLabel);+ name.TextTrimming = TextTrimming.CharacterEllipsis;+ var chev = new Glyph(GlyphKind.ChevronDown, 7)+ {+ Foreground = TextTertiary, Margin = new Thickness(4, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center,+ };+ DockPanel.SetDock(chev, Dock.Right);+ var box = new Border+ {+ Height = 16, Width = 74, Background = NotaPalette.Groove, CornerRadius = NotaRadius.Cell,+ Padding = new Thickness(6, 0, 5, 0), Cursor = new Cursor(StandardCursorType.Hand),+ VerticalAlignment = VerticalAlignment.Center,+ Child = new DockPanel { Children = { chev, name } },+ };+ box.BindResource(Border.BoxShadowProperty, "Shadow.Groove");+ void Pick(int iv)+ {+ bool was = Imported(o);+ if (I(id) >= 0) AuroraTableImporter.PickBank(engine, track, o, I(id), id, iv / (float)(n - 1));+ if (was) { ReloadInfo(o); ctx.NotifyChanged(); }+ Touch();+ }+ box.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;+ var fly = new MenuFlyout();+ int cur = Sel(id, n);+ bool imp = Imported(o);+ for (int i = 0; i < n; i++)+ {+ int iv = i;+ var mi = new MenuItem { Header = Banks[i], ToggleType = MenuItemToggleType.Radio, IsChecked = !imp && i == cur };+ if (imp && i == cur) mi.Foreground = TextTertiary; // what it falls back to+ mi.Click += (_, _) => Pick(iv);+ fly.Items.Add(mi);+ }+ if (canImport)+ {+ fly.Items.Add(new Separator());+ if (tinfo[o].HasTable)+ {+ var own = new MenuItem { Header = tinfo[o].Name, ToggleType = MenuItemToggleType.Radio, IsChecked = imp };+ own.Click += (_, _) => { engine.AuroraSetSource(track, o, true, undoable: true); ReloadInfo(o); ctx.NotifyChanged(); Touch(); };+ fly.Items.Add(own);+ }+ var import = new MenuItem { Header = Loc.T("device.aurora.import") };+ import.Click += (_, _) => PickFile(box, o);+ fly.Items.Add(import);+ if (tinfo[o].HasTable)+ {+ fly.Items.Add(new Separator());+ fly.Items.Add(MenuKit.Danger(Loc.T("device.aurora.remove_imported_table"), null,+ () => { engine.AuroraClearTable(track, o); ReloadInfo(o); ctx.NotifyChanged(); Touch(); }));+ }+ }+ fly.ShowAt(box);+ e.Handled = true;+ };+ box.PointerWheelChanged += (wt, e) =>+ {+ if (WheelInput.Step(e, wt ?? box) is not { } st) return;+ e.Handled = true; if (st == 0) return;+ Pick(Math.Clamp(Sel(id, n) - st, 0, n - 1));+ };+ readouts.Add(() =>+ {+ name.Text = Imported(o) ? tinfo[o].Name : Banks[Sel(id, n)];+ ToolTip.SetTip(box, Imported(o)+ ? Loc.F("device.aurora.imported_click_for_the_banks", learn, tinfo[o].Name)+ : learn + Loc.T("device.aurora.click_to_pick_or_import"));+ });+ if (I(id) is var pi and >= 0) MidiLearn.Bind(box, MidiTarget.PluginParam(track, -1, pi), learn);+ return box;+ }+// What steers the position: the strongest matrix route into Position (it moves// both oscillators, so both windows name it).string PosModText()@@ -491,7 +691,7 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardstring posId = o == 0 ? "position" : "osc2position";var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto,Auto"), ColumnSpacing = 5, Height = 18 };- var tableDrop = Drop(tableId, Banks, Loc.F("device.aurora.osc_table", nm), 74);+ var tableDrop = TableDrop(o, tableId, Loc.F("device.aurora.osc_table", nm));var warpDrop = Drop(pre + "warpmode", WarpModes, Loc.F("device.aurora.osc_warp_mode", nm), 52);var headCells = new Control[] { Section(nm), Toggle("", pre + "on", () => G(pre + "on") >= 0.5f ? "on" : "off"), new Panel(), tableDrop, warpDrop };for (int i = 0; i < headCells.Length; i++) { Grid.SetColumn(headCells[i], i); head.Children.Add(headCells[i]); }@@ -502,15 +702,36 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardvar frameCap = Mono("", TextPrimary, NotaType.Axis);var modCap = Mono("", Teal, NotaType.Axis);modCap.HorizontalAlignment = HorizontalAlignment.Right;+ // The caption names the source and its frame, or what is happening to it: a drop+ // about to land, a file loading, why one was refused, a table a project lost.+ void UpdateCap()+ {+ string? state = dragging[o] ? Loc.F("device.aurora.drop_to_load_into", nm)+ : loading[o] ? Loc.T("device.aurora.loading")+ : note[o];+ if (state is null && tinfo[o].Missing && !tinfo[o].HasTable) state = Loc.F("device.aurora.missing", tinfo[o].Name);+ if (state is not null) { bankCap.Text = state; frameCap.Text = ""; return; }+ if (Imported(o))+ {+ bankCap.Text = tinfo[o].Name;+ frameCap.Text = PosText(o, G(posId));+ }+ else+ {+ bankCap.Text = Banks[Sel(tableId, 4)];+ frameCap.Text = FrameText(G(posId));+ }+ }+ capUpdates[o] = UpdateCap;readouts.Add(() =>{- bankCap.Text = Banks[Sel(tableId, 4)];- frameCap.Text = FrameText(G(posId));+ UpdateCap();// Nothing drives Position: say so, greyed, as the single window did.string mod = PosModText();modCap.Text = mod.Length > 0 ? mod : Loc.T("device.aurora.no_modulation");modCap.Foreground = mod.Length > 0 ? Teal : TextDisabled;});+ bankCap.TextTrimming = TextTrimming.CharacterEllipsis;var capRow = new Grid{ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 5,@@ -526,7 +747,7 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardvar knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*,*,*") };var cells = new[]{- PKnob(posId, "Position", nm + " Position", FrameText, 34, 35, Teal), // what the modulators reach for: the modulation mark+ PKnob(posId, "Position", nm + " Position", v => PosText(o, v), 34, 35, Teal), // what the modulators reach for: the modulation markPKnob(o == 0 ? "warp" : "osc2warp", "Warp", nm + " Warp", Pct, 34, 35),PKnob(pre + "level", "Level", nm + " Level", Pct, 34, 35),PKnob(pre + "oct", Loc.T("device.aurora.oct"), nm + " Octave", Oct, 34, 35),@@ -545,6 +766,8 @@ internal sealed class AuroraInstrumentCard : IInstrumentCard// Off: everything but the name and the switch takes the unavailable look (the// stack greys itself through Dimmed).oscDimmed[o].AddRange(new Control[] { tableDrop, warpDrop, capRow, knobs });+ col.Background = Brushes.Transparent; // the whole column takes a dropped file+ AcceptDrops(col, o);return col;}@@ -699,7 +922,7 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardvar envPanel2 = EnvPanel.Build(env2, new EnvPanel.Spec("ENV 2", new[] { "env2attack", "env2decay", "env2sustain", "env2release" },new[] { "env2dcurve", "env2rcurve", "env2exp" }, (0.001, 2.0), (0.002, 3.0), (0.002, 4.0)),P, EnvKnobCell, (id, names) => Chips(id, names), EnvRoute(() => EnvDest(1)), envScale);- EnvPanel.FollowVoice(ctx, 0, () => tab == 2, env1, env2);+ EnvPanel.FollowVoice(ctx, WavetableScopeN, () => tab == 2, env1, env2);var env2Host = new Border{BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1, 0, 0, 0),@@ -1095,7 +1318,7 @@ internal sealed class AuroraInstrumentCard : IInstrumentCardvar rail = SectionBox(railGrid);rail.Width = RailW;- string OscWord(int o) => BankWords[Sel(o == 0 ? "table" : "osc2table", 4)];+ string OscWord(int o) => Imported(o) ? tinfo[o].Name : BankWords[Sel(o == 0 ? "table" : "osc2table", 4)];string FiltPre() => fsel == 0 ? "fil1" : "fil2";string Hint() => tab switchdiff --git a/src/managed/Nota.App/DeviceChainView.Instruments.cs b/src/managed/Nota.App/DeviceChainView.Instruments.csindex 854ad654..6b894cf1 100644--- a/src/managed/Nota.App/DeviceChainView.Instruments.cs+++ b/src/managed/Nota.App/DeviceChainView.Instruments.cs@@ -29,6 +29,7 @@ public sealed partial class DeviceChainViewbool hasParams = _engine.PluginParamCount(_trackId, -1) > 0;var strategy = _instrumentFactory.Resolve(kind, hasParams);var ctx = NewCardContext();+ if (kind == 5) UiProbe.BuildBegin(); // card build → first table paint (specs/053)var body = strategy.Build(ctx);if (!strategy.BodyOnly) return body; // card owns its whole frame (not yet migrated)double width = strategy.WidthFor(_engine, _trackId);diff --git a/src/managed/Nota.App/Diagnostics/UiProbe.cs b/src/managed/Nota.App/Diagnostics/UiProbe.csnew file mode 100644index 00000000..3d4e1d64--- /dev/null+++ b/src/managed/Nota.App/Diagnostics/UiProbe.cs@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// An opt-in timing probe for the UI thread (specs/053 quickstart § 4): with+// NOTA_UI_PROBE=aurora, Nota Aurora's table windows time each paint, the card times each live+// tick, and the device panel times building an instrument card up to its first paint. Every+// ten seconds the p50 / p99 of each go to stderr. Off (the default) each hook is one static+// bool test; nothing is allocated or timed.++using System;+using System.Diagnostics;++namespace Nota.App;++internal static class UiProbe+{+ public static readonly bool On =+ string.Equals(Environment.GetEnvironmentVariable("NOTA_UI_PROBE"), "aurora", StringComparison.OrdinalIgnoreCase);++ private const int Cap = 8192;+ private static readonly long ReportEvery = Stopwatch.Frequency * 10;++ private sealed class Ring+ {+ private readonly long[] _v = new long[Cap];+ private int _n;+ public long Count;+ public void Add(long ticks) { _v[_n++ % Cap] = ticks; Count++; }+ public (double P50, double P99, int N) Take()+ {+ int n = Math.Min(_n, Cap);+ if (n == 0) return (0, 0, 0);+ var s = new long[n];+ Array.Copy(_v, s, n);+ Array.Sort(s);+ _n = 0;+ return (Ms(s[n / 2]), Ms(s[Math.Min(n - 1, (int)(n * 0.99))]), n);+ }+ }++ private static readonly Ring Paints = new(), Ticks = new(), Builds = new();+ private static long _lastReport = Stopwatch.GetTimestamp();+ private static long _buildStart;++ private static double Ms(long ticks) => ticks * 1000.0 / Stopwatch.Frequency;++ /// <summary>A timestamp to hand back to an End call, or 0 when the probe is off.</summary>+ public static long Start() => On ? Stopwatch.GetTimestamp() : 0;++ public static void EndPaint(long t0) { if (On && t0 != 0) { Paints.Add(Stopwatch.GetTimestamp() - t0); MaybeReport(); } }+ public static void EndTick(long t0) { if (On && t0 != 0) { Ticks.Add(Stopwatch.GetTimestamp() - t0); MaybeReport(); } }++ /// <summary>A card build begins; the next table-window paint ends it.</summary>+ public static void BuildBegin() { if (On) _buildStart = Stopwatch.GetTimestamp(); }+ public static void FirstPaint()+ {+ if (!On || _buildStart == 0) return;+ Builds.Add(Stopwatch.GetTimestamp() - _buildStart);+ _buildStart = 0;+ }++ /// <summary>Paints counted since the process started (a hidden panel must add none).</summary>+ public static long PaintCount => Paints.Count;++ private static void MaybeReport()+ {+ long now = Stopwatch.GetTimestamp();+ if (now - _lastReport < ReportEvery) return;+ _lastReport = now;+ Console.Error.WriteLine(Report());+ }++ /// <summary>The figures since the last report, as one line (and resets them).</summary>+ public static string Report()+ {+ var p = Paints.Take(); var t = Ticks.Take(); var b = Builds.Take();+ return $"ui-probe aurora: paint p50 {p.P50:0.000}\u2009ms p99 {p.P99:0.000}\u2009ms (n {p.N}) · "+ + $"tick p50 {t.P50:0.000}\u2009ms p99 {t.P99:0.000}\u2009ms (n {t.N}) · "+ + $"card build→first paint p50 {b.P50:0.0}\u2009ms (n {b.N})";+ }+}diff --git a/src/managed/Nota.App/MainWindow.Freeze.cs b/src/managed/Nota.App/MainWindow.Freeze.csindex 811f2438..c28fc9af 100644--- a/src/managed/Nota.App/MainWindow.Freeze.cs+++ b/src/managed/Nota.App/MainWindow.Freeze.cs@@ -70,8 +70,16 @@ public partial class MainWindowbool inPlace = IsFreezable(trackId) && Engine.IsTrackFrozen(trackId);bool sleeping = LinkForSource(trackId) is { State: LinkState.Frozen };bool dim = inPlace || sleeping;+ // Undim only what this dimmed: a pass over a chain that was never dimmed would wipe+ // the off look its own cards keep (a bypassed device, an oscillator switched off).+ if (!dim && !_chainDimmed) return;+ _chainDimmed = dim;Inactive.Set(_deviceChain, dim);+ // The undim pass also lifts the off looks the cards keep for themselves; rebuilding+ // the cards gives each its own state back.+ if (!dim) _deviceChain.Refresh();}+ private bool _chainDimmed;private void EnsureFreezeMenu(){diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex b3d89933..61b11282 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -245,6 +245,24 @@ public struct NotaMosaicStatuspublic long RamBytes;}+/// <summary>A Nota Aurora custom wavetable, as the engine reports it (specs/053): its frame+/// count (0 = the slot is empty), how the file was read (0 wavetable file, 1 single cycle,+/// 2 recording), whether it was cut to 60 s or 256 frames, and, for a track's slot, the source+/// flag and whether a project could not restore it (then <see cref="Name"/> is the name it had).+/// <see cref="Serial"/> changes whenever the slot's table does; <see cref="Hash"/> is the+/// engine's 128-bit content hash of the frames, as hex.</summary>+public readonly record struct AuroraTableInfo(int Frames, int Origin, bool TruncatedLength, bool TruncatedFrames,+ bool UseCustom, bool Missing, uint Serial, string Hash, string Name)+{+ public bool HasTable => Frames > 0;+}++/// <summary>Results of the Aurora table builders (native NOTA_AURORA_*).</summary>+public static class AuroraTableResult+{+ public const int Ok = 0, ErrDecode = -1, ErrFormat = -2, ErrSilent = -3, ErrEmpty = -4, ErrArgs = -5;+}+/// <summary>Captured session audio take. Matches native NotaSessionAudioSlot (M7-6b).</summary>[StructLayout(LayoutKind.Sequential)]public struct NotaSessionAudioSlotdiff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 054be0fe..6816c0b1 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -480,6 +480,39 @@ public interface IAudioEngine : IDisposablebool TryGetMosaicStatus(int trackId, out NotaMosaicStatus status);/// <summary>The sample id behind a zone (for TryGetSampleInfo / ReadSample), 0 = not loaded.</summary>long MosaicZoneSampleId(int trackId, int zone);+ // ---- Nota Aurora custom wavetables (specs/053) ----+ /// <summary>Decodes a WAV / FLAC / MP3 and builds a conditioned, band-limited table on the+ /// calling thread (any thread: it touches no engine state). Returns an+ /// <see cref="AuroraTableResult"/>; on Ok, <paramref name="table"/> is a handle the caller+ /// frees with <see cref="AuroraTableFree"/>.</summary>+ int AuroraTableBuild(string path, out nint table);+ /// <summary>A table from frames a project or preset saved (2048 floats each): only the mips+ /// are rebuilt, so it plays exactly what was saved.</summary>+ int AuroraTableFromFrames(float[] frames, int frameCount, string name, int origin, out nint table);+ AuroraTableInfo AuroraTableInfoOf(nint table);+ /// <summary>The handle's base frames (2048 × frames floats).</summary>+ float[] AuroraTableFrames(nint table);+ void AuroraTableFree(nint table);+ /// <summary>Puts the table into Aurora oscillator <paramref name="osc"/> (0/1) and plays it.+ /// <paramref name="undoable"/>: one undo step (sounding notes stop); false: in place (a project+ /// load). The engine keeps its own reference. False when the track isn't an Aurora.</summary>+ bool AuroraSetTable(int trackId, int osc, nint table, bool undoable = true);+ /// <summary>Removes the imported table (one undo step).</summary>+ bool AuroraClearTable(int trackId, int osc);+ /// <summary>Imported table (true) or the built-in bank (false). Undoable: one undo step+ /// (the instrument is republished); otherwise in place with no undo (loads).</summary>+ bool AuroraSetSource(int trackId, int osc, bool useCustom, bool undoable = false);+ /// <summary>Marks a table a project named but could not restore ("" clears).</summary>+ bool AuroraSetMissing(int trackId, int osc, string name);+ bool TryGetAuroraTableInfo(int trackId, int osc, out AuroraTableInfo info);+ /// <summary>The slot's base frames, or an empty array.</summary>+ float[] AuroraTableRead(int trackId, int osc);+ /// <summary>A drawing preview: <paramref name="repFrames"/> then <paramref name="gridFrames"/>+ /// evenly chosen frames of <paramref name="points"/> samples each; empty when there is no table.</summary>+ float[] AuroraTablePreview(int trackId, int osc, int repFrames, int gridFrames, int points);+ /// <summary>The Aurora's state blob with or without the table frames (a project save keeps+ /// the tables as sample files beside it).</summary>+ byte[] AuroraState(int trackId, bool includeTables);/// <summary>UI editing channel for the track's instrument (e.g. Rhythm step patterns).</summary>void InstrumentAction(int trackId, int id, int iarg, float farg);/// <summary>Loads a state blob into the track's instrument and records what it changed in thediff --git a/src/managed/Nota.Application/Instruments/Aurora/AuroraTableImporter.cs b/src/managed/Nota.Application/Instruments/Aurora/AuroraTableImporter.csnew file mode 100644index 00000000..71321b67--- /dev/null+++ b/src/managed/Nota.Application/Instruments/Aurora/AuroraTableImporter.cs@@ -0,0 +1,92 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Importing a file as a Nota Aurora wavetable (specs/053): the decode and the table build+// run on a worker (they can take a moment for a long recording), then the table goes into+// the oscillator on the caller's thread as one undo step. The file picker and a drop both+// come here, so each says the same thing about a file it could not use.++using System;+using System.IO;+using System.Threading.Tasks;+using Nota.Application.Localization;++namespace Nota.Application;++public enum AuroraImportOutcome { Ok, Shortened, FirstFrames, Unreadable, Format, Silent, NotAurora }++public readonly record struct AuroraImportResult(AuroraImportOutcome Outcome, AuroraTableInfo Info)+{+ public bool Loaded => Outcome is AuroraImportOutcome.Ok or AuroraImportOutcome.Shortened or AuroraImportOutcome.FirstFrames;++ /// <summary>The one line the card shows; "" for a plain success.</summary>+ public string Message => Outcome switch+ {+ AuroraImportOutcome.Shortened => Loc.T("device.aurora.import_shortened_to_60_s"),+ AuroraImportOutcome.FirstFrames => Loc.T("device.aurora.import_first_256_frames"),+ AuroraImportOutcome.Format => Loc.T("device.aurora.import_couldnt_read_this_file"),+ AuroraImportOutcome.Unreadable => Loc.T("device.aurora.import_couldnt_read_this_file"),+ AuroraImportOutcome.Silent => Loc.T("device.aurora.import_this_file_is_silent"),+ AuroraImportOutcome.NotAurora => Loc.T("device.aurora.import_this_track_has_no"),+ _ => "",+ };+}++public static class AuroraTableImporter+{+ /// <summary>The file types a table can come from.</summary>+ public static readonly string[] Extensions = { ".wav", ".flac", ".mp3" };++ public static bool IsSupported(string path)+ {+ string ext = Path.GetExtension(path ?? "");+ foreach (var e in Extensions) if (string.Equals(ext, e, StringComparison.OrdinalIgnoreCase)) return true;+ return false;+ }++ /// <summary>Builds the table on a worker, then (back on the calling thread) puts it into+ /// oscillator <paramref name="osc"/> of the Aurora on <paramref name="trackId"/> as one undo+ /// step. Call from the UI thread so the hand-over runs there.</summary>+ public static async Task<AuroraImportResult> ImportAsync(IAudioEngine engine, int trackId, int osc, string path)+ {+ if (!IsSupported(path)) return new(AuroraImportOutcome.Format, default);+ var (code, table) = await Task.Run(() =>+ {+ int r = engine.AuroraTableBuild(path, out var h);+ return (r, h);+ });+ if (code != AuroraTableResult.Ok)+ return new(code switch+ {+ AuroraTableResult.ErrSilent => AuroraImportOutcome.Silent,+ AuroraTableResult.ErrFormat => AuroraImportOutcome.Format,+ _ => AuroraImportOutcome.Unreadable,+ }, default);+ try+ {+ var info = engine.AuroraTableInfoOf(table);+ if (!engine.AuroraSetTable(trackId, osc, table, undoable: true)) return new(AuroraImportOutcome.NotAurora, info);+ var outcome = info.TruncatedFrames ? AuroraImportOutcome.FirstFrames+ : info.TruncatedLength ? AuroraImportOutcome.Shortened : AuroraImportOutcome.Ok;+ return new(outcome, info);+ }+ finally { engine.AuroraTableFree(table); }+ }++ /// <summary>Picks built-in bank <paramref name="value"/> (the table parameter+ /// <paramref name="paramId"/> at <paramref name="paramIndex"/>) for oscillator+ /// <paramref name="osc"/>. When the oscillator was playing its imported table, it also goes+ /// back to the bank. The two are one undo step: undo brings back both the old bank and the+ /// imported table.</summary>+ public static void PickBank(IAudioEngine engine, int trackId, int osc, int paramIndex, string paramId, float value)+ {+ engine.BeginAutomationWrite(trackId, AutomationTarget.PluginParam, -1, -1, paramId);+ try+ {+ if (engine.TryGetAuroraTableInfo(trackId, osc, out var info) && info.UseCustom)+ engine.AuroraSetSource(trackId, osc, false, undoable: true);+ engine.PluginParamSet(trackId, -1, paramIndex, value);+ }+ finally { engine.EndAutomationWrite(trackId, AutomationTarget.PluginParam, -1, -1, paramId); }+ }+}diff --git a/src/managed/Nota.Application/Localization/en.json b/src/managed/Nota.Application/Localization/en.jsonindex 6cedfff7..647cae81 100644--- a/src/managed/Nota.Application/Localization/en.json+++ b/src/managed/Nota.Application/Localization/en.json@@ -691,15 +691,29 @@"device.aurora.8_in_use": "{0} / 8 in use","device.aurora.click_for_the_next_macros": "Click for the next macros, right-click for the previous","device.aurora.click_for_the_next_target": "Click for the next target, right-click for the previous",+ "device.aurora.click_to_pick_or_import": " · click to pick or import, scroll to step","device.aurora.click_to_pick_scroll_to_step": " · click to pick, scroll to step","device.aurora.drag_a_cell_up_adds": "drag a cell — up adds, down subtracts · ⌥-click types · double-click clears","device.aurora.drag_to_change_double_click": " · drag to change, double-click to reset",+ "device.aurora.drop_to_load_into": "Drop to load into {0}","device.aurora.fine": "Fine",+ "device.aurora.import": "Import…",+ "device.aurora.import_a_wavetable_into_osc": "Import a wavetable into Osc {0}",+ "device.aurora.import_couldnt_read_this_file": "Couldn't read this file — use WAV, FLAC or MP3",+ "device.aurora.import_first_256_frames": "First 256 frames",+ "device.aurora.import_shortened_to_60_s": "Shortened to 60 s",+ "device.aurora.import_this_file_is_silent": "This file is silent",+ "device.aurora.import_this_track_has_no": "This track has no Aurora",+ "device.aurora.imported_click_for_the_banks": "{0} · imported: {1} · click for the banks, Import… or Remove",+ "device.aurora.loading": "Loading…",+ "device.aurora.missing": "Missing: {0}","device.aurora.no_modulation": "no modulation","device.aurora.oct": "Oct",+ "device.aurora.one_frame": "1 frame","device.aurora.osc_n": "Osc {0}","device.aurora.osc_table": "{0} Table","device.aurora.osc_warp_mode": "{0} Warp mode",+ "device.aurora.remove_imported_table": "Remove imported table","device.aurora.semi": "Semi","device.aurora.shape_lfo": "Shape · LFO {0}","device.aurora.shape_lfo_1_caps": "SHAPE · LFO 1",diff --git a/src/managed/Nota.Infrastructure/Audio/AuroraTableWav.cs b/src/managed/Nota.Infrastructure/Audio/AuroraTableWav.csnew file mode 100644index 00000000..5a1e47a4--- /dev/null+++ b/src/managed/Nota.Infrastructure/Audio/AuroraTableWav.cs@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A Nota Aurora wavetable as a file (specs/053): float32 mono WAV, with the `clm ` chunk+// wavetable editors use to name the frame size (2048), so the file opens as a wavetable+// elsewhere too. Float32 makes the reload exact: the frames come back bit for bit.++using System.IO;++namespace Nota.Infrastructure;++public static class AuroraTableWav+{+ public const int FrameSize = 2048;+ private const int SampleRate = 44100;++ public static void Write(string path, float[] frames)+ {+ using var fs = new FileStream(path, FileMode.Create, FileAccess.Write);+ using var w = new BinaryWriter(fs);+ byte[] clm = System.Text.Encoding.ASCII.GetBytes($"<!>{FrameSize} 00000000 wavetable (Nota)");+ int clmPad = clm.Length & 1;+ int dataBytes = frames.Length * sizeof(float);+ int riff = 4 + (8 + 16) + (8 + clm.Length + clmPad) + (8 + dataBytes);++ w.Write("RIFF"u8.ToArray()); w.Write(riff); w.Write("WAVE"u8.ToArray());+ w.Write("fmt "u8.ToArray()); w.Write(16);+ w.Write((ushort)3); // IEEE float+ w.Write((ushort)1); // mono+ w.Write(SampleRate); w.Write(SampleRate * 4);+ w.Write((ushort)4); w.Write((ushort)32);+ w.Write("clm "u8.ToArray()); w.Write(clm.Length); w.Write(clm);+ if (clmPad != 0) w.Write((byte)0);+ w.Write("data"u8.ToArray()); w.Write(dataBytes);+ var bytes = new byte[dataBytes];+ System.Buffer.BlockCopy(frames, 0, bytes, 0, dataBytes);+ w.Write(bytes);+ }+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.csindex fbbe4308..04cc32b1 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs@@ -527,6 +527,46 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_file_decode_mono", StringMarshalling = StringMarshalling.Utf8)]internal static unsafe partial long FileDecodeMono(string path, double maxSeconds, float* output, long cap, out double sampleRate);+ // ---- Nota Aurora custom wavetables (specs/053) ----+ [LibraryImport(Lib, EntryPoint = "nota_aurora_table_build", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuroraTableBuild(string path, out IntPtr table);++ [LibraryImport(Lib, EntryPoint = "nota_aurora_table_from_frames", StringMarshalling = StringMarshalling.Utf8)]+ internal static unsafe partial int AuroraTableFromFrames(float* frames, int count, string name, int origin, out IntPtr table);++ [LibraryImport(Lib, EntryPoint = "nota_aurora_table_info")]+ internal static partial int AuroraTableInfo(IntPtr table, out NotaAuroraTableInfoRaw info);++ [LibraryImport(Lib, EntryPoint = "nota_aurora_table_frames")]+ internal static unsafe partial long AuroraTableFrames(IntPtr table, float* output, long cap);++ [LibraryImport(Lib, EntryPoint = "nota_aurora_table_free")]+ internal static partial void AuroraTableFree(IntPtr table);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_set_table")]+ internal static partial int AuroraSetTable(IntPtr engine, int trackId, int osc, IntPtr table, int checkpoint);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_clear_table")]+ internal static partial int AuroraClearTable(IntPtr engine, int trackId, int osc);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_set_source")]+ internal static partial int AuroraSetSource(IntPtr engine, int trackId, int osc, int useCustom, int checkpoint);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_set_missing", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int AuroraSetMissing(IntPtr engine, int trackId, int osc, string name);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_table_info")]+ internal static partial int AuroraTrackTableInfo(IntPtr engine, int trackId, int osc, out NotaAuroraTableInfoRaw info);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_table_read")]+ internal static unsafe partial long AuroraTableRead(IntPtr engine, int trackId, int osc, float* output, long cap);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_table_preview")]+ internal static unsafe partial int AuroraTablePreview(IntPtr engine, int trackId, int osc, int repFrames, int gridFrames, int points, float* output, int cap);++ [LibraryImport(Lib, EntryPoint = "nota_track_aurora_state")]+ internal static unsafe partial int AuroraState(IntPtr engine, int trackId, int includeTables, byte* output, int cap);+[LibraryImport(Lib, EntryPoint = "nota_track_instrument_action")]internal static partial void InstrumentAction(IntPtr engine, int trackId, int id, int iarg, float farg);@@ -716,3 +756,19 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_track_sampler_info")]internal static partial int TrackSamplerInfo(IntPtr engine, int trackId, out NotaSamplerInfo info);}++/// <summary>Native NotaAuroraTableInfo (specs/053), turned into+/// <see cref="Nota.Application.AuroraTableInfo"/> by <see cref="NotaEngine"/>.</summary>+[StructLayout(LayoutKind.Sequential)]+internal unsafe struct NotaAuroraTableInfoRaw+{+ public int Frames;+ public int Origin;+ public int TruncatedLength;+ public int TruncatedFrames;+ public int UseCustom;+ public int Missing;+ public uint Serial;+ public fixed byte Hash[16];+ public fixed byte Name[256];+}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.csindex 7097c25b..3cb9dcc1 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs@@ -1096,6 +1096,114 @@ public sealed partial class NotaEnginereturn buf;}+ // --- Nota Aurora custom wavetables (specs/053) ------------------------------++ public int AuroraTableBuild(string path, out nint table)+ {+ table = 0;+ if (string.IsNullOrEmpty(path)) return AuroraTableResult.ErrArgs;+ int r = NativeMethods.AuroraTableBuild(path, out var t);+ table = r == AuroraTableResult.Ok ? t : 0;+ return r;+ }++ public unsafe int AuroraTableFromFrames(float[] frames, int frameCount, string name, int origin, out nint table)+ {+ table = 0;+ if (frames is null || frameCount <= 0 || (long)frameCount * 2048 > frames.LongLength) return AuroraTableResult.ErrArgs;+ int r;+ IntPtr t;+ fixed (float* p = frames) r = NativeMethods.AuroraTableFromFrames(p, frameCount, name ?? "", origin, out t);+ table = r == AuroraTableResult.Ok ? t : 0;+ return r;+ }++ public AuroraTableInfo AuroraTableInfoOf(nint table)+ {+ if (table == 0 || NativeMethods.AuroraTableInfo(table, out var raw) == 0) return default;+ return ToInfo(raw);+ }++ public unsafe float[] AuroraTableFrames(nint table)+ {+ if (table == 0) return [];+ long n = NativeMethods.AuroraTableFrames(table, null, 0);+ if (n <= 0 || n > int.MaxValue) return [];+ var buf = new float[n];+ fixed (float* p = buf) n = NativeMethods.AuroraTableFrames(table, p, buf.LongLength);+ return n == buf.LongLength ? buf : [];+ }++ public void AuroraTableFree(nint table)+ {+ if (table != 0) NativeMethods.AuroraTableFree(table);+ }++ public bool AuroraSetTable(int trackId, int osc, nint table, bool undoable = true)+ { ThrowIfDisposed(); return table != 0 && NativeMethods.AuroraSetTable(_handle, trackId, osc, table, undoable ? 1 : 0) != 0; }++ public bool AuroraClearTable(int trackId, int osc)+ { ThrowIfDisposed(); return NativeMethods.AuroraClearTable(_handle, trackId, osc) != 0; }++ public bool AuroraSetSource(int trackId, int osc, bool useCustom, bool undoable = false)+ { ThrowIfDisposed(); return NativeMethods.AuroraSetSource(_handle, trackId, osc, useCustom ? 1 : 0, undoable ? 1 : 0) != 0; }++ public bool AuroraSetMissing(int trackId, int osc, string name)+ { ThrowIfDisposed(); return NativeMethods.AuroraSetMissing(_handle, trackId, osc, name ?? "") != 0; }++ public bool TryGetAuroraTableInfo(int trackId, int osc, out AuroraTableInfo info)+ {+ ThrowIfDisposed();+ info = default;+ if (NativeMethods.AuroraTrackTableInfo(_handle, trackId, osc, out var raw) == 0) return false;+ info = ToInfo(raw);+ return true;+ }++ public unsafe float[] AuroraTableRead(int trackId, int osc)+ {+ ThrowIfDisposed();+ long n = NativeMethods.AuroraTableRead(_handle, trackId, osc, null, 0);+ if (n <= 0 || n > int.MaxValue) return [];+ var buf = new float[n];+ fixed (float* p = buf) n = NativeMethods.AuroraTableRead(_handle, trackId, osc, p, buf.LongLength);+ return n == buf.LongLength ? buf : [];+ }++ public unsafe float[] AuroraTablePreview(int trackId, int osc, int repFrames, int gridFrames, int points)+ {+ ThrowIfDisposed();+ int n = NativeMethods.AuroraTablePreview(_handle, trackId, osc, repFrames, gridFrames, points, null, 0);+ if (n <= 0) return [];+ var buf = new float[n];+ fixed (float* p = buf) n = NativeMethods.AuroraTablePreview(_handle, trackId, osc, repFrames, gridFrames, points, p, buf.Length);+ return n == buf.Length ? buf : [];+ }++ public unsafe byte[] AuroraState(int trackId, bool includeTables)+ {+ ThrowIfDisposed();+ int n = NativeMethods.AuroraState(_handle, trackId, includeTables ? 1 : 0, null, 0);+ if (n <= 0) return [];+ var buf = new byte[n];+ fixed (byte* p = buf) n = NativeMethods.AuroraState(_handle, trackId, includeTables ? 1 : 0, p, buf.Length);+ return n == buf.Length ? buf : [];+ }++ private static unsafe AuroraTableInfo ToInfo(in NotaAuroraTableInfoRaw raw)+ {+ string hash, name;+ fixed (byte* h = raw.Hash) hash = Convert.ToHexString(new ReadOnlySpan<byte>(h, 16)).ToLowerInvariant();+ fixed (byte* n = raw.Name)+ {+ int len = 0;+ while (len < 255 && n[len] != 0) len++;+ name = System.Text.Encoding.UTF8.GetString(n, len);+ }+ return new AuroraTableInfo(raw.Frames, raw.Origin, raw.TruncatedLength != 0, raw.TruncatedFrames != 0,+ raw.UseCustom != 0, raw.Missing != 0, raw.Serial, hash, name);+ }+/// <summary>UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns).</summary>public void InstrumentAction(int trackId, int id, int iarg, float farg){ ThrowIfDisposed(); NativeMethods.InstrumentAction(_handle, trackId, id, iarg, farg); }diff --git a/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs b/src/managed/Nota.Infrastructure/Persistence/BundleContent.csindex 42bee241..5a8095a4 100644--- a/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs+++ b/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs@@ -92,7 +92,8 @@ internal static partial class BundleContentpublic static void PruneUnreferenced(string bundleDir, ProjectDocument doc){if (ProjectHistory.PinnedBinaries(bundleDir) is not { } pinned) return;- bool Keep(string rel) => doc.SampleRefs.ContainsKey(rel) || doc.StateBlobs.ContainsKey(rel) || pinned.Contains(rel);+ bool Keep(string rel) => doc.SampleRefs.ContainsKey(rel) || doc.TableRefs.ContainsKey(rel) || doc.StateBlobs.ContainsKey(rel)+ || pinned.Contains(rel);foreach (var relDir in new[] { SamplesDir, StatesDir }){string dir = Path.Combine(bundleDir, relDir);diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs b/src/managed/Nota.Infrastructure/Persistence/PresetModel.csindex e50162f8..f4dada09 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetModel.cs@@ -48,6 +48,12 @@ public sealed class PresetDocument[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]public string? MosaicProgram { get; set; }+ /// <summary>Nota Aurora: the imported wavetables (specs/053), one entry per oscillator that+ /// holds one. Null = none: applying the preset puts both oscillators back on their built-in+ /// tables (every factory preset).</summary>+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]+ public System.Collections.Generic.List<PresetAuroraTable>? AuroraTables { get; set; }+/// <summary>Nota EQ-8: the user's band labels and notes (specs/049), one entry per annotated/// band. Null = none (a factory preset, or one saved before labels existed).</summary>[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]@@ -68,3 +74,15 @@ public sealed class PresetBandTextpublic string Label { get; set; } = "";public string Note { get; set; } = "";}++/// <summary>One Nota Aurora oscillator's imported table in a preset (specs/053): the frames as+/// base64 of little-endian float32 (2048 per frame), and whether the oscillator plays it.</summary>+public sealed class PresetAuroraTable+{+ public int Osc { get; set; }+ public string Name { get; set; } = "";+ public int Origin { get; set; }+ public int Frames { get; set; }+ public bool UseCustom { get; set; } = true;+ public string Data { get; set; } = "";+}diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.csindex 96288525..2951ff5d 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs@@ -61,6 +61,8 @@ public static class PresetService}// Nota Mosaic: the zone map travels with the sound (its samples stay referenced).if (ik == MosaicModel.Kind && engine.MosaicProgram(trackId) is { Length: > 0 } prog) doc.MosaicProgram = prog;+ // Nota Aurora: its imported tables travel with the sound (specs/053).+ if (ik == 5) doc.AuroraTables = CaptureAuroraTables(engine, trackId);// Nota Twin: its sequencer patterns travel with the sound (a params-free state blob).if (ik == Nota.Application.Twin.TwinMatrix.Kind && Nota.Application.Twin.TwinPatterns.FromState(engine.GetPluginState(trackId, -1)) is { } pats)doc.StateBase64 = Convert.ToBase64String(Nota.Application.Twin.TwinPatterns.StateWithPatterns(pats));@@ -293,6 +295,7 @@ public static class PresetServiceengine.PluginParamSet(t, -1, i, v);}LoadTwinPatterns(doc, engine, t);+ if (doc.BuiltinKind == 5) return LoadAuroraTables(doc, engine, t, undoable: false);string mw = LoadMosaicProgram(doc, engine, t);return mw.Length > 0 ? mw : LoadGrainSource(doc, engine, t);}@@ -330,6 +333,81 @@ public static class PresetServicereturn engine.SetTrackGrainSample(trackId, path, src.Root) ? "" : Loc.F("persistence.preset.couldnt_load_the_sample", src.Name);}+ // A built-in instrument's parameters in place: the named ones, every other one back to its+ // default (the card size excepted). The Aurora path above shares it.+ private static void ApplyInstrumentParams(PresetDocument doc, IAudioEngine engine, int trackId)+ {+ int pc = engine.PluginParamCount(trackId, -1);+ for (int i = 0; i < pc; i++)+ {+ string id = engine.PluginParamId(trackId, -1, i);+ if (InstrumentView.IsViewParam(id)) continue;+ bool named = doc.NamedParams is { Count: > 0 } && doc.NamedParams.ContainsKey(id);+ engine.PluginParamSet(trackId, -1, i, named ? doc.NamedParams![id] : engine.InstrumentParamDefault(trackId, i));+ }+ }++ // Nota Aurora's imported tables into a preset: the frames, as base64 float32.+ private static List<PresetAuroraTable>? CaptureAuroraTables(IAudioEngine engine, int trackId)+ {+ List<PresetAuroraTable>? list = null;+ for (int o = 0; o < 2; o++)+ {+ if (!engine.TryGetAuroraTableInfo(trackId, o, out var info) || !info.HasTable) continue;+ var frames = engine.AuroraTableRead(trackId, o);+ if (frames.Length == 0) continue;+ var bytes = new byte[frames.Length * sizeof(float)];+ Buffer.BlockCopy(frames, 0, bytes, 0, bytes.Length);+ (list ??= new()).Add(new PresetAuroraTable+ {+ Osc = o, Name = info.Name, Origin = info.Origin, Frames = info.Frames, UseCustom = info.UseCustom,+ Data = Convert.ToBase64String(bytes),+ });+ }+ return list;+ }++ // A Nota Aurora preset sets exactly its tables: the ones it carries, and the built-in bank+ // on every oscillator it does not name (so a factory preset clears an imported table).+ private static string LoadAuroraTables(PresetDocument doc, IAudioEngine engine, int trackId, bool undoable)+ {+ string warn = "";+ for (int o = 0; o < 2; o++)+ {+ var entry = doc.AuroraTables?.Find(x => x.Osc == o);+ if (entry is null)+ {+ if (engine.TryGetAuroraTableInfo(trackId, o, out var cur))+ {+ if (cur.HasTable) engine.AuroraClearTable(trackId, o);+ else if (cur.Missing) engine.AuroraSetMissing(trackId, o, "");+ if (cur.UseCustom) engine.AuroraSetSource(trackId, o, false, undoable && !cur.HasTable);+ }+ continue;+ }+ float[]? frames = null;+ try+ {+ var bytes = Convert.FromBase64String(entry.Data);+ if (entry.Frames is > 0 and <= 256 && bytes.Length == entry.Frames * 2048 * sizeof(float))+ {+ frames = new float[bytes.Length / sizeof(float)];+ Buffer.BlockCopy(bytes, 0, frames, 0, bytes.Length);+ }+ }+ catch (FormatException) { }+ if (frames is null || engine.AuroraTableFromFrames(frames, entry.Frames, entry.Name, entry.Origin, out var h) != AuroraTableResult.Ok)+ {+ warn = $"The preset's Osc {o + 1} table \"{entry.Name}\" couldn't be read.";+ continue;+ }+ try { engine.AuroraSetTable(trackId, o, h, undoable); }+ finally { engine.AuroraTableFree(h); }+ engine.AuroraSetSource(trackId, o, entry.UseCustom);+ }+ return warn;+ }+// A Nota Mosaic preset loads its program: a factory multisample (rendered on first use) or// the program text it carries. Loading itself runs in the background in the engine.private static string LoadMosaicProgram(PresetDocument doc, IAudioEngine engine, int trackId)@@ -424,6 +502,18 @@ public static class PresetServiceif (trackId <= 0) return Loc.T("common.select_a_track_first");switch (doc.Type){+ case "builtin-instrument" when engine.TrackInstrumentKind(trackId) == 5:+ {+ // Nota Aurora: the parameters and the imported tables are one undo step.+ engine.BeginUndoGroup();+ try+ {+ var parms = new PresetDocument { Type = "builtin-instrument-params", NamedParams = doc.NamedParams };+ ApplyInstrumentParams(parms, engine, trackId);+ return LoadAuroraTables(doc, engine, trackId, undoable: true);+ }+ finally { engine.EndUndoGroup(); }+ }case "builtin-instrument":{int pc = engine.PluginParamCount(trackId, -1);diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.csindex 6fcbe7a6..b78292b7 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs@@ -122,6 +122,9 @@ public static class ProjectMigrations// v29 -> v30: tracks gain MidiOffsetMs (MIDI playback offset) and ArticulationMap, notes gain// Articulation (an id in that map, specs/085). Absent in v29 documents = 0 / none — no-op.new Migration(29, _ => { }),+ // v30 -> v31: Nota Aurora instruments gain Wavetables, their imported tables+ // (specs/053). Absent in v30 documents; null = the built-in tables — no-op.+ new Migration(30, _ => { }),};/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex 2d2bdba3..7a27a7ab 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -52,6 +52,11 @@ public sealed class ProjectDocument/// Capture, written to <c>plugin-states/</c> by Save; not serialized.</summary>[JsonIgnore] public Dictionary<string, byte[]> StateBlobs { get; } = new();+ /// <summary>Nota Aurora custom wavetables (format v29, specs/053): relative bundle path+ /// -> the table's frames (2048 floats each). Populated by Capture, written to+ /// <c>samples/</c> as float32 WAV by Save; not serialized.</summary>+ [JsonIgnore] public Dictionary<string, float[]> TableRefs { get; } = new();+/// <summary>Name binaries by live id / position (<c>sample-N.wav</c>, <c>state-N.bin</c>)/// instead of by content hash. Cheap — nothing is read or hashed — but only stable within/// a session, so it is for change detection (<see cref="ProjectService.Capture"/> with@@ -362,6 +367,9 @@ public sealed class InstrumentDtopublic bool Folded { get; set; }/// <summary>Nota Rhythm (Kind == 12) per-voice one-shots (only sample-source voices).</summary>public List<VoiceSampleDto>? VoiceSamples { get; set; }+ /// <summary>Nota Aurora (Kind == 5) imported wavetables, one per oscillator that holds one+ /// (format v29, specs/053); null = none.</summary>+ public List<WavetableDto>? Wavetables { get; set; }/// <summary>The card's on/off switch is off: the instrument makes no sound (#148).</summary>public bool Bypassed { get; set; }@@ -370,6 +378,22 @@ public sealed class InstrumentDto/// <summary>One drum voice's sample for Nota Rhythm: the voice index + a bundle-relative/// path into <c>samples/</c>.</summary>+/// <summary>One Nota Aurora oscillator's imported wavetable (format v29, specs/053): its frames+/// as a float32 WAV in <c>samples/</c> (a <c>clm </c> chunk names the 2048-sample frame), the+/// name it was imported as, how the file was read (0 wavetable file, 1 single cycle,+/// 2 recording) and whether the oscillator plays it. <see cref="Missing"/>: the table could not+/// be restored when the project was last opened; <see cref="Sample"/> is empty then.</summary>+public sealed class WavetableDto+{+ public int Osc { get; set; }+ public string Sample { get; set; } = "";+ public string Name { get; set; } = "";+ public int Origin { get; set; }+ public int Frames { get; set; }+ public bool UseCustom { get; set; } = true;+ public bool Missing { get; set; }+}+public sealed class VoiceSampleDto{public int Voice { get; set; }diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex 08bbd351..ef5da3f7 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -37,9 +37,11 @@ public sealed class ProjectService/// chain children's sidechain keys / CC targets./// v26 (specs/048) adds Preset on instruments, devices and MIDI effects./// v27 (specs/046) adds Preview on hosted plug-ins: the picture of their window.+ /// v28 (specs/050) lets a sidechain key name one pad, chain or voice of its source./// v29 (specs/067) adds Takes on audio tracks and TakeId on audio clips./// v30 (specs/085) adds MidiOffsetMs and ArticulationMap on tracks and Articulation on notes.- public const int CurrentFormatVersion = 30;+ /// v31 (specs/053) adds Wavetables on Nota Aurora: its imported tables, as samples.+ public const int CurrentFormatVersion = 31;/// <summary>Manifest file name inside the bundle folder.</summary>public const string ManifestName = "project.json";@@ -162,7 +164,12 @@ public sealed class ProjectServiceinstDto.State = RegisterBlob(doc, engine.GetPluginState(ti.Id, -1));}}- else // every other built-in instrument (Synth/Physical/Aurora/Volt/Instrument+ else if (kind == 5) // Nota Aurora: the blob without its tables, which go to samples/+ {+ instDto.State = RegisterBlob(doc, engine.AuroraState(ti.Id, includeTables: false));+ instDto.Wavetables = CaptureWavetables(doc, engine, ti.Id);+ }+ else // every other built-in instrument (Synth/Physical/Volt/Instrument{ // Rack/Drum Rack/Flux) persists its state blob — the load path rebuilds from it.instDto.State = RegisterBlob(doc, engine.GetPluginState(ti.Id, -1));}@@ -704,6 +711,9 @@ public sealed class ProjectServicevar blob = ReadBlob(bundleDir, synthState);if (blob.Length > 0) engine.SetPluginState(id, -1, blob);}+ // Nota Aurora: its imported tables, from samples/ (specs/053).+ if (id > 0 && t.Instrument is { Kind: 5, Wavetables: { } wts })+ RestoreWavetables(engine, id, bundleDir, wts, warnings, newTrackIds.Count + 1);// Nota Rhythm Phase 2: reload each voice's one-shot from the bundle.if (id > 0 && t.Instrument is { Kind: 12, VoiceSamples: { } vsl })foreach (var vs in vsl)@@ -1074,6 +1084,17 @@ public sealed class ProjectServiceWriteSampleWav(engine, kv.Value, ResolveInBundle(bundleDir, kv.Key));}+ if (doc.TableRefs.Count > 0)+ {+ Directory.CreateDirectory(Path.Combine(bundleDir, BundleContent.SamplesDir));+ foreach (var kv in doc.TableRefs)+ {+ string path = ResolveInBundle(bundleDir, kv.Key);+ if (File.Exists(path) && new FileInfo(path).Length >= kv.Value.Length * sizeof(float)) continue;+ BundleContent.WriteAtomic(path, tmp => AuroraTableWav.Write(tmp, kv.Value));+ }+ }+if (doc.StateBlobs.Count > 0){Directory.CreateDirectory(Path.Combine(bundleDir, BundleContent.StatesDir));@@ -1178,6 +1199,68 @@ public sealed class ProjectServicereturn rel;}+ // Nota Aurora's imported tables (specs/053): each one a content-named float32 WAV, so two+ // Auroras with the same table share one file. A table a project could not restore stays+ // listed as missing, so the next save keeps its name.+ private static List<WavetableDto>? CaptureWavetables(ProjectDocument doc, IAudioEngine engine, int trackId)+ {+ List<WavetableDto>? list = null;+ for (int o = 0; o < 2; o++)+ {+ if (!engine.TryGetAuroraTableInfo(trackId, o, out var info)) return null;+ if (info.HasTable)+ {+ string rel;+ if (doc.SessionNames) rel = $"{BundleContent.SamplesDir}/table-{trackId}-{o}-{info.Serial}.wav";+ else+ {+ var frames = engine.AuroraTableRead(trackId, o);+ if (frames.Length == 0) continue;+ var bytes = new byte[frames.Length * sizeof(float)];+ Buffer.BlockCopy(frames, 0, bytes, 0, bytes.Length);+ rel = BundleContent.SampleRel(BundleContent.BlobHash(bytes));+ doc.TableRefs.TryAdd(rel, frames);+ }+ (list ??= new()).Add(new WavetableDto+ {+ Osc = o, Sample = rel, Name = info.Name, Origin = info.Origin, Frames = info.Frames,+ UseCustom = info.UseCustom,+ });+ }+ else if (info.Missing)+ (list ??= new()).Add(new WavetableDto { Osc = o, Name = info.Name, Missing = true, UseCustom = false });+ }+ return list;+ }++ // Puts each saved table back (no undo step: this is a load). A table that cannot be read+ // leaves its oscillator on the built-in bank, marked missing under the name it had.+ private static void RestoreWavetables(IAudioEngine engine, int id, string bundleDir, List<WavetableDto> tables,+ List<string> warnings, int trackNo)+ {+ foreach (var w in tables)+ {+ if (w.Osc is < 0 or > 1) continue;+ bool ok = false;+ if (!w.Missing && w.Sample.Length > 0 && w.Frames is > 0 and <= 256)+ {+ string path = ResolveInBundle(bundleDir, w.Sample);+ float[]? mono = File.Exists(path) ? NotaEngine.DecodeMono(path, 60.0, out _) : null;+ if (mono is not null && mono.Length == w.Frames * 2048+ && engine.AuroraTableFromFrames(mono, w.Frames, w.Name, w.Origin, out var h) == AuroraTableResult.Ok)+ {+ try { ok = engine.AuroraSetTable(id, w.Osc, h, undoable: false); }+ finally { engine.AuroraTableFree(h); }+ if (ok) engine.AuroraSetSource(id, w.Osc, w.UseCustom);+ }+ }+ if (ok) continue;+ warnings.Add($"Track {trackNo}: Aurora Osc {w.Osc + 1} table \"{w.Name}\" is missing — it plays its built-in table.");+ engine.AuroraSetMissing(id, w.Osc, w.Name.Length > 0 ? w.Name : "table");+ engine.AuroraSetSource(id, w.Osc, false);+ }+ }+// A saved track's hardware input (specs/086): the device channel + width, or — in files// saved before 0.60 — the old three-value pick (absent before 0.58: the stereo pair).internal static InputPick TrackInputOf(TrackDto t)diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex 6dff4491..af8a6ca6 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -176,6 +176,7 @@ set(NOTA_ENGINE_SOURCESsrc/devices/instruments/Pentad.cppsrc/devices/instruments/Consort.cppsrc/devices/instruments/WavetableSynth.cpp+ src/devices/instruments/AuroraTable.cppsrc/devices/instruments/OperatorSynth.cppsrc/devices/instruments/FluxSynth.cppsrc/devices/instruments/PendulumSynth.cppdiff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex c0da8b41..0cc5adcb 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -796,6 +796,73 @@ NOTA_API void nota_path_root_set(const char* name_utf8, const char* path_utf8* frames; out may be null to ask). Returns the frames decoded (≤ cap when out is given),* 0 on failure; *sample_rate gets the file's rate. */NOTA_API int64_t nota_file_decode_mono(const char* path_utf8, double max_seconds, float* out, int64_t cap, double* sample_rate);+/* Nota Aurora custom wavetables (specs/053). A table is built from a file, or from frames a+ * project or preset saved, on any thread (the builders touch no engine state), then handed to+ * an oscillator of an Aurora track on the message thread. The engine keeps its own reference;+ * the caller frees its handle. */+typedef struct NotaAuroraTable NotaAuroraTable; /* opaque, immutable once built */+typedef struct NotaAuroraTableInfo {+ int32_t frames; /* 1..256; 0 = no table in that slot */+ int32_t origin; /* 0 wavetable file, 1 single cycle, 2 recording */+ int32_t truncated_length; /* 1 = only the first 60 s were read */+ int32_t truncated_frames; /* 1 = frames beyond 256 were dropped */+ int32_t use_custom; /* track queries only: the source flag */+ int32_t missing; /* track queries only: 1 = a restore failed; name holds it */+ uint32_t serial; /* changes whenever the slot's table changes; 0 = none */+ uint8_t hash[16]; /* content hash of the base frames */+ char name[256]; /* UTF-8, NUL-terminated */+} NotaAuroraTableInfo;+enum {+ NOTA_AURORA_OK = 0,+ NOTA_AURORA_ERR_DECODE = -1, /* unreadable or broken file */+ NOTA_AURORA_ERR_FORMAT = -2, /* not WAV / FLAC / MP3 */+ NOTA_AURORA_ERR_SILENT = -3, /* peak below -60 dBFS */+ NOTA_AURORA_ERR_EMPTY = -4,+ NOTA_AURORA_ERR_ARGS = -5+};+/* Decode a file and build a conditioned, band-limited table. *out gets a new handle. */+NOTA_API int32_t nota_aurora_table_build(const char* path_utf8, NotaAuroraTable** out);+/* From already-conditioned frames (2048 floats each): only the mips are rebuilt, so a reload+ * plays exactly what was saved. */+NOTA_API int32_t nota_aurora_table_from_frames(const float* frames, int32_t frame_count, const char* name_utf8,+ int32_t origin, NotaAuroraTable** out);+NOTA_API int32_t nota_aurora_table_info(const NotaAuroraTable* table, NotaAuroraTableInfo* out);+/* The base frames (2048 × frames floats) into out; returns floats written, or the count when out is null. */+NOTA_API int64_t nota_aurora_table_frames(const NotaAuroraTable* table, float* out, int64_t cap);+NOTA_API void nota_aurora_table_free(NotaAuroraTable* table);+/* Put the table into oscillator osc (0/1) and make it the active source. checkpoint 1 = one+ * undo step (the instrument is republished; sounding notes stop), 0 = in place, no undo (a+ * project load). Returns 1, or 0 when the track is not an Aurora or osc is out of range. */+NOTA_API int32_t nota_track_aurora_set_table(NotaEngine* engine, int32_t track_id, int32_t osc,+ const NotaAuroraTable* table, int32_t checkpoint);+/* Remove the imported table from osc (one undo step); it plays its built-in bank again. */+NOTA_API int32_t nota_track_aurora_clear_table(NotaEngine* engine, int32_t track_id, int32_t osc);+/* 1 = play the imported table, 0 = the built-in bank. checkpoint 1 = one undo step (the+ * instrument is republished, as for set_table; no step when nothing changes), 0 = in place,+ * lock-free, no undo (a project or preset load). Inside an unlatched parameter gesture the+ * parameter's value step merges into it, so a bank pick that leaves the imported table+ * undoes as one step. */+NOTA_API int32_t nota_track_aurora_set_source(NotaEngine* engine, int32_t track_id, int32_t osc, int32_t use_custom,+ int32_t checkpoint);+/* Mark osc as missing a table a project named ("" clears). No undo. */+NOTA_API int32_t nota_track_aurora_set_missing(NotaEngine* engine, int32_t track_id, int32_t osc, const char* name_utf8);+/* 1 and *out filled (frames 0 when the slot is empty), 0 when the track is not an Aurora. */+NOTA_API int32_t nota_track_aurora_table_info(const NotaEngine* engine, int32_t track_id, int32_t osc,+ NotaAuroraTableInfo* out);+/* The slot's base frames (2048 × frames floats); returns floats written (the count when out is null), 0 if none. */+NOTA_API int64_t nota_track_aurora_table_read(const NotaEngine* engine, int32_t track_id, int32_t osc, float* out,+ int64_t cap);+/* Drawing preview: rep_frames (≤ 16) evenly chosen frames, then grid_frames (≤ 64) evenly chosen+ * frames, each `points` (≤ 256) values back to back: for each of points / 2 slices of the+ * frame, its lowest and highest sample in the order they occur (a min / max outline).+ * Returns floats written (the count needed when out is null). */+NOTA_API int32_t nota_track_aurora_table_preview(const NotaEngine* engine, int32_t track_id, int32_t osc,+ int32_t rep_frames, int32_t grid_frames, int32_t points, float* out,+ int32_t cap);+/* The state blob with (1) or without (0) the table frames; 0 is what a project save stores+ * beside the tables' own sample files. Size / copy semantics of nota_track_get_plugin_state. */+NOTA_API int32_t nota_track_aurora_state(const NotaEngine* engine, int32_t track_id, int32_t include_tables,+ uint8_t* out, int32_t cap);/* UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns):* id/iarg/farg are instrument-specific (see the instrument's action()). */NOTA_API void nota_track_instrument_action(NotaEngine* engine, int32_t track_id, int32_t id, int32_t iarg, float farg);diff --git a/src/native/nota.engine/src/abi/nota_engine_import.cpp b/src/native/nota.engine/src/abi/nota_engine_import.cppindex 5279fe9f..3d344aec 100644--- a/src/native/nota.engine/src/abi/nota_engine_import.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_import.cpp@@ -119,4 +119,57 @@ int64_t nota_file_decode_mono(const char* path, double max_seconds, float* out,return n;}+// ---- Nota Aurora tables (specs/053): builders, any thread ----+int32_t nota_aurora_table_build(const char* path, NotaAuroraTable** out) {+ if (!path || !out) return NOTA_AURORA_ERR_ARGS;+ *out = nullptr;+ std::shared_ptr<const nota::AuroraTable> t;+ const int32_t r = nota::AuroraTable::buildFromFile(std::string(path), t);+ if (r != nota::AuroraTable::Ok) return r;+ *out = new NotaAuroraTable{std::move(t)};+ return NOTA_AURORA_OK;+}++int32_t nota_aurora_table_from_frames(+ const float* frames, int32_t count, const char* name, int32_t origin, NotaAuroraTable** out) {+ if (!out) return NOTA_AURORA_ERR_ARGS;+ *out = nullptr;+ std::shared_ptr<const nota::AuroraTable> t;+ const int32_t r = nota::AuroraTable::buildFromFrames(frames, count, name ? std::string(name) : std::string(), origin, t);+ if (r != nota::AuroraTable::Ok) return r;+ *out = new NotaAuroraTable{std::move(t)};+ return NOTA_AURORA_OK;+}++int32_t nota_aurora_table_info(const NotaAuroraTable* t, NotaAuroraTableInfo* out) {+ if (!t || !out) return 0;+ notaFillAuroraInfo(t->table.get(), out);+ return 1;+}++int64_t nota_aurora_table_frames(const NotaAuroraTable* t, float* out, int64_t cap) {+ if (!t || !t->table) return 0;+ const int64_t n = (int64_t)t->table->level[0].size();+ if (!out) return n;+ const int64_t k = std::min(n, cap);+ if (k > 0) std::memcpy(out, t->table->base(), (size_t)k * sizeof(float));+ return std::max<int64_t>(k, 0);+}++void nota_aurora_table_free(NotaAuroraTable* t) { delete t; }+} // extern "C"++void notaFillAuroraInfo(const nota::AuroraTable* t, NotaAuroraTableInfo* out) {+ *out = NotaAuroraTableInfo{};+ if (!t) return;+ out->frames = t->frames;+ out->origin = t->origin;+ out->truncated_length = t->truncatedLength ? 1 : 0;+ out->truncated_frames = t->truncatedFrames ? 1 : 0;+ out->serial = t->serial;+ std::memcpy(out->hash, t->hash, 16);+ const size_t n = std::min(t->name.size(), sizeof(out->name) - 1);+ std::memcpy(out->name, t->name.data(), n);+ out->name[n] = 0;+}diff --git a/src/native/nota.engine/src/abi/nota_engine_internal.h b/src/native/nota.engine/src/abi/nota_engine_internal.hindex e58fba85..5b3dae6a 100644--- a/src/native/nota.engine/src/abi/nota_engine_internal.h+++ b/src/native/nota.engine/src/abi/nota_engine_internal.h@@ -15,3 +15,10 @@ using nota::Engine;// Handle-cast shorthands used across every C ABI slice.#define ENG(e) reinterpret_cast<Engine*>(e)#define CENG(e) reinterpret_cast<const Engine*>(e)++// The opaque Aurora table handle (specs/053): one reference to an immutable table.+struct NotaAuroraTable {+ std::shared_ptr<const nota::AuroraTable> table;+};+// Fills a NotaAuroraTableInfo's table fields from `t` (null = an empty slot).+void notaFillAuroraInfo(const nota::AuroraTable* t, NotaAuroraTableInfo* out);diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cppindex 985a0213..1c685af3 100644--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp@@ -7,6 +7,7 @@#include "nota_engine_internal.h"#include "devices/instruments/Mosaic.h"+#include "devices/instruments/WavetableSynth.h"#include <algorithm>#include <cstring>@@ -1022,4 +1023,96 @@ NotaResult nota_midi_clip_ctl_set(return ENG(e)->ctlSet(track_id, false, clip_index, ctl, pts, count) ? NOTA_OK : NOTA_ERR_INVALID_ARG;}++// ---- Nota Aurora custom wavetables (specs/053), message thread ----+int32_t nota_track_aurora_set_table(NotaEngine* e, int32_t track_id, int32_t osc, const NotaAuroraTable* t, int32_t checkpoint) {+ if (!e || !t || !t->table) return 0;+ return ENG(e)->auroraSetTable(track_id, osc, t->table, checkpoint != 0) ? 1 : 0;+}+int32_t nota_track_aurora_clear_table(NotaEngine* e, int32_t track_id, int32_t osc) {+ return e && ENG(e)->auroraClearTable(track_id, osc) ? 1 : 0;+}+int32_t nota_track_aurora_set_source(NotaEngine* e, int32_t track_id, int32_t osc, int32_t use_custom,+ int32_t checkpoint) {+ return e && ENG(e)->auroraSetSource(track_id, osc, use_custom != 0, checkpoint != 0) ? 1 : 0;+}+int32_t nota_track_aurora_set_missing(NotaEngine* e, int32_t track_id, int32_t osc, const char* name) {+ return e && ENG(e)->auroraSetMissing(track_id, osc, name ? std::string(name) : std::string()) ? 1 : 0;+}+int32_t nota_track_aurora_table_info(const NotaEngine* e, int32_t track_id, int32_t osc, NotaAuroraTableInfo* out) {+ if (!e || !out || osc < 0 || osc > 1) return 0;+ auto w = CENG(e)->auroraOf(track_id);+ if (!w) return 0;+ const auto t = w->table(osc);+ notaFillAuroraInfo(t.get(), out);+ out->use_custom = w->useCustom(osc) ? 1 : 0;+ const std::string miss = w->missingName(osc);+ if (!miss.empty()) {+ out->missing = 1;+ if (!t) {+ const size_t n = std::min(miss.size(), sizeof(out->name) - 1);+ std::memcpy(out->name, miss.data(), n);+ out->name[n] = 0;+ }+ }+ return 1;+}+int64_t nota_track_aurora_table_read(const NotaEngine* e, int32_t track_id, int32_t osc, float* out, int64_t cap) {+ if (!e || osc < 0 || osc > 1) return 0;+ auto w = CENG(e)->auroraOf(track_id);+ const auto t = w ? w->table(osc) : nullptr;+ if (!t) return 0;+ const int64_t n = (int64_t)t->level[0].size();+ if (!out) return n;+ const int64_t k = std::min(n, cap);+ if (k <= 0) return 0;+ std::memcpy(out, t->base(), (size_t)k * sizeof(float));+ return k;+}+int32_t nota_track_aurora_table_preview(const NotaEngine* e, int32_t track_id, int32_t osc, int32_t rep_frames,+ int32_t grid_frames, int32_t points, float* out, int32_t cap) {+ if (!e || osc < 0 || osc > 1) return 0;+ auto w = CENG(e)->auroraOf(track_id);+ const auto t = w ? w->table(osc) : nullptr;+ if (!t) return 0;+ rep_frames = std::clamp(rep_frames, 0, 16);+ grid_frames = std::clamp(grid_frames, 0, 64);+ points = std::clamp(points, 2, 256);+ const int64_t need = (int64_t)(rep_frames + grid_frames) * points;+ if (!out) return (int32_t)need;+ if (cap < need) return 0;+ // Each pair of points is the low and the high of one slice of the frame, in the order+ // they occur: a slow wave draws as its own shape, a frame full of fast cycles as the+ // band they fill, which a plain resample of a few hundred points would alias.+ const int len = nota::AuroraTable::kSize, nf = t->frames, slices = points / 2;+ float* p = out;+ for (int pass = 0; pass < 2; ++pass) {+ const int count = pass == 0 ? rep_frames : grid_frames;+ for (int i = 0; i < count; ++i) {+ const int f = count > 1 ? (int)std::lround((double)i * (nf - 1) / (count - 1)) : 0;+ const float* src = t->frame(0, std::clamp(f, 0, nf - 1));+ for (int s = 0; s < slices; ++s) {+ const int a = s * len / slices, b = (s + 1) * len / slices;+ int lo = a, hi = a;+ for (int k = a + 1; k < b; ++k) {+ if (src[k] < src[lo]) lo = k;+ if (src[k] > src[hi]) hi = k;+ }+ *p++ = src[std::min(lo, hi)];+ *p++ = src[std::max(lo, hi)];+ }+ if (points & 1) *p++ = src[len - 1];+ }+ }+ return (int32_t)need;+}+int32_t nota_track_aurora_state(const NotaEngine* e, int32_t track_id, int32_t include_tables, uint8_t* out, int32_t cap) {+ if (!e) return 0;+ auto w = CENG(e)->auroraOf(track_id);+ if (!w) return 0;+ const auto v = w->stateWith(include_tables != 0);+ if (out && cap >= (int32_t)v.size()) std::copy(v.begin(), v.end(), out);+ return (int32_t)v.size();+}+} // extern "C"diff --git a/src/native/nota.engine/src/devices/instruments/AuroraTable.cpp b/src/native/nota.engine/src/devices/instruments/AuroraTable.cppnew file mode 100644index 00000000..d396df15--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/AuroraTable.cpp@@ -0,0 +1,276 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// AuroraTable builders (see AuroraTable.h). Everything here runs on the caller's thread+// — a worker for an import, the message thread for a reload — and allocates freely; the+// audio thread only ever sees the finished, immutable table.++#include "devices/instruments/AuroraTable.h"++#include "media/AudioFile.h"++#include <signalsmith-linear/fft.h>++#include <algorithm>+#include <atomic>+#include <cctype>+#include <cmath>+#include <complex>+#include <cstdio>+#include <cstring>++namespace nota {+namespace {++using Cx = std::complex<double>;+constexpr double kTwoPi = 6.283185307179586;+constexpr double kSilentPeak = 0.001; // −60 dBFS+constexpr int kSeam = 32;++bool isPow2(int64_t n) { return n > 0 && (n & (n - 1)) == 0; }++std::string extLower(const std::string& path) {+ auto dot = path.find_last_of('.');+ if (dot == std::string::npos) return {};+ std::string e = path.substr(dot + 1);+ for (auto& c : e) c = (char)std::tolower((unsigned char)c);+ return e;+}++// The frame size a wavetable WAV declares in its `clm ` chunk ("<!>2048 …"), or 0.+int32_t clmFrameSize(const std::string& path) {+ std::FILE* f = std::fopen(path.c_str(), "rb");+ if (!f) return 0;+ int32_t found = 0;+ unsigned char hdr[12];+ if (std::fread(hdr, 1, 12, f) == 12 && std::memcmp(hdr, "RIFF", 4) == 0 && std::memcmp(hdr + 8, "WAVE", 4) == 0) {+ for (int guard = 0; guard < 64; ++guard) {+ unsigned char ch[8];+ if (std::fread(ch, 1, 8, f) != 8) break;+ const uint32_t sz = (uint32_t)ch[4] | ((uint32_t)ch[5] << 8) | ((uint32_t)ch[6] << 16) | ((uint32_t)ch[7] << 24);+ if (std::memcmp(ch, "clm ", 4) == 0) {+ char buf[64] = {};+ const size_t want = std::min<size_t>(sz, sizeof(buf) - 1);+ if (std::fread(buf, 1, want, f) == want) {+ const char* p = std::strstr(buf, "<!>");+ if (p) found = std::atoi(p + 3);+ }+ break;+ }+ if (std::fseek(f, (long)(sz + (sz & 1u)), SEEK_CUR) != 0) break;+ }+ }+ std::fclose(f);+ return found;+}++// Complex spectrum of one real period x[0..n), bins 0..k-1 (k ≤ n/2), unscaled.+void spectrum(const float* x, int n, int k, std::vector<Cx>& out) {+ out.assign((size_t)k, Cx{});+ if (isPow2(n)) {+ signalsmith::linear::Pow2FFT<double> fft((size_t)n);+ std::vector<Cx> t((size_t)n), fr((size_t)n);+ for (int i = 0; i < n; ++i) t[(size_t)i] = Cx(x[i], 0.0);+ fft.fft(t.data(), fr.data());+ for (int i = 0; i < k; ++i) out[(size_t)i] = fr[(size_t)i];+ return;+ }+ for (int b = 0; b < k; ++b) { // naive DFT: only for short single cycles of odd length+ Cx acc{};+ for (int i = 0; i < n; ++i) {+ const double ph = -kTwoPi * (double)b * i / n;+ acc += (double)x[i] * Cx(std::cos(ph), std::sin(ph));+ }+ out[(size_t)b] = acc;+ }+}++// One period of `len` samples from bins 0..k-1 of an n-sample period's spectrum.+void synth(const std::vector<Cx>& bins, int k, int n, int len, float* out) {+ signalsmith::linear::Pow2FFT<double> fft((size_t)len);+ std::vector<Cx> fr((size_t)len, Cx{}), t((size_t)len);+ const int kk = std::min(k, len / 2);+ fr[0] = Cx(bins[0].real(), 0.0);+ for (int b = 1; b < kk; ++b) {+ fr[(size_t)b] = bins[(size_t)b];+ fr[(size_t)(len - b)] = std::conj(bins[(size_t)b]);+ }+ fft.ifft(fr.data(), t.data());+ for (int i = 0; i < len; ++i) out[i] = (float)(t[(size_t)i].real() / n);+}++// Resample one period of n samples to exactly 2048 (band-limited, no interpolation).+void resampleCycle(const float* x, int n, float* out) {+ if (n == AuroraTable::kSize) {+ std::copy(x, x + n, out);+ return;+ }+ std::vector<Cx> bins;+ const int k = std::min((n + 1) / 2, AuroraTable::kSize / 2);+ spectrum(x, n, k, bins);+ synth(bins, k, n, AuroraTable::kSize, out);+}++void buildMips(AuroraTable& t) {+ const int N = AuroraTable::kSize;+ for (int k = 1; k < AuroraTable::kLevels; ++k) t.level[k].assign((size_t)t.frames * (size_t)AuroraTable::len(k), 0.0f);+ std::vector<Cx> bins;+ for (int f = 0; f < t.frames; ++f) {+ spectrum(t.frame(0, f), N, N / 2, bins);+ for (int k = 1; k < AuroraTable::kLevels; ++k) {+ const int L = AuroraTable::len(k);+ synth(bins, AuroraTable::harmonics(k), N, L, t.level[k].data() + (size_t)f * (size_t)L);+ }+ }+}++void hashBase(AuroraTable& t) {+ uint64_t a = 1469598103934665603ull, b = 1099511628211ull ^ 0x9e3779b97f4a7c15ull;+ const auto* p = reinterpret_cast<const unsigned char*>(t.level[0].data());+ const size_t n = t.level[0].size() * sizeof(float);+ for (size_t i = 0; i < n; ++i) {+ a = (a ^ p[i]) * 1099511628211ull;+ b = (b ^ p[i]) * 0x100000001b3ull + 0x2545F4914F6CDD1Dull;+ }+ for (int i = 0; i < 8; ++i) {+ t.hash[i] = (uint8_t)(a >> (8 * i));+ t.hash[8 + i] = (uint8_t)(b >> (8 * i));+ }+}++uint32_t nextSerial() {+ static std::atomic<uint32_t> s{0};+ return ++s;+}++std::string baseName(const std::string& path) {+ auto sl = path.find_last_of("/\\");+ return sl == std::string::npos ? path : path.substr(sl + 1);+}++} // namespace++int32_t AuroraTable::buildFromMono(const float* mono, int64_t n, int32_t declaredFrame, std::string name,+ bool truncatedLength, std::shared_ptr<const AuroraTable>& out) {+ if (!mono || n <= 0) return ErrEmpty;+ float peakIn = 0.0f;+ for (int64_t i = 0; i < n; ++i) peakIn = std::max(peakIn, std::fabs(mono[i]));+ if (!(peakIn >= kSilentPeak)) return ErrSilent;++ auto t = std::make_shared<AuroraTable>();+ t->name = std::move(name);+ t->truncatedLength = truncatedLength;+ std::vector<float>& base = t->level[0];++ const bool declared = declaredFrame >= 256 && declaredFrame <= 4096 && isPow2(declaredFrame) && n >= declaredFrame;+ // Without a `clm ` chunk, an exact multiple of 2048 counts as a wavetable file only up+ // to 256 frames: a longer recording that happens to land on a multiple is a recording.+ if (declared || (n % kSize == 0 && n >= 2 * kSize && n <= (int64_t)kMaxFrames * kSize)) {+ // (a) A standard wavetable file.+ const int fs = declared ? declaredFrame : kSize;+ int64_t count = n / fs;+ if (count > kMaxFrames) {+ count = kMaxFrames;+ t->truncatedFrames = true;+ }+ t->origin = WavetableFile;+ t->frames = (int32_t)count;+ base.assign((size_t)count * kSize, 0.0f);+ for (int64_t f = 0; f < count; ++f) resampleCycle(mono + f * fs, fs, base.data() + f * kSize);+ } else if (n <= 2 * kSize) {+ // (b) One cycle.+ t->origin = SingleCycle;+ t->frames = 1;+ base.assign(kSize, 0.0f);+ resampleCycle(mono, (int)n, base.data());+ } else {+ // (c) A recording: 16 windows across it, each starting on an upward zero crossing+ // near its even position, and its last samples blended into its first so it loops.+ t->origin = Recording;+ t->frames = kRecordingFrames;+ base.assign((size_t)kRecordingFrames * kSize, 0.0f);+ const int64_t span = std::max<int64_t>(0, n - kSize);+ for (int f = 0; f < kRecordingFrames; ++f) {+ int64_t s0 = (int64_t)std::llround((double)f * (double)span / (kRecordingFrames - 1));+ int64_t best = s0, bestD = -1;+ const int64_t lo = std::max<int64_t>(1, s0 - kSize / 2), hi = std::min<int64_t>(span, s0 + kSize / 2);+ for (int64_t j = lo; j <= hi; ++j)+ if (mono[j - 1] < 0.0f && mono[j] >= 0.0f) {+ const int64_t d = std::llabs(j - s0);+ if (bestD < 0 || d < bestD) {+ bestD = d;+ best = j;+ }+ }+ float* dst = base.data() + (size_t)f * kSize;+ for (int i = 0; i < kSize; ++i) dst[i] = mono[std::min<int64_t>(best + i, n - 1)];+ for (int i = 0; i < kSeam; ++i) {+ const int64_t src = best + kSize + i;+ if (src >= n) break;+ const double w = (i + 0.5) / kSeam * (kTwoPi / 4.0);+ dst[i] = (float)(dst[i] * std::sin(w) + mono[src] * std::cos(w));+ }+ }+ }++ // DC out of every frame, then the whole table to the built-in tables' peak (1.0),+ // the frames keeping their relative levels.+ float peak = 0.0f;+ for (int f = 0; f < t->frames; ++f) {+ float* p = base.data() + (size_t)f * kSize;+ double mean = 0.0;+ for (int i = 0; i < kSize; ++i) mean += p[i];+ mean /= kSize;+ for (int i = 0; i < kSize; ++i) {+ p[i] = (float)(p[i] - mean);+ peak = std::max(peak, std::fabs(p[i]));+ }+ }+ if (!(peak > 1e-9f)) return ErrSilent;+ const float g = 1.0f / peak;+ for (auto& v : base) v *= g;++ buildMips(*t);+ hashBase(*t);+ t->serial = nextSerial();+ out = std::move(t);+ return Ok;+}++int32_t AuroraTable::buildFromFile(const std::string& path, std::shared_ptr<const AuroraTable>& out) {+ const std::string ext = extLower(path);+ if (ext != "wav" && ext != "flac" && ext != "mp3") return ErrFormat;+ auto buf = decodeAudioFile(path);+ if (!buf) return ErrDecode;+ if (buf->empty()) return ErrEmpty;+ const double sr = buf->sourceSampleRate > 0 ? buf->sourceSampleRate : 44100.0;+ const int64_t cap = (int64_t)(sr * kMaxSeconds);+ const bool truncated = buf->frames > cap;+ const int64_t n = std::min<int64_t>(buf->frames, cap);+ std::vector<float> mono((size_t)n, 0.0f);+ const int ch = buf->channels;+ for (int64_t i = 0; i < n; ++i) {+ float acc = 0.0f;+ for (int c = 0; c < ch; ++c) acc += buf->samples[(size_t)(i * ch + c)];+ mono[(size_t)i] = acc / (float)ch;+ }+ const int32_t declared = ext == "wav" ? clmFrameSize(path) : 0;+ return buildFromMono(mono.data(), n, declared, baseName(path), truncated, out);+}++int32_t AuroraTable::buildFromFrames(const float* frames, int32_t count, std::string name, int32_t origin,+ std::shared_ptr<const AuroraTable>& out) {+ if (!frames || count <= 0 || count > kMaxFrames) return ErrArgs;+ auto t = std::make_shared<AuroraTable>();+ t->name = std::move(name);+ t->origin = std::clamp(origin, 0, 2);+ t->frames = count;+ t->level[0].assign(frames, frames + (size_t)count * kSize);+ buildMips(*t);+ hashBase(*t);+ t->serial = nextSerial();+ out = std::move(t);+ return Ok;+}++} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/AuroraTable.h b/src/native/nota.engine/src/devices/instruments/AuroraTable.hnew file mode 100644index 00000000..d78c97b1--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/AuroraTable.h@@ -0,0 +1,75 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A custom wavetable for Nota Aurora (specs/053): the frames an audio file was turned+// into, conditioned (DC removed, peak-normalised, loop seams blended) and band-limited+// into ten mip levels so a bright table played high does not fold back. It is built+// once on any thread — the builders touch no engine state — and never changes after,+// so the audio thread can read it through a plain pointer for as long as the+// snapshot that holds it is live.+//+// How a file becomes frames (spec FR-009, research R3):+// (a) a standard wavetable file — a `clm ` chunk names the frame size, or the length+// is an exact multiple of 2048 from two to 256 frames — keeps its frames, ≤ 256;+// (b) otherwise up to 4096 samples is one cycle, resampled to 2048 exactly;+// (c) otherwise a recording: 16 evenly spaced 2048-sample windows, each snapped to+// an upward zero crossing, with no pitch detection.+// Only the first 60 s are read.++#pragma once++#include <cstdint>+#include <memory>+#include <string>+#include <vector>++namespace nota {++struct AuroraTable {+ static constexpr int kSize = 2048, kLevels = 10, kMaxFrames = 256, kRecordingFrames = 16;+ static constexpr int kMinLen = 256;+ static constexpr double kMaxSeconds = 60.0;++ enum Origin : int32_t { WavetableFile = 0, SingleCycle = 1, Recording = 2 };+ enum Result : int32_t { Ok = 0, ErrDecode = -1, ErrFormat = -2, ErrSilent = -3, ErrEmpty = -4, ErrArgs = -5 };++ int32_t frames = 0;+ int32_t origin = WavetableFile;+ bool truncatedLength = false, truncatedFrames = false;+ std::string name;+ uint8_t hash[16] = {};+ uint32_t serial = 0;+ // level[k] holds `frames` frames of len(k) samples with the harmonics below+ // harmonics(k) = 1024 >> k (level 0 is the conditioned frames themselves). From level 1+ // on a level keeps at least four samples per cycle of its top harmonic, and no level is+ // shorter than 256 samples, so the linear read stays clean (research R4).+ std::vector<float> level[kLevels];++ static constexpr int len(int k) {+ const int l = k == 0 ? kSize : (2 * kSize) >> k;+ return l > kSize ? kSize : (l < kMinLen ? kMinLen : l);+ }+ static constexpr int harmonics(int k) { return (kSize / 2) >> k; }+ const float* frame(int k, int f) const { return level[k].data() + (size_t)f * (size_t)len(k); }+ const float* base() const { return level[0].data(); }++ // Decode and build (WAV / FLAC / MP3). Returns Ok and sets `out`, or an error.+ static int32_t buildFromFile(const std::string& path, std::shared_ptr<const AuroraTable>& out);+ // The same rules from mono samples already in memory (`declaredFrame` > 0 when the+ // source names its frame size). Used by buildFromFile and by tests.+ static int32_t buildFromMono(const float* mono, int64_t n, int32_t declaredFrame, std::string name,+ bool truncatedLength, std::shared_ptr<const AuroraTable>& out);+ // Already-conditioned frames (a project or preset reload): only the mips are+ // rebuilt, so a reload plays exactly what was saved.+ static int32_t buildFromFrames(const float* frames, int32_t count, std::string name, int32_t origin,+ std::shared_ptr<const AuroraTable>& out);+};++// What one Aurora holds: a table per oscillator (null = none) and, for a table a project+// could not restore, the name it had.+struct AuroraTableSet {+ std::shared_ptr<const AuroraTable> slot[2];+ std::string missing[2];+};++} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/WavetableSynth.cpp b/src/native/nota.engine/src/devices/instruments/WavetableSynth.cppindex 2bd28e31..890299e3 100644--- a/src/native/nota.engine/src/devices/instruments/WavetableSynth.cpp+++ b/src/native/nota.engine/src/devices/instruments/WavetableSynth.cpp@@ -232,39 +232,248 @@ int32_t WavetableSynth::pluginParamIndexOfId(const std::string& id) const {return it == map.end() ? -1 : it->second;}-std::vector<uint8_t> WavetableSynth::getState() const {+// ---- state blob (contracts/state-blob.md) --------------------------------+namespace {+constexpr char kTrailerTag[4] = {'A', 'W', 'T', '1'};+constexpr uint32_t kTrailerVersion = 1;++void putU8(std::vector<uint8_t>& b, uint8_t v) { b.push_back(v); }+void putU16(std::vector<uint8_t>& b, uint16_t v) {+ b.push_back((uint8_t)(v & 0xFF));+ b.push_back((uint8_t)(v >> 8));+}+void putU32(std::vector<uint8_t>& b, uint32_t v) {+ for (int i = 0; i < 4; ++i) b.push_back((uint8_t)(v >> (8 * i)));+}+void putStr(std::vector<uint8_t>& b, const std::string& s) {+ const size_t n = std::min<size_t>(s.size(), 0xFFFF);+ putU16(b, (uint16_t)n);+ b.insert(b.end(), s.begin(), s.begin() + (ptrdiff_t)n);+}++struct Reader {+ const uint8_t* p;+ size_t n, at = 0;+ bool ok = true;+ bool need(size_t k) {+ if (!ok || at + k > n) ok = false;+ return ok;+ }+ uint8_t u8() { return need(1) ? p[at++] : 0; }+ uint16_t u16() {+ if (!need(2)) return 0;+ const uint16_t v = (uint16_t)(p[at] | (p[at + 1] << 8));+ at += 2;+ return v;+ }+ uint32_t u32() {+ if (!need(4)) return 0;+ uint32_t v = 0;+ for (int i = 0; i < 4; ++i) v |= (uint32_t)p[at + i] << (8 * i);+ at += 4;+ return v;+ }+ std::string str() {+ const uint16_t k = u16();+ if (!need(k)) return {};+ std::string s(reinterpret_cast<const char*>(p + at), k);+ at += k;+ return s;+ }+};+} // namespace++std::vector<uint8_t> WavetableSynth::stateWith(bool includeTables) const {std::vector<uint8_t> b(kNumParams * sizeof(float));for (int i = 0; i < kNumParams; ++i) {float v = pn_[i].load(std::memory_order_relaxed);std::memcpy(b.data() + i * sizeof(float), &v, sizeof(float));}+ const auto set = tableSet_.current();+ const uint8_t flag[2] = {useCustom_[0].load(std::memory_order_relaxed), useCustom_[1].load(std::memory_order_relaxed)};+ bool any = flag[0] || flag[1];+ if (set)+ for (int o = 0; o < 2; ++o) any = any || set->slot[o] || !set->missing[o].empty();+ if (!any) return b; // byte-identical to the blob before custom tables existed++ const size_t start = b.size();+ b.insert(b.end(), kTrailerTag, kTrailerTag + 4);+ putU32(b, kTrailerVersion);+ putU8(b, flag[0]);+ putU8(b, flag[1]);+ for (int o = 0; o < 2; ++o) {+ const AuroraTable* t = (includeTables && set) ? set->slot[o].get() : nullptr;+ putU8(b, t ? 1 : 0);+ putStr(b, set ? set->missing[o] : std::string());+ if (!t) continue;+ const AuroraTable* t0 = set->slot[0].get();+ if (o == 1) {+ const bool same = t0 && (t0 == t || std::memcmp(t0->hash, t->hash, 16) == 0);+ putU8(b, same ? 1 : 0);+ if (same) continue;+ }+ putStr(b, t->name);+ putU8(b, (uint8_t)t->origin);+ putU8(b, t->truncatedLength ? 1 : 0);+ putU8(b, t->truncatedFrames ? 1 : 0);+ putU32(b, (uint32_t)t->frames);+ const auto* f = reinterpret_cast<const uint8_t*>(t->base());+ b.insert(b.end(), f, f + (size_t)t->frames * AuroraTable::kSize * sizeof(float));+ }+ const uint32_t S = (uint32_t)(b.size() - start);+ putU32(b, S);+ b.insert(b.end(), kTrailerTag, kTrailerTag + 4);return b;}void WavetableSynth::setState(const uint8_t* data, int32_t size) {- if (!data) return;- const int n = std::min<int>(kNumParams, size / (int)sizeof(float));+ if (!data || size < 0) return;+ // The trailer, when there is one, is found from the end of the blob.+ size_t paramBytes = (size_t)size;+ const uint8_t* sec = nullptr;+ size_t secLen = 0;+ if (size >= 8 && std::memcmp(data + size - 4, kTrailerTag, 4) == 0) {+ uint32_t S = 0;+ for (int i = 0; i < 4; ++i) S |= (uint32_t)data[size - 8 + i] << (8 * i);+ if ((uint64_t)S + 8 <= (uint64_t)size && S >= 4 && std::memcmp(data + size - 8 - S, kTrailerTag, 4) == 0) {+ paramBytes = (size_t)size - S - 8;+ sec = data + paramBytes;+ secLen = S;+ }+ }+ const int n = std::min<int>(kNumParams, (int)(paramBytes / sizeof(float)));for (int i = 0; i < n; ++i) {float v;std::memcpy(&v, data + i * sizeof(float), sizeof(float));if (std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);}++ if (!sec) {+ // No trailer: a blob from before custom tables, or one without any. Both+ // oscillators go back to their built-in tables.+ const auto cur = tableSet_.current();+ if (cur && (cur->slot[0] || cur->slot[1] || !cur->missing[0].empty() || !cur->missing[1].empty()))+ publishSet(std::make_shared<AuroraTableSet>());+ useCustom_[0].store(0, std::memory_order_relaxed);+ useCustom_[1].store(0, std::memory_order_relaxed);+ return;+ }+ Reader r{sec, secLen};+ r.at = 4;+ if (r.u32() != kTrailerVersion || !r.ok) return; // a newer writer: keep the tables as they are+ uint8_t flag[2];+ flag[0] = r.u8();+ flag[1] = r.u8();+ auto next = std::make_shared<AuroraTableSet>();+ for (int o = 0; o < 2 && r.ok; ++o) {+ const uint8_t present = r.u8();+ next->missing[o] = r.str();+ if (!present) continue;+ if (o == 1 && r.u8()) {+ next->slot[1] = next->slot[0];+ continue;+ }+ std::string name = r.str();+ const int32_t origin = r.u8();+ const bool tl = r.u8() != 0, tf = r.u8() != 0;+ const uint32_t frames = r.u32();+ if (!r.ok || frames < 1 || frames > (uint32_t)AuroraTable::kMaxFrames) {+ r.ok = false;+ break;+ }+ const size_t bytes = (size_t)frames * AuroraTable::kSize * sizeof(float);+ if (!r.need(bytes)) break;+ std::vector<float> base((size_t)frames * AuroraTable::kSize);+ std::memcpy(base.data(), sec + r.at, bytes);+ r.at += bytes;+ std::shared_ptr<const AuroraTable> t;+ if (AuroraTable::buildFromFrames(base.data(), (int32_t)frames, std::move(name), origin, t) == AuroraTable::Ok) {+ auto m = std::const_pointer_cast<AuroraTable>(t);+ m->truncatedLength = tl;+ m->truncatedFrames = tf;+ next->slot[o] = t;+ }+ }+ if (!r.ok) return; // a damaged section: the parameters stand, the tables stay as they were+ publishSet(std::move(next));+ useCustom_[0].store(flag[0] ? 1 : 0, std::memory_order_relaxed);+ useCustom_[1].store(flag[1] ? 1 : 0, std::memory_order_relaxed);}std::shared_ptr<Instrument> WavetableSynth::clone() const {auto s = std::make_shared<WavetableSynth>();for (int i = 0; i < kNumParams; ++i)s->pn_[i].store(pn_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);+ if (auto cur = tableSet_.current()) s->tableSet_.publish(cur); // immutable: shared, not copied+ for (int o = 0; o < 2; ++o) s->useCustom_[o].store(useCustom_[o].load(std::memory_order_relaxed));s->setSampleRate(sampleRate_);return s;}+// ---- custom tables: message-thread setters ----------------------------------+void WavetableSynth::setTable(int osc, std::shared_ptr<const AuroraTable> t) {+ if (osc < 0 || osc > 1) return;+ auto next = copySet();+ next->slot[osc] = std::move(t);+ next->missing[osc].clear();+ const bool has = next->slot[osc] != nullptr;+ publishSet(std::move(next));+ useCustom_[osc].store(has ? 1 : 0, std::memory_order_relaxed);+ wake();+}++void WavetableSynth::clearTable(int osc) {+ if (osc < 0 || osc > 1) return;+ useCustom_[osc].store(0, std::memory_order_relaxed);+ auto next = copySet();+ next->slot[osc].reset();+ next->missing[osc].clear();+ publishSet(std::move(next));+ wake();+}++void WavetableSynth::setMissing(int osc, const std::string& name) {+ if (osc < 0 || osc > 1) return;+ auto next = copySet();+ next->missing[osc] = name;+ publishSet(std::move(next));+}++std::shared_ptr<const AuroraTable> WavetableSynth::table(int osc) const {+ if (osc < 0 || osc > 1) return nullptr;+ auto cur = tableSet_.current();+ return cur ? cur->slot[osc] : nullptr;+}++std::string WavetableSynth::missingName(int osc) const {+ if (osc < 0 || osc > 1) return {};+ auto cur = tableSet_.current();+ return cur ? cur->missing[osc] : std::string();+}++int32_t WavetableSynth::scopeRead(float* out, int32_t maxN) const {+ if (!out || maxN <= 0) return 0;+ const int32_t n = std::min(maxN, kScopeN);+ for (int32_t i = 0; i < n; ++i) out[i] = scope_[i].load(std::memory_order_relaxed);+ // The serials come from the set the message thread holds, so they are current even+ // while the synth sleeps and is not rendered.+ const auto cur = tableSet_.current();+ for (int o = 0; o < 2 && 2 + o < n; ++o)+ out[2 + o] = (cur && cur->slot[o]) ? (float)(cur->slot[o]->serial & 0xFFFFFFu) : 0.0f;+ // Which oscillators play their imported table (bit 0 = Osc 1, bit 1 = Osc 2), so a card+ // sees a source switch made anywhere else (another card, an undo, a state load).+ if (n > 5) out[5] = (float)((useCustom(0) ? 1 : 0) | (useCustom(1) ? 2 : 0));+ if (maxN <= kScopeN) return n;+ return kScopeN + readEnvTele(envTele_, 2 * kEnvTeleFloats, out + kScopeN, maxN - kScopeN);+}+void WavetableSynth::noteOn(int32_t pitch, float velocity) {const bool mono = get(MonoMode) > 0.5f;Voice* v = mono ? &voices_[0] : findFreeVoice();const bool legato = mono && v->active && v->stage != Stage::Off;v->active = true;v->pitch = pitch;+ v->seq = ++noteSeq_;v->freq = 440.0 * std::pow(2.0, (pitch - 69) / 12.0);{float add[kExprDims];@@ -315,6 +524,7 @@ void WavetableSynth::allNotesOff() {}void WavetableSynth::render(float* out, int32_t frames) {+ SnapshotHistory<const AuroraTableSet>::RenderScope tableScope(tableSet_);// ---- macros first: seven of the twelve destinations ride the per-voice bus// below, the other five move this block's snapshot ----double macroDst[kDests] = {0, 0, 0, 0, 0, 0, 0};@@ -340,6 +550,12 @@ void WavetableSynth::render(float* out, int32_t frames) {// ---- block snapshot ----const int b1 = bankOf(Table), b2 = bankOf(Osc2Table);+ // Imported tables (specs/053): null unless the oscillator holds one and plays it.+ const AuroraTableSet* tset = tableSet_.live();+ const AuroraTable* ct1 =+ (tset && useCustom_[0].load(std::memory_order_relaxed)) ? tset->slot[0].get() : nullptr;+ const AuroraTable* ct2 =+ (tset && useCustom_[1].load(std::memory_order_relaxed)) ? tset->slot[1].get() : nullptr;const int wm1 = warpModeOf(Osc1WarpMode), wm2 = warpModeOf(Osc2WarpMode);const float basePos1 = get(Position), basePos2 = get(Osc2Position);const double warp1 = std::clamp(get(Warp) + macroBlk[0], 0.0, 1.0);@@ -373,6 +589,9 @@ void WavetableSynth::render(float* out, int32_t frames) {// √2 undoes the equal-power law's 0.707 at centre, so a spread of 0 is bit-for-bit// the mono stack this used to be.const float uniNorm = 1.41421356f / std::sqrt((float)uniN);+ // The fastest unison voice's detune factor, for the imported tables' mip pick.+ double uniMaxDet = 1.0;+ for (int u = 0; u < uniN; ++u) uniMaxDet = std::max(uniMaxDet, uniDetF[u]);// Only a spread stack has a side; without one its filter state is parked at zero so// it starts clean the moment the spread opens.const bool stereoUni = uniN > 1 && uniSpread > 1e-6f;@@ -522,12 +741,22 @@ void WavetableSynth::render(float* out, int32_t frames) {// routing and the same filters (own state, shared coefficients), so every// unison voice gets the cutoff, the envelope and the modulation (#193).float o1 = 0.0f, o2 = 0.0f, sd1 = 0.0f, sd2 = 0.0f;- if (lvl1 > 1e-5f)- o1 = oscStack(- v.ph1, base * m1, b1, pos1, wm1, warp1, uniN, uniDetF, uniPanL, uniPanR, uniNorm, sd1);- if (lvl2 > 1e-5f)- o2 = oscStack(v.ph2, base * m2 * (osc2PitchStatic ? 1.0 : std::exp2(dst[1] * 2.0)), b2, pos2,- wm2, warp2, uniN, uniDetF, uniPanL, uniPanR, uniNorm, sd2);+ if (lvl1 > 1e-5f) {+ if (ct1)+ o1 = oscStackCustom(v.ph1, base * m1, *ct1, pos1, wm1, warp1, uniN, uniDetF, uniMaxDet, uniPanL,+ uniPanR, uniNorm, sd1);+ else+ o1 = oscStack(+ v.ph1, base * m1, b1, pos1, wm1, warp1, uniN, uniDetF, uniPanL, uniPanR, uniNorm, sd1);+ }+ if (lvl2 > 1e-5f) {+ const double inc2 = base * m2 * (osc2PitchStatic ? 1.0 : std::exp2(dst[1] * 2.0));+ if (ct2)+ o2 = oscStackCustom(v.ph2, inc2, *ct2, pos2, wm2, warp2, uniN, uniDetF, uniMaxDet, uniPanL,+ uniPanR, uniNorm, sd2);+ else+ o2 = oscStack(v.ph2, inc2, b2, pos2, wm2, warp2, uniN, uniDetF, uniPanL, uniPanR, uniNorm, sd2);+ }float sub = 0.0f;if (subLvl > 1e-5f) {sub = subOsc(subWave, v.subPh);@@ -607,8 +836,34 @@ void WavetableSynth::render(float* out, int32_t frames) {// Auto-sleep flag only (the engine skips render while idle): no voice sounding// and this block silent. noteOn/noteOff/setParam wake.int live = 0;+ const Voice* newest = nullptr;for (auto& v : voices_)- if (v.active) ++live;+ if (v.active) {+ ++live;+ if (!newest || v.seq > newest->seq) newest = &v;+ }+ // Live follow telemetry, once per block (relaxed: the UI only draws it). The newest+ // voice's positions are worked out here from its end-of-block state rather than kept+ // per sample, so a block with no card watching costs nothing extra in the voice loop.+ float follow[2] = {-1.0f, -1.0f};+ if (newest) {+ double d = macroDst[2];+ if (amN) {+ auto wrap = [](double ph) { return ph >= 1.0 ? ph - 1.0 : ph; };+ const double lfo1 = lfoValue(ls1, wrap(lfoPhase1_), lfoSh1_) * lfo1Depth;+ const double lfo2 = lfoValue(ls2, wrap(lfoPhase2_), lfoSh2_) * lfo2Depth;+ const double src[kSources] = {newest->env, newest->env2, lfo1, lfo2, newest->velocity,+ std::clamp(newest->ktOct / 4.0, -1.0, 1.0), modWheel, newest->rand};+ for (int k = 0; k < amN; ++k)+ if (amD[k] == 2) d += src[amS[k]] * amA[k];+ }+ const float off = (float)d + newest->ex.slide() * 0.5f;+ follow[0] = std::clamp(basePos1 + off, 0.0f, 1.0f);+ follow[1] = std::clamp(basePos2 + off, 0.0f, 1.0f);+ }+ scope_[0].store(follow[0], std::memory_order_relaxed);+ scope_[1].store(follow[1], std::memory_order_relaxed);+ scope_[4].store((float)live, std::memory_order_relaxed);{const Voice* lv = lastVoice_ >= 0 ? &voices_[lastVoice_] : nullptr;const bool on = lv && lv->active;@@ -710,6 +965,40 @@ float WavetableSynth::oscStack(double* ph, double inc, int bank, float pos, intreturn (accL + accR) * 0.5f;}+float WavetableSynth::oscStackCustom(double* ph, double inc, const AuroraTable& t, float pos, int mode, double warpAmt,+ int uniN, const double* detF, double maxDet, const float* panL, const float* panR, float norm, float& sideOut) {+ // Mip pick (research R4): the smallest level k whose top harmonic (below 1024 >> k)+ // stays under 0.45 of the sample rate at the fastest unison voice, with the warp+ // mode's bias — Sync squeezes the cycle up to 8×, Bend up to 4×.+ double bias = 1.0;+ if (mode == 1) bias = 1.0 + 7.0 * warpAmt;+ else if (mode == 2) bias = 1.0 + 3.0 * warpAmt;+ const double fEff = std::fabs(inc) * maxDet * bias;+ int k = 0;+ while (k < AuroraTable::kLevels - 1 && (double)AuroraTable::harmonics(k) * fEff > 0.45) ++k;+ const int len = AuroraTable::len(k);+ const int nf = t.frames;+ const float posF = pos * (float)(nf - 1);+ const int f0 = std::clamp((int)posF, 0, nf - 1), f1 = std::min(f0 + 1, nf - 1);+ const float ff = posF - (float)f0;+ const float* t0 = t.frame(k, f0);+ const float* t1 = t.frame(k, f1);+ float accL = 0.0f, accR = 0.0f;+ for (int u = 0; u < uniN; ++u) {+ double rp = warpRead(mode, ph[u], warpAmt);+ float s = readMorphSized(t0, t1, ff, rp, len);+ if (mode == 4) s = foldOut(s, warpAmt);+ accL += s * panL[u];+ accR += s * panR[u];+ ph[u] += inc * detF[u];+ if (ph[u] >= 1.0) ph[u] -= 1.0;+ }+ accL *= norm;+ accR *= norm;+ sideOut = (accL - accR) * 0.5f;+ return (accL + accR) * 0.5f;+}+float WavetableSynth::harmAmp(int bank, float t, int n) {switch (bank) {case 0: return n == 1 ? 1.0f : t * (1.0f / n);diff --git a/src/native/nota.engine/src/devices/instruments/WavetableSynth.h b/src/native/nota.engine/src/devices/instruments/WavetableSynth.hindex 73db01ed..a2ac0649 100644--- a/src/native/nota.engine/src/devices/instruments/WavetableSynth.h+++ b/src/native/nota.engine/src/devices/instruments/WavetableSynth.h@@ -32,7 +32,9 @@#include "devices/Instrument.h"#include "EnvShape.h"+#include "devices/instruments/AuroraTable.h"#include "engine/NoteExpression.h"+#include "engine/SnapshotHistory.h"#include <algorithm>#include <atomic>@@ -173,11 +175,6 @@ class WavetableSynth final : public Instrument {// tail). Settles after the hangover; noteOn/noteOff/setParam wake.bool hasTail() const override { return true; }bool isIdle() const override { return idle_; }- // Envelope telemetry for the editor's graphs: the newest sounding voice's Env 1 stage and- // progress, then Env 2's (stage 0 A · 1 D · 2 S · 3 R · 4 none).- int32_t scopeRead(float* out, int32_t maxN) const override {- return out && maxN > 0 ? readEnvTele(envTele_, 2 * kEnvTeleFloats, out, maxN) : 0;- }void wake() override;// ---- parameters --------------------------------------------------------@@ -193,10 +190,40 @@ class WavetableSynth final : public Instrument {// each id's string on the way past it.int32_t pluginParamIndexOfId(const std::string& id) const override;- std::vector<uint8_t> getState() const override;+ std::vector<uint8_t> getState() const override { return stateWith(true); }void setState(const uint8_t* data, int32_t size) override;std::shared_ptr<Instrument> clone() const override;+ // ---- custom wavetables (specs/053) -------------------------------------+ // Message thread. Each oscillator can hold one imported table (AuroraTable.h) and a+ // source flag that picks it over the built-in bank. A new table set is published+ // through a SnapshotHistory, so the audio thread reads it through a raw pointer+ // and never frees it; the flags are plain atomics. With no table or flag set, the+ // synth, its state blob and its sound are exactly what they were before.+ void setTable(int osc, std::shared_ptr<const AuroraTable> t); // also selects it and clears "missing"+ void clearTable(int osc); // back to the built-in+ void setSource(int osc, bool custom) {+ if (osc >= 0 && osc < 2) useCustom_[osc].store(custom ? 1 : 0, std::memory_order_relaxed);+ }+ void setMissing(int osc, const std::string& name);+ std::shared_ptr<const AuroraTable> table(int osc) const;+ bool useCustom(int osc) const {+ return osc >= 0 && osc < 2 && useCustom_[osc].load(std::memory_order_relaxed) != 0;+ }+ std::string missingName(int osc) const;+ // The state blob, with the table frames (getState) or without them (a project save,+ // which keeps each table as its own sample file). contracts/state-blob.md.+ std::vector<uint8_t> stateWith(bool includeTables) const;++ // Live follow (specs/053 data model § Scope telemetry): [0]/[1] the position Osc 1 /+ // Osc 2 of the most recently started sounding voice played at the end of the last+ // block (−1 = none), [2]/[3] the serials of the two tables (0 = none), [4] voices,+ // [5] which oscillators play their imported table. Then, from [kScopeN], the envelope+ // telemetry for the editor's graphs (#531): the newest sounding voice's Env 1 stage and+ // progress, then Env 2's (stage 0 A · 1 D · 2 S · 3 R · 4 none).+ static constexpr int32_t kScopeN = 6;+ int32_t scopeRead(float* out, int32_t maxN) const override;+void noteOn(int32_t pitch, float velocity) override;void noteOff(int32_t pitch) override;void allNotesOff() override;@@ -228,6 +255,7 @@ class WavetableSynth final : public Instrument {for (int i = 0; i < 2; ++i) sc1L[i] = sc2L[i] = sc1R[i] = sc2R[i] = 0.0;}int32_t modCount = 0;+ uint64_t seq = 0; // note-on order, for the scope's newest voiceVoiceExpr ex; // MPE bend / pressure / slidefloat exBendAt = 0.0f;double exBendMul = 1.0;@@ -301,6 +329,21 @@ class WavetableSynth final : public Instrument {const float b = t1[i0] + (t1[i1] - t1[i0]) * xf;return a + (b - a) * ff;}+ // The same interpolation for an imported table's mip level of `len` samples.+ static float readMorphSized(const float* t0, const float* t1, float ff, double phase, int len) {+ const double x = phase * len;+ int i0 = (int)x & (len - 1);+ int i1 = (i0 + 1) & (len - 1);+ const float xf = (float)(x - std::floor(x));+ const float a = t0[i0] + (t0[i1] - t0[i0]) * xf;+ const float b = t1[i0] + (t1[i1] - t1[i0]) * xf;+ return a + (b - a) * ff;+ }+ // oscStack over an imported table: the mip level is picked per read from the+ // fastest unison voice's increment and the warp mode's harmonic bias (research R4),+ // so a bright table played high stays below Nyquist.+ float oscStackCustom(double* ph, double inc, const AuroraTable& t, float pos, int mode, double warpAmt, int uniN,+ const double* detF, double maxDet, const float* panL, const float* panR, float norm, float& sideOut);static float harmAmp(int bank, float t, int n);// The four banks × sixteen frames are the same read-only 512 KB for every instance and// every clone, so they are built once, on first use, and handed out as a pointer.@@ -376,6 +419,17 @@ class WavetableSynth final : public Instrument {std::atomic<float> envTele_[4]; // Env 1 stage, progress, Env 2 stage, progressstd::atomic<float> pn_[kNumParams];+ // Custom tables (message thread publishes, audio thread reads live()).+ SnapshotHistory<const AuroraTableSet> tableSet_;+ std::atomic<uint8_t> useCustom_[2] = {0, 0};+ void publishSet(std::shared_ptr<AuroraTableSet> s) { tableSet_.publish(std::move(s)); }+ std::shared_ptr<AuroraTableSet> copySet() const {+ auto cur = tableSet_.current();+ return cur ? std::make_shared<AuroraTableSet>(*cur) : std::make_shared<AuroraTableSet>();+ }+ uint64_t noteSeq_ = 0;+ std::atomic<float> scope_[kScopeN] = {-1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f};+// Auto-sleep hangover (flag only — the engine skips render while idle).static constexpr uint64_t kIdleSamples = 16384;uint64_t quietSamples_ = 0;diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 85eb9501..8cde4da2 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -27,6 +27,7 @@#include "media/SampleBuffer.h"#include "Transport.h"#include "nota/nota_engine.h" // NotaNoteData+#include "devices/instruments/AuroraTable.h"#include <algorithm>#include <array>@@ -45,6 +46,8 @@namespace nota {+class WavetableSynth;+// Live MIDI event (UI/CoreMIDI -> audio), lock-free down-queue.class RackCore; // shared rack guts (RackInstrument / RackDevice; see RackCore.h)class ClipWarpStream; // offline warp-cache builder (WarpStream.h); held by unique_ptr in wb_@@ -776,6 +779,14 @@ class Engine {bool mosaicStatus(int32_t trackId, NotaMosaicStatus* out) const;int64_t mosaicZoneSampleId(int32_t trackId, int32_t zone) const;void instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg); // UI editing channel+ // Nota Aurora custom wavetables (specs/053). setTable with checkpoint publishes a+ // fresh Aurora holding the table (one undo step; sounding notes stop), without it the+ // live one takes it in place (a project load). Source and missing are in place, no undo.+ bool auroraSetTable(int32_t trackId, int32_t osc, std::shared_ptr<const AuroraTable> t, bool checkpoint);+ bool auroraClearTable(int32_t trackId, int32_t osc);+ bool auroraSetSource(int32_t trackId, int32_t osc, bool custom, bool checkpoint);+ bool auroraSetMissing(int32_t trackId, int32_t osc, const std::string& name);+ std::shared_ptr<const WavetableSynth> auroraOf(int32_t trackId) const; // null unless an Auroravoid instrumentActionUndoable(Instrument& inst, int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t id,int32_t iarg, float farg); // the action, plus its undo step when the edit state changedbool instrumentSetStateUndoable(int32_t trackId, int32_t deviceIndex, int32_t chain, const uint8_t* data,diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cppindex 519ae4ca..b090b481 100644--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp@@ -458,6 +458,77 @@ bool Engine::setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::strreturn true;}+// ---- Nota Aurora custom wavetables (specs/053) --------------------------------+std::shared_ptr<const WavetableSynth> Engine::auroraOf(int32_t trackId) const {+ auto t = findTrackAuthoring(trackId);+ if (!t || !t->instrument) return nullptr;+ auto w = std::dynamic_pointer_cast<WavetableSynth>(t->instrument);+ return w;+}++bool Engine::auroraSetTable(int32_t trackId, int32_t osc, std::shared_ptr<const AuroraTable> table, bool checkpoint) {+ if (osc < 0 || osc > 1 || !table) return false;+ auto old = findTrackAuthoring(trackId);+ auto* w = old && old->instrument ? dynamic_cast<WavetableSynth*>(old->instrument.get()) : nullptr;+ if (!w) return false;+ if (!checkpoint) {+ w->setTable(osc, std::move(table)); // a project load: in place, through the table history+ return true;+ }+ // Undoable: a fresh Aurora with the table (the clone shares the other slot), so undo+ // brings the old instrument, and its tables, back.+ auto fresh = std::static_pointer_cast<WavetableSynth>(w->clone());+ fresh->setTable(osc, std::move(table));+ fresh->presetTag = w->presetTag;+ auto nt = cloneTrack(*old);+ nt->instrument = fresh;+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::auroraClearTable(int32_t trackId, int32_t osc) {+ if (osc < 0 || osc > 1) return false;+ auto old = findTrackAuthoring(trackId);+ auto* w = old && old->instrument ? dynamic_cast<WavetableSynth*>(old->instrument.get()) : nullptr;+ if (!w) return false;+ auto fresh = std::static_pointer_cast<WavetableSynth>(w->clone());+ fresh->clearTable(osc);+ fresh->presetTag = w->presetTag;+ auto nt = cloneTrack(*old);+ nt->instrument = fresh;+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::auroraSetSource(int32_t trackId, int32_t osc, bool custom, bool checkpoint) {+ auto t = findTrackAuthoring(trackId);+ auto* w = t && t->instrument ? dynamic_cast<WavetableSynth*>(t->instrument.get()) : nullptr;+ if (!w || osc < 0 || osc > 1) return false;+ if (!checkpoint) {+ w->setSource(osc, custom); // a load: in place, lock-free+ w->wake();+ return true;+ }+ if (w->useCustom(osc) == custom) return true; // nothing to undo+ // Undoable, like set_table: a fresh Aurora with the flag flipped, so undo brings back the+ // instrument that still holds the old flag (and redo the new one).+ auto fresh = std::static_pointer_cast<WavetableSynth>(w->clone());+ fresh->setSource(osc, custom);+ fresh->presetTag = w->presetTag;+ auto nt = cloneTrack(*t);+ nt->instrument = fresh;+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::auroraSetMissing(int32_t trackId, int32_t osc, const std::string& name) {+ auto t = findTrackAuthoring(trackId);+ auto* w = t && t->instrument ? dynamic_cast<WavetableSynth*>(t->instrument.get()) : nullptr;+ if (!w || osc < 0 || osc > 1) return false;+ w->setMissing(osc, name);+ return true;+}+bool Engine::setTrackGrainSample(int32_t trackId, const std::string& path, int32_t rootNote) {auto old = findTrackAuthoring(trackId);auto* gr = old && old->instrument ? dynamic_cast<GrainSynth*>(old->instrument.get()) : nullptr;diff --git a/src/native/nota.engine/src/engine/SnapshotHistory.h b/src/native/nota.engine/src/engine/SnapshotHistory.hindex 72b59d2c..18458220 100644--- a/src/native/nota.engine/src/engine/SnapshotHistory.h+++ b/src/native/nota.engine/src/engine/SnapshotHistory.h@@ -30,6 +30,9 @@ template <class T> class SnapshotHistory {// that read it.T* live() const { return live_.load(std::memory_order_acquire); }+ // The snapshot last published (message thread), e.g. for a clone to share.+ std::shared_ptr<T> current() const { return current_; }+// Publish `next` and retire the current one; frees retirees no render can still hold.void publish(std::shared_ptr<T> next) {live_.store(next.get(), std::memory_order_seq_cst);diff --git a/tests/Nota.SmokeTest/ArticulationEngineTests.cs b/tests/Nota.SmokeTest/ArticulationEngineTests.csindex c998ab2b..5a9a4e0e 100644--- a/tests/Nota.SmokeTest/ArticulationEngineTests.cs+++ b/tests/Nota.SmokeTest/ArticulationEngineTests.cs@@ -514,8 +514,8 @@ internal static class ArticulationEngineTestsforeach (var r in Playback()) yield return r;var old = ProjectMigrations.Migrate(new JsonObject { ["formatVersion"] = 29 });- yield return (old["formatVersion"]?.GetValue<int>() == ProjectService.CurrentFormatVersion && ProjectService.CurrentFormatVersion == 30+ yield return (old["formatVersion"]?.GetValue<int>() == ProjectService.CurrentFormatVersion && ProjectService.CurrentFormatVersion >= 30&& new TrackDto().MidiOffsetMs is null && new NoteDto().Articulation is null && new NoteDto().ToNote().ArticulationId == 0,- "articulations: a v29 project migrates to v30 with no offsets and no articulations");+ "articulations: a v29 project migrates past v30 with no offsets and no articulations");}}diff --git a/tests/Nota.SmokeTest/AuroraFixtures.cs b/tests/Nota.SmokeTest/AuroraFixtures.csnew file mode 100644index 00000000..94bd6376--- /dev/null+++ b/tests/Nota.SmokeTest/AuroraFixtures.cs@@ -0,0 +1,205 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Test material for Nota Aurora's custom wavetables (specs/053, quickstart § 2 and § 4):+// generated, deterministic files for each way a file becomes a table, and the projects the+// UI budget is measured with. `--aurora-fixtures <dir>` writes the files;+// `--aurora-ui-fixture <dir> [--builtin]` writes the measurement project: <dir>/baseline.nota+// with --builtin (the built-in tables, stamped format 27 so the base build opens it), else+// <dir>/scenario.nota (the same project with a generated 256-frame table on both+// oscillators of every Aurora).++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class AuroraFixtures+{+ public const int Frame = 2048;++ /// <summary>Writes the quickstart § 2 files into <paramref name="dir"/>; returns their paths by name.</summary>+ public static Dictionary<string, string> Write(string dir)+ {+ Directory.CreateDirectory(dir);+ var paths = new Dictionary<string, string>();+ string P(string name) => paths[name] = Path.Combine(dir, name);++ WriteMono(P("cycle-2048.wav"), Saw(Frame, 1));+ AuroraTableWav.Write(P("table-64x2048.wav"), Morph(64));+ AuroraTableWav.Write(P("table-300x2048.wav"), Morph(300)); // clm: 300 frames, cut to 256+ WriteMono(P("table-256x2048.wav"), Morph(256)); // no clm: still a wavetable+ WriteMono(P("rec-40s-2048x.wav"), Sweep(Frame * 862, 44100)); // 40 s that lands on a multiple of 2048+ WriteMono(P("cycle-600.wav"), Saw(600, 1));+ WriteMono(P("long-90s.wav"), Sweep(44100 * 90, 44100));+ WriteMono(P("silence.wav"), new float[44100]);+ WriteMono(P("sweep-3s.wav"), Sweep(44100 * 3, 44100));+ // A two-second stereo "vowel": a buzz through two moving formants, as FLAC.+ using (var enc = new NativeEncoder(P("vowel-2s.flac"), 44100, 2, WavBitDepth.Pcm16))+ {+ var v = Vowel(44100 * 2, 44100);+ var st = new float[v.Length * 2];+ for (int i = 0; i < v.Length; i++) { st[2 * i] = v[i]; st[2 * i + 1] = v[i] * 0.8f; }+ enc.WriteFrames(st, v.Length);+ enc.Close();+ }+ File.WriteAllBytes(P("broken.wav"), "RIFF\u0010\0\0\0WAVEjunkjunk"u8.ToArray());+ File.WriteAllBytes(P("x.aiff"), "FORM\0\0\0\u0004AIFF"u8.ToArray());+ return paths;+ }++ /// <summary>One band-limited saw cycle of n samples (harmonics up to `n/2`), peak about 0.6.</summary>+ public static float[] Saw(int n, int cycles)+ {+ var x = new float[n];+ int top = Math.Min(n / 2 - 1, 512);+ for (int i = 0; i < n; i++)+ {+ double s = 0, ph = 2 * Math.PI * cycles * i / n;+ for (int h = 1; h <= top; h++) s += Math.Sin(h * ph) / h;+ x[i] = (float)(0.35 * s);+ }+ return x;+ }++ /// <summary>A bright table: frame f of `count` moves from a saw to a pulse; every+ /// harmonic up to 1023 present, so a high note would fold back without band-limiting.</summary>+ public static float[] Morph(int count)+ {+ var t = new float[count * Frame];+ var saw = new double[Frame];+ var sq = new double[Frame];+ for (int i = 0; i < Frame; i++)+ {+ double ph = (i + 0.5) / Frame;+ saw[i] = 2 * ph - 1; // naive: full bandwidth on purpose+ sq[i] = ph < 0.5 ? 0.8 : -0.8;+ }+ for (int f = 0; f < count; f++)+ {+ double m = count > 1 ? (double)f / (count - 1) : 0;+ for (int i = 0; i < Frame; i++) t[f * Frame + i] = (float)(saw[i] * (1 - m) + sq[i] * m) * 0.7f;+ }+ return t;+ }++ /// <summary>An exponential sine sweep from 60 Hz to 6 kHz, at 0.5.</summary>+ public static float[] Sweep(int n, int sr)+ {+ var x = new float[n];+ double f0 = 60, f1 = 6000, T = (double)n / sr, k = Math.Log(f1 / f0);+ for (int i = 0; i < n; i++)+ {+ double t = (double)i / sr;+ double ph = 2 * Math.PI * f0 * T / k * (Math.Exp(t / T * k) - 1);+ x[i] = (float)(0.5 * Math.Sin(ph));+ }+ return x;+ }++ private static float[] Vowel(int n, int sr)+ {+ var x = new float[n];+ double ph = 0;+ for (int i = 0; i < n; i++)+ {+ double t = (double)i / sr, m = t / ((double)n / sr);+ ph += 110.0 / sr;+ double s = 0;+ for (int h = 1; h <= 60; h++)+ {+ double fh = 110.0 * h;+ double a1 = Math.Exp(-Math.Pow((fh - (700 - 400 * m)) / 120, 2));+ double a2 = Math.Exp(-Math.Pow((fh - (1200 + 900 * m)) / 180, 2));+ s += (a1 + 0.6 * a2 + 0.02) * Math.Sin(2 * Math.PI * h * ph);+ }+ x[i] = (float)(0.3 * s);+ }+ return x;+ }++ public static void WriteMono(string path, float[] samples)+ {+ using var w = new Nota.Infrastructure.WavWriter(path, 44100, 1, WavBitDepth.Float32);+ w.WriteFrames(samples, samples.Length);+ w.Close();+ }++ // ---- the UI measurement project (quickstart § 4) ----++ /// <summary>Four Auroras on Formant / Chroma with both positions under LFO modulation, and a+ /// four-bar six-note chord loop. Without <paramref name="builtin"/> each oscillator of each+ /// Aurora also holds a generated 256-frame table.</summary>+ public static int WriteUiProject(string dir, bool builtin)+ {+ using var eng = new NotaEngine();+ eng.SetBpm(120);+ var tables = builtin ? null : new[] { Morph(256), Sweep256() };+ for (int k = 0; k < 4; k++)+ {+ int t = eng.AddWavetableSynthTrack();+ Set(eng, t, "table", 0.667f); // Osc 1 Formant+ Set(eng, t, "osc2on", 1f);+ Set(eng, t, "osc2table", 1f); // Osc 2 Chroma+ Set(eng, t, "osc2level", 0.6f);+ Set(eng, t, "lfo1rate", 0.5f); // ≈ 1 Hz+ Set(eng, t, "lfo1depth", 1f);+ Set(eng, t, "lfo2rate", 0.6157f); // ≈ 2 Hz+ Set(eng, t, "lfo2depth", 1f);+ Set(eng, t, "mtx2_2", 0.9f); // LFO 1 → Position+ Set(eng, t, "mtx3_2", 0.8f); // LFO 2 → Position+ int clip = eng.AddMidiClip(t, 0, 16);+ eng.SetClipNotes(t, clip, new[]+ {+ new NotaNote(48, 0, 16, 0.8f), new NotaNote(55, 0, 16, 0.7f), new NotaNote(60, 0, 16, 0.7f),+ new NotaNote(64, 0, 16, 0.7f), new NotaNote(67, 0, 16, 0.7f), new NotaNote(71, 0, 16, 0.6f),+ });+ if (tables is null) continue;+ for (int o = 0; o < 2; o++)+ {+ if (eng.AuroraTableFromFrames(tables[o], 256, o == 0 ? "morph-256" : "sweep-256", 0, out var h) != 0) return 1;+ try { eng.AuroraSetTable(t, o, h, undoable: false); }+ finally { eng.AuroraTableFree(h); }+ }+ }+ eng.SetLoop(true, 0, 16); // the four bars loop+ var warnings = new List<string>();+ var doc = ProjectService.Capture(eng, new TransportState(120.0, 1.0, false, true), warnings);+ string bundle = Path.Combine(dir, builtin ? "baseline.nota" : "scenario.nota");+ ProjectService.Save(doc, bundle, eng);+ if (builtin)+ {+ // Nothing in it needs format 30, so stamp it 27: the base build opens it too.+ string mf = Path.Combine(bundle, ProjectService.ManifestName);+ var node = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(mf))!.AsObject();+ node["formatVersion"] = 27;+ File.WriteAllText(mf, node.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));+ }+ Console.WriteLine($"wrote {bundle} ({(builtin ? "built-in tables, format 27" : $"256-frame tables on both oscillators, format {doc.FormatVersion}")})");+ return 0;+ }++ private static float[] Sweep256()+ {+ // 256 frames, frame f a sine at harmonic 1 + f / 4 plus its octave: a slow spectral sweep.+ var t = new float[256 * Frame];+ for (int f = 0; f < 256; f++)+ {+ double h = 1 + f / 4.0;+ for (int i = 0; i < Frame; i++)+ {+ double ph = 2 * Math.PI * i / Frame;+ t[f * Frame + i] = (float)(0.6 * Math.Sin(Math.Round(h) * ph) + 0.3 * Math.Sin(2 * Math.Round(h) * ph));+ }+ }+ return t;+ }++ private static void Set(NotaEngine e, int t, string id, float v)+ {+ int n = e.PluginParamCount(t, -1);+ for (int i = 0; i < n; i++)+ if (e.PluginParamId(t, -1, i) == id) { e.PluginParamSet(t, -1, i, v); return; }+ throw new InvalidOperationException($"Aurora has no parameter '{id}'");+ }+}diff --git a/tests/Nota.SmokeTest/AuroraTableTests.cs b/tests/Nota.SmokeTest/AuroraTableTests.csnew file mode 100644index 00000000..e3540b41--- /dev/null+++ b/tests/Nota.SmokeTest/AuroraTableTests.cs@@ -0,0 +1,616 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Aurora custom wavetables (specs/053): how a file becomes a table, the undo and source+// rules, the state blob and its trailer, copies and duplicates, the sound (an imported copy+// of a built-in frame sounds like it; a bright table played high does not fold back), the+// project v29 round trip (bit-identical render, one file per table, missing tables, v27+// documents), presets, and the live-follow telemetry. An Aurora without a table keeps its+// old state blob byte for byte and the factory sounds pass the null gate.+// Also runnable alone: `--aurora-tables`.++using System.Text.Json.Nodes;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class AuroraTableTests+{+ private const int Sr = 48000, Frame = 2048, Params = 162; // 156 + the six envelope-shape params appended by #531++ public static IEnumerable<(bool ok, string label)> Run()+ {+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-aurora-" + Guid.NewGuid().ToString("N"));+ Dictionary<string, string> fx;+ try { fx = AuroraFixtures.Write(Path.Combine(dir, "fixtures")); }+ catch (Exception ex) { fx = new(); Console.WriteLine($" (fixtures failed: {ex.Message})"); }+ yield return (fx.Count >= 10, $"aurora tables: fixtures written ({fx.Count})");+ if (fx.Count < 10) yield break;+ try+ {+ foreach (var r in Regression()) yield return r;+ foreach (var r in Conditioning(fx)) yield return r;+ foreach (var r in UndoAndSource(fx)) yield return r;+ foreach (var r in State(fx)) yield return r;+ foreach (var r in Sound()) yield return r;+ foreach (var r in Project(fx, dir)) yield return r;+ foreach (var r in Presets(fx)) yield return r;+ foreach (var r in Scope(fx)) yield return r;+ }+ finally+ {+ try { Directory.Delete(dir, recursive: true); } catch { /* best effort */ }+ }+ }++ // ---- T017: nothing changes for an Aurora without a table ----+ private static IEnumerable<(bool, string)> Regression()+ {+ using var e = new NotaEngine();+ int t = e.AddWavetableSynthTrack();+ var blob = e.GetPluginState(t, -1);+ yield return (blob.Length == Params * 4, $"aurora tables: a fresh Aurora's state is the {Params}-float layout ({blob.Length} bytes)");+ yield return (e.AuroraState(t, false).AsSpan().SequenceEqual(blob) && e.AuroraState(t, true).AsSpan().SequenceEqual(blob),+ "aurora tables: with no table the blob is the same with or without tables");+ bool paramsOnly = true;+ for (int i = 0; i < Params && paramsOnly; i++)+ paramsOnly = BitConverter.ToSingle(blob, i * 4) == e.PluginParamGet(t, -1, i);+ yield return (paramsOnly, "aurora tables: the blob is exactly the parameters, in order");++ var h = Build(e, Saw64(), 1, "saw");+ e.AuroraSetTable(t, 0, h); e.AuroraTableFree(h);+ e.AuroraClearTable(t, 0);+ yield return (e.GetPluginState(t, -1).AsSpan().SequenceEqual(blob),+ "aurora tables: import then remove leaves the blob byte-identical to before");++ // The built-in path is untouched: a table that is loaded but not played changes nothing.+ var a = RenderChord(setup: null);+ var b = RenderChord(setup: (eng, tr) =>+ {+ var th = Build(eng, AuroraFixtures.Morph(64), 64, "morph");+ eng.AuroraSetTable(tr, 0, th, undoable: false); eng.AuroraTableFree(th);+ eng.AuroraSetSource(tr, 0, false);+ });+ double res = ResidualDb(a, b);+ yield return (a.Length > 0 && res < -120, $"aurora tables: a held-but-unplayed table renders bit-identically to none (residual {res:0} dBFS)");+ }++ // ---- T025: files to tables ----+ private static IEnumerable<(bool, string)> Conditioning(Dictionary<string, string> fx)+ {+ using var e = new NotaEngine();+ (int code, AuroraTableInfo info, float[] frames) B(string name)+ {+ int r = e.AuroraTableBuild(fx[name], out var h);+ if (r != 0) return (r, default, []);+ try { return (r, e.AuroraTableInfoOf(h), e.AuroraTableFrames(h)); }+ finally { e.AuroraTableFree(h); }+ }++ var c = B("cycle-2048.wav");+ yield return (c.code == 0 && c.info is { Frames: 1, Origin: 1 }, $"aurora tables: a 2048-sample file is one cycle ({c.code}, {c.info.Frames} frames, origin {c.info.Origin})");+ var s6 = B("cycle-600.wav");+ yield return (s6.code == 0 && s6.info is { Frames: 1, Origin: 1 } && s6.frames.Length == Frame,+ $"aurora tables: a 600-sample cycle is resampled to one 2048 frame ({s6.info.Frames})");+ var t64 = B("table-64x2048.wav");+ yield return (t64.code == 0 && t64.info is { Frames: 64, Origin: 0, TruncatedFrames: false },+ $"aurora tables: a clm wavetable keeps its 64 frames ({t64.info.Frames}, origin {t64.info.Origin})");+ var t300 = B("table-300x2048.wav");+ yield return (t300.code == 0 && t300.info is { Frames: 256, TruncatedFrames: true },+ $"aurora tables: 300 frames are cut to 256 and say so ({t300.info.Frames}, truncated {t300.info.TruncatedFrames})");+ var t256 = B("table-256x2048.wav");+ yield return (t256.code == 0 && t256.info is { Frames: 256, Origin: 0, TruncatedFrames: false },+ $"aurora tables: 256 × 2048 samples with no clm chunk is a wavetable ({t256.info.Frames}, origin {t256.info.Origin})");+ var r40 = B("rec-40s-2048x.wav");+ yield return (r40.code == 0 && r40.info is { Frames: 16, Origin: 2, TruncatedLength: false },+ $"aurora tables: a 40 s recording on a multiple of 2048 is a recording, not 256 raw frames ({r40.info.Frames}, origin {r40.info.Origin})");+ var lng = B("long-90s.wav");+ yield return (lng.code == 0 && lng.info is { Frames: 16, Origin: 2, TruncatedLength: true },+ $"aurora tables: a 90 s recording gives 16 frames from its first 60 s ({lng.info.Frames}, origin {lng.info.Origin}, cut {lng.info.TruncatedLength})");+ var vow = B("vowel-2s.flac");+ yield return (vow.code == 0 && vow.info is { Frames: 16, Origin: 2, TruncatedLength: false },+ $"aurora tables: a stereo FLAC recording gives 16 frames ({vow.code}, {vow.info.Frames})");+ yield return (B("silence.wav").code == AuroraTableResult.ErrSilent, "aurora tables: silence is refused as silent");+ yield return (B("broken.wav").code == AuroraTableResult.ErrDecode, "aurora tables: a broken WAV is refused as unreadable");+ yield return (B("x.aiff").code == AuroraTableResult.ErrFormat, "aurora tables: AIFF is refused as an unsupported format");+ yield return (e.AuroraTableBuild(Path.Combine(Path.GetDirectoryName(fx["x.aiff"])!, "nope.wav"), out _) == AuroraTableResult.ErrDecode,+ "aurora tables: a file that is not there is refused as unreadable");++ foreach (var (name, r) in new[] { ("cycle", c), ("64-frame", t64), ("recording", lng), ("flac", vow) })+ {+ double worstMean = 0, peak = 0;+ int n = r.frames.Length / Frame;+ for (int f = 0; f < n; f++)+ {+ double m = 0;+ for (int i = 0; i < Frame; i++) { m += r.frames[f * Frame + i]; peak = Math.Max(peak, Math.Abs(r.frames[f * Frame + i])); }+ worstMean = Math.Max(worstMean, Math.Abs(m / Frame));+ }+ yield return (n > 0 && worstMean < 1e-6 && Math.Abs(peak - 1.0) < 1e-6,+ $"aurora tables: {name} frames have no DC and the table peaks at 1.0 (mean {worstMean:0.0e0}, peak {peak:0.000000})");+ }++ // A recording's loop seam is no bigger a step than the frame's own motion.+ var sw = B("sweep-3s.wav");+ bool seamOk = sw.code == 0;+ double worstRatio = 0;+ for (int f = 0; seamOk && f < sw.info.Frames; f++)+ {+ var steps = new double[Frame - 1];+ for (int i = 0; i < Frame - 1; i++) steps[i] = Math.Abs(sw.frames[f * Frame + i + 1] - sw.frames[f * Frame + i]);+ Array.Sort(steps);+ double median = steps[steps.Length / 2], max = steps[^1];+ double seam = Math.Abs(sw.frames[f * Frame] - sw.frames[f * Frame + Frame - 1]);+ worstRatio = Math.Max(worstRatio, seam / Math.Max(median, 1e-9));+ seamOk = seam <= Math.Max(2 * median, max);+ }+ yield return (seamOk, $"aurora tables: each recording frame loops without a jump (worst seam {worstRatio:0.0}× the median step)");+ }++ // ---- T026: undo, and the source switch ----+ private static IEnumerable<(bool, string)> UndoAndSource(Dictionary<string, string> fx)+ {+ using var e = new NotaEngine();+ int t = e.AddWavetableSynthTrack();+ Render(e, 512);+ e.AuroraTableBuild(fx["table-64x2048.wav"], out var h);+ bool set = e.AuroraSetTable(t, 0, h); e.AuroraTableFree(h);+ e.TryGetAuroraTableInfo(t, 0, out var i1);+ yield return (set && i1 is { Frames: 64, UseCustom: true } && i1.Name == "table-64x2048.wav",+ $"aurora tables: an import holds the table and plays it ({i1.Frames}, \"{i1.Name}\")");+ e.Undo();+ e.TryGetAuroraTableInfo(t, 0, out var i2);+ yield return (i2.Frames == 0 && !i2.UseCustom, "aurora tables: undo takes the import back");+ e.Redo();+ e.TryGetAuroraTableInfo(t, 0, out var i3);+ yield return (i3.Frames == 64 && i3.Serial == i1.Serial && i3.UseCustom, "aurora tables: redo brings the same table back");++ e.AuroraClearTable(t, 0);+ e.TryGetAuroraTableInfo(t, 0, out var i4);+ e.Undo();+ e.TryGetAuroraTableInfo(t, 0, out var i5);+ yield return (i4.Frames == 0 && i5.Frames == 64 && i5.Serial == i1.Serial, "aurora tables: remove is one undo step");++ // The source switch is in place: voices keep sounding and it adds no undo step.+ e.TrackNoteOn(t, 60, 0.8f);+ Render(e, 2048);+ int before = e.InstrumentVoiceCount(t);+ e.AuroraSetSource(t, 0, false);+ Render(e, 512);+ e.TryGetAuroraTableInfo(t, 0, out var i6);+ int after = e.InstrumentVoiceCount(t);+ yield return (!i6.UseCustom && i6.Frames == 64 && before > 0 && after == before,+ $"aurora tables: switching to the built-in keeps the table and the held voice ({before} → {after})");+ e.AuroraSetSource(t, 0, true);+ e.Undo(); // takes back the import itself: the switches added nothing to undo+ e.TryGetAuroraTableInfo(t, 0, out var i7);+ yield return (i7.Frames == 0, "aurora tables: the source switch adds no undo step");+ e.TrackNoteOff(t, 60);++ // Picking a built-in bank while the imported table plays: the bank and the switch+ // off the import are one undo step, and redo makes both again (the card's path).+ using var g = new NotaEngine();+ int u = g.AddWavetableSynthTrack();+ int tp = -1;+ for (int i = 0; i < g.PluginParamCount(u, -1); i++) if (g.PluginParamId(u, -1, i) == "table") tp = i;+ float bank0 = g.PluginParamGet(u, -1, tp);+ g.AuroraTableBuild(fx["table-64x2048.wav"], out var h2);+ g.AuroraSetTable(u, 0, h2); g.AuroraTableFree(h2);+ AuroraTableImporter.PickBank(g, u, 0, tp, "table", 1f);+ g.TryGetAuroraTableInfo(u, 0, out var p1);+ float bank1 = g.PluginParamGet(u, -1, tp);+ yield return (!p1.UseCustom && p1.Frames == 64 && bank1 == 1f,+ $"aurora tables: picking a bank leaves the imported table (custom {p1.UseCustom}, bank {bank1})");+ g.Undo();+ g.TryGetAuroraTableInfo(u, 0, out var p2);+ float bank2 = g.PluginParamGet(u, -1, tp);+ yield return (p2.UseCustom && p2.Frames == 64 && bank2 == bank0,+ $"aurora tables: undo brings back the old bank and the imported table together (custom {p2.UseCustom}, bank {bank2})");+ g.Redo();+ g.TryGetAuroraTableInfo(u, 0, out var p3);+ float bank3 = g.PluginParamGet(u, -1, tp);+ yield return (!p3.UseCustom && p3.Frames == 64 && bank3 == 1f,+ $"aurora tables: redo picks the bank and leaves the import again (custom {p3.UseCustom}, bank {bank3})");+ g.Undo(); g.Undo();+ g.TryGetAuroraTableInfo(u, 0, out var p4);+ yield return (p4.Frames == 0 && g.PluginParamGet(u, -1, tp) == bank0, "aurora tables: one more undo takes the import back");+ // The imported name in the drop-down is an undo step of its own.+ g.Redo(); g.Redo();+ g.AuroraSetSource(u, 0, true, undoable: true);+ g.TryGetAuroraTableInfo(u, 0, out var p5);+ g.Undo();+ g.TryGetAuroraTableInfo(u, 0, out var p6);+ yield return (p5.UseCustom && !p6.UseCustom && g.PluginParamGet(u, -1, tp) == 1f,+ $"aurora tables: going back to the imported table is one undo step ({p5.UseCustom} → {p6.UseCustom})");+ }++ // ---- T027: the state blob, copies and duplicates ----+ private static IEnumerable<(bool, string)> State(Dictionary<string, string> fx)+ {+ using var e = new NotaEngine();+ int t = e.AddWavetableSynthTrack();+ e.AuroraTableBuild(fx["table-64x2048.wav"], out var h);+ e.AuroraSetTable(t, 0, h); e.AuroraSetTable(t, 1, h); e.AuroraTableFree(h);+ e.AuroraSetSource(t, 1, false);+ e.TryGetAuroraTableInfo(t, 0, out var src0);+ var frames0 = e.AuroraTableRead(t, 0);+ var full = e.AuroraState(t, true);+ var lean = e.AuroraState(t, false);+ yield return (full.Length > Params * 4 + 64 * Frame * 4 && full.Length < Params * 4 + 2 * 64 * Frame * 4,+ $"aurora tables: one table in both slots is stored once ({full.Length} bytes)");+ yield return (lean.Length > Params * 4 && lean.Length < Params * 4 + 64,+ $"aurora tables: the project blob leaves the frames out ({lean.Length} bytes)");++ int t2 = e.AddWavetableSynthTrack();+ e.SetPluginState(t2, -1, full);+ e.TryGetAuroraTableInfo(t2, 0, out var d0);+ e.TryGetAuroraTableInfo(t2, 1, out var d1);+ yield return (d0.Hash == src0.Hash && d0.Frames == 64 && d0.UseCustom && d1.Hash == src0.Hash && !d1.UseCustom+ && e.AuroraTableRead(t2, 0).AsSpan().SequenceEqual(frames0) && d0.Name == src0.Name,+ "aurora tables: the blob restores both tables, their frames, names and sources");+ yield return (e.GetPluginState(t2, -1).AsSpan().SequenceEqual(full), "aurora tables: a restored blob saves back byte for byte");++ var plain = full.AsSpan(0, Params * 4).ToArray();+ e.SetPluginState(t2, -1, plain);+ e.TryGetAuroraTableInfo(t2, 0, out var p0);+ yield return (p0.Frames == 0 && !p0.UseCustom, "aurora tables: a blob without a trailer puts both oscillators back on the built-in");++ e.SetPluginState(t2, -1, full);+ var future = (byte[])full.Clone();+ int sec = full.Length - 8 - BitConverter.ToInt32(full, full.Length - 8);+ future[sec + 4] = 2; // version 2+ future[0] = 0; future[1] = 0; future[2] = 0; future[3] = 0; // param 0 = 0.0+ e.PluginParamSet(t2, -1, 0, 0.5f);+ e.SetPluginState(t2, -1, future);+ e.TryGetAuroraTableInfo(t2, 0, out var f0);+ yield return (f0.Frames == 64 && e.PluginParamGet(t2, -1, 0) == 0f,+ "aurora tables: a newer trailer version is skipped: parameters load, the tables stay");++ int dup = e.DuplicateTrack(t);+ e.TryGetAuroraTableInfo(dup, 0, out var u0);+ e.TryGetAuroraTableInfo(dup, 1, out var u1);+ yield return (dup > 0 && u0.Hash == src0.Hash && u0.UseCustom && u1.Frames == 64 && !u1.UseCustom,+ "aurora tables: a duplicated track keeps both tables and sources");++ bool copied = e.CopyInstrument(t);+ int t3 = e.AddWavetableSynthTrack();+ int pasted = copied ? e.PasteInstrument(t3) : -1;+ e.TryGetAuroraTableInfo(t3, 0, out var c0);+ e.TryGetAuroraTableInfo(t3, 1, out var c1);+ yield return (copied && pasted == 0 && c0.Hash == src0.Hash && c0.UseCustom && !c1.UseCustom,+ $"aurora tables: a copied and pasted Aurora keeps its tables (paste {pasted})");++ // An Aurora grouped into an Instrument Rack keeps its table, through the rack's blob too.+ int rackAddr = e.GroupDevices(t3, 0, 0, true, 0, 0);+ var rackBlob = e.GetPluginState(t3, -1);+ int t4 = e.AddInstrumentRackTrack();+ e.SetPluginState(t4, -1, rackBlob);+ int un = e.UngroupRack(t4, DeviceFamily.Instrument, -1, out _);+ e.TryGetAuroraTableInfo(t4, 0, out var r0);+ yield return (rackAddr == -1 && e.TrackInstrumentKind(t3) == 3 && un >= 0 && r0.Hash == src0.Hash && r0.UseCustom,+ $"aurora tables: an Aurora in a rack chain keeps its table through the rack's state (group {rackAddr}, ungroup {un})");+ }++ // ---- T028: the sound ----+ private static IEnumerable<(bool, string)> Sound()+ {+ // The built-in Analog's last frame (harmonics 1/n up to 64), imported as a cycle,+ // sounds like the built-in at Position 1.+ var cycle = new float[Frame];+ double peak = 0;+ for (int i = 0; i < Frame; i++)+ {+ double s = 0, ph = (double)i / Frame;+ for (int n = 1; n <= 64; n++) s += 1.0 / n * Math.Sin(2 * Math.PI * n * ph);+ cycle[i] = (float)s; peak = Math.Max(peak, Math.Abs(s));+ }+ for (int i = 0; i < Frame; i++) cycle[i] = (float)(cycle[i] / peak);+ var builtin = RenderNote(48, (eng, t) => Set(eng, t, "position", 1f));+ var imported = RenderNote(48, (eng, t) =>+ {+ Set(eng, t, "position", 1f);+ var h = Build(eng, cycle, 1, "analog-15");+ eng.AuroraSetTable(t, 0, h, undoable: false); eng.AuroraTableFree(h);+ });+ double rel = RelativeDb(builtin, imported);+ yield return (rel < -40, $"aurora tables: an imported copy of a built-in frame sounds like it at C3 ({rel:0} dB difference)");++ // A bright table at C7, Warp Off: what folds back stays 60 dB under the harmonics.+ var hi = RenderNote(96, (eng, t) =>+ {+ Set(eng, t, "cutoff", 1f); Set(eng, t, "unison", 0f);+ var h = Build(eng, AuroraFixtures.Morph(64), 64, "bright");+ eng.AuroraSetTable(t, 0, h, undoable: false); eng.AuroraTableFree(h);+ });+ double alias = AliasDb(hi, 440.0 * Math.Pow(2, (96 - 69) / 12.0));+ yield return (alias <= -60, $"aurora tables: a bright table at C7 does not fold back ({alias:0} dB alias energy vs harmonics)");+ }++ // ---- T029: project v29 ----+ private static IEnumerable<(bool, string)> Project(Dictionary<string, string> fx, string root)+ {+ var transport = new TransportState(120.0, 1.0, false, false);+ string bundle = Path.Combine(root, "p.nota");+ float[] a, b;+ string[] wavs;+ int warnCount;+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int t1 = Chord(e), t2 = Chord(e);+ foreach (var (t, o, file) in new[] { (t1, 0, "vowel-2s.flac"), (t1, 1, "table-64x2048.wav"), (t2, 0, "vowel-2s.flac") })+ {+ e.AuroraTableBuild(fx[file], out var h);+ e.AuroraSetTable(t, o, h); e.AuroraTableFree(h);+ }+ Set(e, t1, "osc2on", 1f); Set(e, t1, "osc2level", 0.7f);+ e.AuroraSetSource(t2, 0, false);+ a = RenderSong(e);+ var w = new List<string>();+ var doc = ProjectService.Capture(e, transport, w);+ ProjectService.Save(doc, bundle, e);+ warnCount = w.Count;+ wavs = Directory.GetFiles(Path.Combine(bundle, "samples")).Select(Path.GetFileName).OfType<string>().ToArray();+ }+ var json = JsonNode.Parse(File.ReadAllText(Path.Combine(bundle, ProjectService.ManifestName)))!;+ yield return (json["formatVersion"]?.GetValue<int>() == 31 && warnCount == 0, $"aurora tables: projects save as format 31 ({json["formatVersion"]})");+ yield return (wavs.Length == 2, $"aurora tables: two Auroras with the same table share one file ({wavs.Length} tables for 3 slots)");+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ var w = ProjectService.Apply(ProjectService.Load(bundle), e, bundle);+ b = RenderSong(e);+ var ids = TrackIds(e);+ e.TryGetAuroraTableInfo(ids[1], 0, out var s2);+ yield return (w.Count == 0 && s2 is { Frames: 16, UseCustom: false },+ $"aurora tables: reopening restores tables and sources ({w.Count} warnings)");+ }+ double res = ResidualDb(a, b);+ yield return (a.Length > 0 && res < -120, $"aurora tables: import → save → reopen renders bit-identically (residual {res:0} dBFS)");++ // A table file gone missing: the project opens, says so, and plays the built-in.+ foreach (var f in Directory.GetFiles(Path.Combine(bundle, "samples"))) File.Delete(f);+ {+ using var e = new NotaEngine();+ var w = ProjectService.Apply(ProjectService.Load(bundle), e, bundle);+ var ids = TrackIds(e);+ e.TryGetAuroraTableInfo(ids[0], 0, out var m0);+ bool says = w.Any(x => x.Contains("Aurora Osc 1 table \"vowel-2s.flac\" is missing"));+ yield return (says && m0 is { Missing: true, Frames: 0, UseCustom: false } && m0.Name == "vowel-2s.flac",+ $"aurora tables: a missing table warns and plays the built-in ({w.Count} warnings: {w.FirstOrDefault()})");+ // Saving again keeps the name, so the warning repeats until the table is imported again.+ string again = Path.Combine(root, "p2.nota");+ ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), again, e);+ using var e2 = new NotaEngine();+ var w2 = ProjectService.Apply(ProjectService.Load(again), e2, again);+ yield return (w2.Count(x => x.Contains("is missing")) == 3, $"aurora tables: a re-saved project still names its missing tables ({w2.Count})");+ }++ // A v27 project (before custom tables) loads as it did and migrates.+ {+ using var e = new NotaEngine();+ Chord(e);+ string old = Path.Combine(root, "v27.nota");+ ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), old, e);+ string mf = Path.Combine(old, ProjectService.ManifestName);+ var node = JsonNode.Parse(File.ReadAllText(mf))!.AsObject();+ node["formatVersion"] = 27;+ File.WriteAllText(mf, node.ToJsonString());+ var doc = ProjectService.Load(old);+ using var e2 = new NotaEngine();+ var w = ProjectService.Apply(doc, e2, old);+ int id = TrackIds(e2)[0];+ e2.TryGetAuroraTableInfo(id, 0, out var v0);+ yield return (doc.FormatVersion == 31 && w.Count == 0 && v0.Frames == 0+ && e2.GetPluginState(id, -1).Length == Params * 4,+ $"aurora tables: a v27 project loads unchanged and migrates to 31 ({doc.FormatVersion})");+ }+ }++ // ---- T030: presets ----+ private static IEnumerable<(bool, string)> Presets(Dictionary<string, string> fx)+ {+ using var e = new NotaEngine();+ int t = e.AddWavetableSynthTrack();+ e.AuroraTableBuild(fx["table-64x2048.wav"], out var h);+ e.AuroraSetTable(t, 1, h); e.AuroraTableFree(h);+ var frames = e.AuroraTableRead(t, 1);+ var doc = PresetService.Capture(e, t, -1, "Mine")!;+ yield return (doc.AuroraTables is { Count: 1 } && doc.AuroraTables[0] is { Osc: 1, Frames: 64 },+ $"aurora tables: a user preset carries its table ({doc.AuroraTables?.Count ?? 0})");+ string json = System.Text.Json.JsonSerializer.Serialize(doc);+ var back = System.Text.Json.JsonSerializer.Deserialize<PresetDocument>(json)!;++ int t2 = e.AddWavetableSynthTrack();+ PresetService.ApplyInPlace(back, e, t2, -1);+ e.TryGetAuroraTableInfo(t2, 1, out var i1);+ yield return (i1 is { Frames: 64, UseCustom: true } && e.AuroraTableRead(t2, 1).AsSpan().SequenceEqual(frames),+ "aurora tables: applying it restores the frames exactly");+ e.Undo();+ e.TryGetAuroraTableInfo(t2, 1, out var i2);+ yield return (i2.Frames == 0, "aurora tables: the preset apply is one undo step");+ e.Redo();++ var cat = new FactoryPresetCatalog();+ var factories = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 5 && p.DisplayName != "Init").Take(1).ToList();+ string warn = factories.Count == 0 ? "none" : cat.ApplyInPlace(e, factories[0].Id!, t2, -1);+ e.TryGetAuroraTableInfo(t2, 1, out var i3);+ yield return (factories.Count == 1 && warn.Length == 0 && i3.Frames == 0 && !i3.UseCustom,+ $"aurora tables: a factory preset plays the built-in tables ({(factories.Count == 1 ? factories[0].DisplayName : "none")})");+ }++ // ---- T047: live follow ----+ private static IEnumerable<(bool, string)> Scope(Dictionary<string, string> fx)+ {+ using var e = new NotaEngine();+ int t = e.AddWavetableSynthTrack();+ Set(e, t, "lfo1rate", 0.5f); Set(e, t, "lfo1depth", 1f); Set(e, t, "mtx2_2", 1f); Set(e, t, "position", 0.5f);+ var sc = new float[6];+ Render(e, 512);+ e.InstrumentScope(t, sc);+ yield return (sc[0] == -1f && sc[1] == -1f && sc[2] == 0f, $"aurora tables: with no note the scope says none ({sc[0]}, serial {sc[2]})");+ e.TrackNoteOn(t, 60, 0.8f);+ float lo = 2, hi = -2;+ bool inRange = true;+ for (int k = 0; k < 100; k++) // about a second in 10 ms steps+ {+ Render(e, 480);+ e.InstrumentScope(t, sc);+ lo = Math.Min(lo, sc[0]); hi = Math.Max(hi, sc[0]);+ inRange &= sc[0] is >= 0 and <= 1 && sc[1] is >= 0 and <= 1;+ }+ yield return (inRange && hi - lo > 0.5 && sc[4] >= 1, $"aurora tables: a held note's played position moves with the LFO ({lo:0.00}..{hi:0.00})");+ e.AuroraTableBuild(fx["cycle-2048.wav"], out var h);+ e.AuroraSetTable(t, 1, h, undoable: false); e.AuroraTableFree(h);+ e.InstrumentScope(t, sc);+ e.TryGetAuroraTableInfo(t, 1, out var info);+ yield return (sc[3] > 0 && sc[3] == (info.Serial & 0xFFFFFF), $"aurora tables: the scope carries the table serial ({sc[3]})");+ float srcOn = sc[5];+ e.AuroraSetSource(t, 1, false);+ e.InstrumentScope(t, sc);+ yield return (srcOn == 2f && sc[5] == 0f, $"aurora tables: the scope says which oscillators play their imported table ({srcOn} → {sc[5]})");+ e.TrackNoteOff(t, 60);+ }++ // ---- helpers ----+ private static nint Build(NotaEngine e, float[] frames, int count, string name)+ => e.AuroraTableFromFrames(frames, count, name, 0, out var h) == 0 ? h : throw new InvalidOperationException("build");++ private static int[] TrackIds(NotaEngine e)+ {+ var ids = new List<int>();+ for (int i = 0; i < e.TrackCount; i++)+ if (e.TryGetTrackInfo(i, out var ti)) ids.Add(ti.Id);+ return ids.ToArray();+ }++ private static float[] Saw64() => AuroraFixtures.Saw(Frame, 1);++ private static void Render(NotaEngine e, int frames)+ {+ var buf = new float[frames * 2];+ e.RenderOffline(buf, frames, Sr);+ }++ private static int Chord(NotaEngine e)+ {+ int t = e.AddWavetableSynthTrack();+ int clip = e.AddMidiClip(t, 0, 4);+ e.SetClipNotes(t, clip, new[] { new NotaNote(48, 0, 4, 0.8f), new NotaNote(60, 0, 4, 0.7f), new NotaNote(67, 0, 4, 0.7f) });+ return t;+ }++ private static float[] RenderSong(NotaEngine e)+ {+ const int frames = 2 * Sr, block = 512;+ var buf = new float[frames * 2];+ var chunk = new float[block * 2];+ e.Seek(0);+ e.Play();+ for (int done = 0; done < frames; done += block)+ {+ e.RenderOffline(chunk, block, Sr);+ Array.Copy(chunk, 0, buf, done * 2, Math.Min(block, frames - done) * 2);+ }+ e.StopTransport();+ return buf;+ }++ private static float[] RenderChord(Action<NotaEngine, int>? setup)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int t = Chord(e);+ Set(e, t, "unison", 0.5f); Set(e, t, "unispread", 0.6f);+ setup?.Invoke(e, t);+ return RenderSong(e);+ }++ private static float[] RenderNote(int pitch, Action<NotaEngine, int> setup)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int t = e.AddWavetableSynthTrack();+ Set(e, t, "unison", 0f); Set(e, t, "cutoff", 1f); Set(e, t, "fxreverb", 0f); Set(e, t, "fxchorus", 0f);+ Set(e, t, "attack", 0f); Set(e, t, "sustain", 1f);+ setup(e, t);+ int clip = e.AddMidiClip(t, 0, 4);+ e.SetClipNotes(t, clip, new[] { new NotaNote(pitch, 0, 4, 0.8f) });+ return RenderSong(e);+ }++ private static void Set(NotaEngine e, int t, string id, float v)+ {+ int n = e.PluginParamCount(t, -1);+ for (int i = 0; i < n; i++)+ if (e.PluginParamId(t, -1, i) == id) { e.PluginParamSet(t, -1, i, v); return; }+ throw new InvalidOperationException($"Aurora has no parameter '{id}'");+ }++ private static double ResidualDb(float[] a, float[] b)+ {+ if (a.Length != b.Length || a.Length == 0) return 0;+ double worst = 0;+ for (int i = 0; i < a.Length; i++) worst = Math.Max(worst, Math.Abs(a[i] - b[i]));+ return 20 * Math.Log10(Math.Max(worst, 1e-12));+ }++ // Energy of the difference relative to the reference, over the steady second half.+ private static double RelativeDb(float[] reference, float[] x)+ {+ double e = 0, d = 0;+ for (int i = reference.Length / 2; i < reference.Length; i++) { e += reference[i] * reference[i]; d += (x[i] - reference[i]) * (x[i] - reference[i]); }+ return 10 * Math.Log10(Math.Max(d, 1e-30) / Math.Max(e, 1e-30));+ }++ // Energy away from the harmonics of f0 against the energy on them: a windowed DFT of the+ // left channel's steady part, bins within ±3 of a harmonic counted as harmonic.+ private static double AliasDb(float[] stereo, double f0)+ {+ const int n = 32768;+ int start = Sr; // frame Sr / 2: half a second into the held note+ var x = new double[n];+ for (int i = 0; i < n; i++)+ {+ double w = 0.35875 - 0.48829 * Math.Cos(2 * Math.PI * i / n) + 0.14128 * Math.Cos(4 * Math.PI * i / n) - 0.01168 * Math.Cos(6 * Math.PI * i / n);+ x[i] = stereo[start + 2 * i] * w;+ }+ var re = (double[])x.Clone(); var im = new double[n];+ Fft(re, im);+ double harm = 0, other = 0, binHz = (double)Sr / n;+ for (int k = 1; k < n / 2; k++)+ {+ double p = re[k] * re[k] + im[k] * im[k];+ double hz = k * binHz, nearest = Math.Round(hz / f0) * f0;+ if (nearest >= f0 && Math.Abs(hz - nearest) <= 4 * binHz) harm += p; else other += p;+ }+ return 10 * Math.Log10(Math.Max(other, 1e-30) / Math.Max(harm, 1e-30));+ }++ private static void Fft(double[] re, double[] im)+ {+ int n = re.Length;+ for (int i = 1, j = 0; i < n; i++)+ {+ int bit = n >> 1;+ for (; (j & bit) != 0; bit >>= 1) j ^= bit;+ j ^= bit;+ if (i < j) { (re[i], re[j]) = (re[j], re[i]); (im[i], im[j]) = (im[j], im[i]); }+ }+ for (int len = 2; len <= n; len <<= 1)+ {+ double ang = -2 * Math.PI / len;+ for (int i = 0; i < n; i += len)+ for (int k = 0; k < len / 2; k++)+ {+ double wr = Math.Cos(ang * k), wi = Math.Sin(ang * k);+ double ur = re[i + k], ui = im[i + k];+ double vr = re[i + k + len / 2] * wr - im[i + k + len / 2] * wi;+ double vi = re[i + k + len / 2] * wi + im[i + k + len / 2] * wr;+ re[i + k] = ur + vr; im[i + k] = ui + vi;+ re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;+ }+ }+ }+}diff --git a/tests/Nota.SmokeTest/LocalizationAllowList.txt b/tests/Nota.SmokeTest/LocalizationAllowList.txtindex c31d3f15..63352708 100644--- a/tests/Nota.SmokeTest/LocalizationAllowList.txt+++ b/tests/Nota.SmokeTest/LocalizationAllowList.txt@@ -2061,6 +2061,9 @@ Nota.App/DeviceCards/Rack/RackKindProfile.cs Select # data: device parameter, poNota.App/DeviceCards/Rack/RackKindProfile.cs Serial # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackKindProfile.cs Zones # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/SidechainSourcePicker.cs Internal # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/Diagnostics/UiProbe.cs $"card build→first paint p50 {b.P50:0.0}\u2009ms (n {b.N})" # data: perf probe report for stderr and perf runs (specs/053), not interface text+Nota.App/Diagnostics/UiProbe.cs $"tick p50 {t.P50:0.000}\u2009ms p99 {t.P99:0.000}\u2009ms (n {t.N}) · " # data: perf probe report for stderr and perf runs (specs/053), not interface text+Nota.App/Diagnostics/UiProbe.cs $"ui-probe aurora: paint p50 {p.P50:0.000}\u2009ms p99 {p.P99:0.000}\u2009ms (n {p.N}) · " # data: perf probe report for stderr and perf runs (specs/053), not interface textNota.App/ExportWindow.cs 32-bit float # data: bit-depth names of the export formatNota.App/ImeLogNoiseFilter.cs Error while destroying the context: # data: log text matched against the OSNota.App/MacAppMenu.cs Hide Others # data: the English title Avalonia gives the item, matched in code; the app namediff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 76eb674d..5e0edffc 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -718,6 +718,24 @@ if (args.Length >= 1 && args[0] == "--aurora-null")Console.WriteLine(failures == 0 ? "AURORA-NULL PASSED" : $"AURORA-NULL FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Aurora custom wavetables alone: `--aurora-tables` (specs/053). Also part of the full run.+if (args.Length >= 1 && args[0] == "--aurora-tables")+{+ Console.WriteLine("-- aurora tables --");+ foreach (var (ok, label) in AuroraTableTests.Run()) Check(ok, label);+ foreach (var (ok, label) in AuroraNullTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "AURORA-TABLES PASSED" : $"AURORA-TABLES FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}+// The Aurora import test files: `--aurora-fixtures <dir>` (specs/053 quickstart § 2).+if (args.Length >= 2 && args[0] == "--aurora-fixtures")+{+ foreach (var kv in AuroraFixtures.Write(args[1])) Console.WriteLine(kv.Value);+ return 0;+}+// The Aurora UI measurement project: `--aurora-ui-fixture <dir> [--builtin]` (quickstart § 4).+if (args.Length >= 2 && args[0] == "--aurora-ui-fixture")+ return AuroraFixtures.WriteUiProject(args[1], builtin: args.Length >= 3 && args[2] == "--builtin");// Dump Aurora reference renders: `--aurora-null-dump <dir>`.if (args.Length >= 2 && args[0] == "--aurora-null-dump"){@@ -15762,6 +15780,8 @@ foreach (var (ok, label) in PanLawTests.Run()) Check(ok, label);Console.WriteLine("-- aurora null --");foreach (var (ok, label) in AuroraNullTests.Run()) Check(ok, label);+Console.WriteLine("-- aurora tables --");+foreach (var (ok, label) in AuroraTableTests.Run()) Check(ok, label);Console.WriteLine("-- device fold --");foreach (var (ok, label) in DeviceFoldTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/TwinTests.cs b/tests/Nota.SmokeTest/TwinTests.csindex cea5ed2b..5f4987a9 100644--- a/tests/Nota.SmokeTest/TwinTests.cs+++ b/tests/Nota.SmokeTest/TwinTests.cs@@ -317,6 +317,8 @@ internal static class TwinTestsvar bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();yield return (bad.Count == 0, $"every Twin preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");int tp = e.AddTwinTrack();+ // Settle the heap first, so a collection left over from earlier tests doesn't land in the timing.+ GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();int fails = 0;double slowest = 0;foreach (var p in mine)diff --git a/tests/perf/nota_perf.cpp b/tests/perf/nota_perf.cppindex 43d8ac86..afaf81d7 100644--- a/tests/perf/nota_perf.cpp+++ b/tests/perf/nota_perf.cpp@@ -35,6 +35,12 @@#include <valgrind/callgrind.h>#endif#endif+#if defined(__has_include)+#if __has_include(<dlfcn.h>)+#include <dlfcn.h>+#define NOTA_PERF_HAS_DL 1+#endif+#endif#ifndef CALLGRIND_START_INSTRUMENTATION#define CALLGRIND_START_INSTRUMENTATION#define CALLGRIND_STOP_INSTRUMENTATION@@ -98,6 +104,41 @@ void fillChords6(NotaEngine* e, int track, int transpose, double startBeat, doubnota_clip_set_notes(e, track, clip, notes.data(), (int)notes.size());}+// A bright 256-frame table (saw to pulse across the frames, full bandwidth), the worst+// case an import can produce: the most frames and every harmonic present (specs/053).+// The gate compiles this harness against the base engine's header too, so the table calls+// are looked up at run time; on an engine without them the scenario reports "base error".+using TableFromFrames = int32_t (*)(const float*, int32_t, const char*, int32_t, void**);+using AuroraSetTable = int32_t (*)(NotaEngine*, int32_t, int32_t, const void*, int32_t);++template <typename F> F engineSymbol(const char* name) {+#if defined(NOTA_PERF_HAS_DL)+ return reinterpret_cast<F>(dlsym(RTLD_DEFAULT, name));+#else+ (void)name;+ return nullptr;+#endif+}++const void* importedTable() {+ static void* table = [] {+ const auto fromFrames = engineSymbol<TableFromFrames>("nota_aurora_table_from_frames");+ if (!fromFrames) return (void*)nullptr;+ constexpr int kFrame = 2048, kFrames = 256;+ std::vector<float> t((size_t)kFrame * kFrames);+ for (int f = 0; f < kFrames; ++f) {+ const double m = (double)f / (kFrames - 1);+ for (int i = 0; i < kFrame; ++i) {+ const double ph = (i + 0.5) / kFrame;+ t[(size_t)f * kFrame + i] = (float)((2 * ph - 1) * (1 - m) + (ph < 0.5 ? 0.8 : -0.8) * m);+ }+ }+ void* h = nullptr;+ return fromFrames(t.data(), kFrames, "perf-256", 0, &h) == 0 ? h : nullptr;+ }();+ return table;+}+// Sets a track instrument's param by id (no-op for an unknown id).void setParamById(NotaEngine* e, int track, const char* id, float v) {const int n = nota_plugin_param_count(e, track, -1);@@ -219,6 +260,7 @@ std::vector<Scenario> scenarios() {s.push_back({"instrument-rack", "Instrument Rack, 2 Synth chains"});s.push_back({"effect-base", "Synth alone (effect baseline)"});s.push_back({"aurora-supersaw-2x", "Aurora Super Saw x2"});+ s.push_back({"aurora-imported-2x", "Aurora Super Saw x2, imported 256-frame tables"});// Full-polyphony synth loads (specs/055 SC-001: Twin at 12 voices against Pentad at 16).s.push_back({"pentad-full-16", "Pentad, 16-voice chord"});s.push_back({"twin-full-12", "Twin, 12-voice chord, both filters, 16 routes, FX"});@@ -284,11 +326,19 @@ bool build(NotaEngine* e, const std::string& id) {fillClip(e, t, 0, 0, 16);return true;}- if (id == "aurora-supersaw-2x") {+ if (id == "aurora-supersaw-2x" || id == "aurora-imported-2x") {+ // The imported variant is the same load with both oscillators on a 256-frame table:+ // what an import costs on the audio thread (budget: within 10 % of the built-in row).+ const bool imported = id == "aurora-imported-2x";+ const auto setTable = imported ? engineSymbol<AuroraSetTable>("nota_track_aurora_set_table") : nullptr;+ if (imported && (!setTable || !importedTable())) return false;for (int t = 0; t < 2; ++t) {const int tr = instrumentTrack(e, 5);if (tr < 0) return false;applySuperSaw(e, tr);+ if (imported)+ for (int o = 0; o < 2; ++o)+ if (setTable(e, tr, o, importedTable(), 0) != 1) return false;fillChords6(e, tr, t == 0 ? 0 : 7, 0, 16);}return true;