Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) Articulation maps (#549)

ret_xed1581075c3ccb
diff --git a/.specify/bugs/articulation-manager-reopen/assessment.md b/.specify/bugs/articulation-manager-reopen/assessment.md
new file mode 100644
index 00000000..3aac449b
--- /dev/null
+++ b/.specify/bugs/articulation-manager-reopen/assessment.md
@@ -0,0 +1,71 @@
+# Bug Assessment: "Edit maps…" doesn't bring up the articulation map manager
+
+- **Slug**: articulation-manager-reopen
+- **Created**: 2026-11-09
+- **Source**: pasted text (owner, in the session building specs/085)
+- **Verdict**: likely valid, needs reproduction
+- **Severity**: medium
+
+## Report (verbatim or summarized)
+
+> "the edit map button doesnt show up sometimes" — "after changing the values in note offset and
+> saving it" — "The button is there, but clicking it doesn't bring up the manager."
+
+## Symptom
+
+After editing an articulation's note offset in the manager and saving, clicking "Edit maps…" in the
+track inspector does nothing visible. Expected: the manager comes to the front (or opens).
+
+## Reproduction
+
+1. Open the manager from the inspector's "Edit maps…", change a note offset, Save.
+2. [NEEDS CLARIFICATION: what happened to the manager window between Save and the next click —
+ closed, minimized, or left open?]
+3. Click "Edit maps…" again: no manager appears.
+
+## Suspected Code Paths
+
+- `src/managed/Nota.App/ArticulationMapManager.cs:Open()` — with an instance already recorded in
+ `_open`, it only calls `w.Activate()`. `Activate` does not restore a minimized window, and the
+ manager is owned by the main window, so it has no taskbar button of its own to restore it from:
+ a minimized manager can't be brought back by the button or the menu.
+- Same method — it trusts `_open` blindly. If the window is no longer shown but `Closed` hasn't
+ cleared `_open`, every click activates a window nobody can see. `IsVisible` is never checked.
+- Same method — the new window is shown synchronously inside the click; `LensWindow` and the scope
+ window post the show/activate until after the click finishes so the clicked window doesn't take
+ activation back.
+
+Checked and ruled out: `TrackInspectorView.ArticulationsBody` always adds the button for instrument
+tracks (the owner confirms it's there); its click goes to `MainWindow.ShowArticulationMaps`. The log
+`%APPDATA%\Nota\logs\nota-20261109.log` has no exception, so nothing threw and was swallowed.
+
+## Root Cause Hypothesis
+
+The manager instance still exists but isn't visible — most plausibly minimized (an owned window with
+no taskbar button) — and `Open` only calls `Activate()`, which neither restores nor re-shows it.
+Confidence: medium. Saving itself doesn't hide the window in any code path found; it is the step
+before the window was put away.
+
+## Proposed Remediation
+
+**Preferred**: make `Open` bring an existing manager back whatever its state: drop a recorded
+instance that is no longer visible and open a new one; restore a minimized one to Normal; then
+activate it after the click has finished (`Dispatcher.UIThread.Post`, as `LensWindow` does). Show a
+new manager the same way.
+
+**Files likely to change**:
+- `src/managed/Nota.App/ArticulationMapManager.cs`
+
+**Tests to add or update**:
+- No window harness exists in the smoke test (no Avalonia.Headless). Verification is manual: minimize
+ the manager, click "Edit maps…" — it comes back; close it, click — a new one opens; leave it open
+ behind a dialog, click — it comes to the front.
+
+## Risks & Considerations
+
+- Restoring a minimized window while it holds unsaved edits must keep them (it does: the instance is
+ reused, only its state changes).
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: was the manager minimized, closed, or still open when the click did nothing?]
diff --git a/.specify/bugs/articulation-manager-reopen/fix.md b/.specify/bugs/articulation-manager-reopen/fix.md
new file mode 100644
index 00000000..9606855c
--- /dev/null
+++ b/.specify/bugs/articulation-manager-reopen/fix.md
@@ -0,0 +1,59 @@
+# Bug Fix: "Edit maps…" doesn't bring up the articulation map manager
+
+- **Slug**: articulation-manager-reopen
+- **Fixed**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+The owner confirmed the manager had been minimized. It is owned by the main window, so it has no
+taskbar button, and `Open` only called `Activate()`, which doesn't restore a minimized window — the
+button and menu did nothing. `Open` now restores a minimized manager, replaces one that was shown and
+is no longer visible, and shows / activates after the click has finished.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/managed/Nota.App/ArticulationMapManager.cs` | modified `Open` | restore from Minimized; drop a shown-but-invisible instance (`_wasShown` set on `Opened`); `Closed` clears only its own instance; show and `Activate` posted at Background priority (the `LensWindow` / `ScopeWindow` pattern); one log line per reopen with the window state |
+
+## Diff Highlights (optional)
+
+```csharp
+if (_open is { _wasShown: true, IsVisible: false } gone) { … _open = null; }
+if (_open is { } w)
+{
+ if (w.WindowState == WindowState.Minimized) w.WindowState = WindowState.Normal;
+ if (!w.Dirty) w.Reload(w.TrackMapId());
+ Dispatcher.UIThread.Post(w.Activate, DispatcherPriority.Background);
+ return;
+}
+```
+
+## Tests Added or Updated
+
+- None automated: the smoke test has no window harness (no Avalonia.Headless), as the assessment
+ noted. Covered by the manual checks in `/speckit-bug-test`.
+
+## Local Verification
+
+- `dotnet build src/managed/Nota.App -c Release -o <scratch>` → 0 errors (the normal output was locked
+ by the owner's running Nota, PID 1156, so the app was compiled to a scratch folder instead).
+- `dotnet build tests/Nota.SmokeTest -c Release` → 0 errors.
+- Full smoke test, twice → 5392 pass, 1 fail both times: "exporting 16 tracks in 8192-frame chunks:
+ render threads do 0 % of the work (>= 20 %)". This is the render-pool timing check measured earlier
+ in specs/085 as pre-existing flakiness (a `git archive` HEAD baseline fails it the same way); the
+ same suite passed 5393/0 earlier today with Nota closed, and this change touches only window
+ opening on the UI thread. Rerun with Nota closed to confirm.
+- Manual: not yet — needs the rebuilt app (see Follow-ups).
+
+## Deviations from Assessment
+
+- None in the fix. The open question is answered: the manager was minimized (owner, 2026-11-09).
+
+## Follow-ups
+
+- Close Nota, rebuild (`dotnet build Nota.sln -c Release`), rerun the smoke test, then the manual
+ checks: minimize the manager → "Edit maps…" restores it; close it → a new one opens; with unsaved
+ edits, minimize and reopen → the edits are still there.
diff --git a/.specify/bugs/articulation-manager-reopen/test.md b/.specify/bugs/articulation-manager-reopen/test.md
new file mode 100644
index 00000000..094225f2
--- /dev/null
+++ b/.specify/bugs/articulation-manager-reopen/test.md
@@ -0,0 +1,39 @@
+# Bug Verification: "Edit maps…" doesn't bring up the articulation map manager
+
+- **Slug**: articulation-manager-reopen
+- **Tested**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+With the fix built, the owner reports the manager works ("everything works", 2026-11-09), including
+bringing it back after it was minimized — the case the assessment identified and the owner
+confirmed. The full smoke test passes with Nota closed.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (post-fix) | Owner, in the rebuilt app: minimize the manager, click "Edit maps…" | pass | owner's report; not observed by the agent |
+| New / updated tests | — | not-run | no window harness in the smoke test (no Avalonia.Headless), as the assessment noted |
+| Regression suite | `scripts`-equivalent local run: `Nota.SmokeTest.dll` (full) | pass | 5401 pass, 0 fail, Nota closed |
+| Build | `dotnet build Nota.sln -c Release` | pass | 0 errors |
+
+## Output Excerpts
+
+```
+EXIT=0 pass 5401 fail 0 art 153 | SMOKE TEST PASSED
+```
+
+The render-pool timing check that failed in fix.md's runs (Nota was open then) passed here.
+
+## Residual Risks
+
+- The window behaviour is covered by the owner's manual check only; a regression would not be caught
+ by the smoke test.
+
+## Recommendation
+
+Close the bug — the owner verified it in the app and the regression suite is green.
diff --git a/.specify/bugs/pr549-follow-up/.gitignore b/.specify/bugs/pr549-follow-up/.gitignore
new file mode 100644
index 00000000..397b4a76
--- /dev/null
+++ b/.specify/bugs/pr549-follow-up/.gitignore
@@ -0,0 +1 @@
+*.log
diff --git a/.specify/bugs/pr549-follow-up/assessment.md b/.specify/bugs/pr549-follow-up/assessment.md
new file mode 100644
index 00000000..388a161e
--- /dev/null
+++ b/.specify/bugs/pr549-follow-up/assessment.md
@@ -0,0 +1,27 @@
+# Bug Assessment: PR #549 follow-up review
+
+- **Slug**: pr549-follow-up
+- **Created**: 2026-11-09
+- **Source**: https://github.com/nota-daw/nota/pull/549 (github.com, HTTPS, allowlisted)
+- **Approved scope**: issue #547; continuation of the articulation-map review fixes
+- **Verdict**: valid
+- **Severity**: high for stuck keyswitches; medium for manager availability
+
+## Symptoms and reproduction
+
+1. Thread `discussion_r4512772111`: legato-launch a Session phrase at beat 8, 120 BPM, 48 kHz, 512-frame blocks. Before the 20 ms chased-key hold ends, change to 60 BPM. The stored sample position belongs to the old beat-to-sample conversion; the next block's position is rebuilt with the new tempo and skips the release. Natural latching switches have the same clock problem.
+2. Thread `discussion_r4512772121`: copy a readable `.notamap` file to another filename in the user's articulation folder. `ArticulationLibraryStore.List()` returns both maps with the same ID, and `Catalog()` throws in `ToDictionary`.
+
+## Root causes and remediation
+
+The Session player's absolute sample chase origin is derived from musical position. Replace that reconstruction for Session latching key releases with a bounded, audio-thread-owned pending-release queue, storing the actual channel/key and remaining rendered frames. Count down by rendered frames independently of tempo and preserve releases when map data changes. Queue only successfully emitted key-ons, prioritize pending releases, and reject additional key-ons if the fixed queue is full; no audio-thread allocation or locking.
+
+Build the library lookup with duplicate-tolerant insertion, retaining the first readable copy for each ID. Continue preferring project copies when their contents differ. Test copied files with the same ID in both project-backed and library-only catalogs.
+
+## Files and validation
+
+- Native: `ArticulationSchedule.h/.cpp`, `SessionPlayer.h/.cpp`, `Engine_Render.cpp`; extend native self-test through the real Session renderer for slower/faster tempo changes, natural/chased switches, relaunch and bounded queue behavior.
+- Managed: `ArticulationMapUsage.cs`, `ArticulationManagerTests.cs`.
+- Run the focused articulation suite and the full required Windows build/smoke/scanner script. Commit each fix independently, push to the existing PR, and resolve the two verified threads.
+
+The prior pushed revision `96733e0e` passed the remote engine instruction-count gate (`42617643537`). These additional changes require their own CI run.
diff --git a/.specify/bugs/pr549-follow-up/fix.md b/.specify/bugs/pr549-follow-up/fix.md
new file mode 100644
index 00000000..4627ae92
--- /dev/null
+++ b/.specify/bugs/pr549-follow-up/fix.md
@@ -0,0 +1,32 @@
+# Bug Fix: PR #549 follow-up review
+
+- **Slug**: pr549-follow-up (from assessment context)
+- **Fixed**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Changes
+
+### Tempo changes leave switches held
+
+`ArticulationReleaseState` retains actual MIDI channel/key pairs and remaining rendered frames in fixed storage. Session scheduling queues only successfully emitted latching key-ons, for both natural and chased switches. Pending releases advance with rendered frames before new actions; they never depend on `localBeats * spb` after emission. Clearing a map still drains pending releases without consulting the old table.
+
+The queue never grows on the audio thread. It rejects key-ons when no release slot remains and carries undeliverable releases to the next block. Session launch/stop clears the old queue when the caller flushes instrument voices. A user-provided `SessionPlayer` constructor prevents value-initialization from zero-filling the unused queue on every track clone.
+
+Files: `ArticulationSchedule.h/.cpp`, `SessionPlayer.h/.cpp`, `Engine_Render.cpp`.
+
+Native checks 36/37 capture actual instrument events at nonzero Session positions while changing from 120 BPM to 60 or 240 BPM during the hold. They cover natural/chased switches, map removal, saturation, small output buffers and launch/stop cleanup. Existing checks through 35 remain unchanged.
+
+### Duplicate files block the manager
+
+`ArticulationMapUsage.Catalog` uses an ordinal dictionary with `TryAdd`, keeping the first readable copy for each library map ID. It still prefers a differing project copy. Manager tests write copied files with both identical and differing content and verify deduplication in project-backed and library-only catalogs.
+
+Files: `ArticulationMapUsage.cs`, `ArticulationManagerTests.cs`.
+
+## Local verification
+
+The focused articulation suite passes 414 checks with zero failures, including native self-test result zero. The final complete Windows build/smoke/scanner script passes with exit zero. Two earlier complete runs failed different render-pool timing guards; the isolated performance suite passed. All results are recorded in `test.md`; no guard thresholds or production code were changed between the full runs. Local logs remain ignored.
+
+## Deviations and follow-ups
+
+No deviation from the assessment. The previously pushed revision `96733e0e` passed the remote Linux instruction-count gate; the new commits must run CI again. No manual hosted-library audition or local macOS/Linux build is claimed.
diff --git a/.specify/bugs/pr549-follow-up/test.md b/.specify/bugs/pr549-follow-up/test.md
new file mode 100644
index 00000000..c88a26ea
--- /dev/null
+++ b/.specify/bugs/pr549-follow-up/test.md
@@ -0,0 +1,44 @@
+# Bug Verification: PR #549 follow-up review
+
+- **Slug**: pr549-follow-up (from assessment/fix context)
+- **Tested**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified on Windows
+
+## Summary
+
+Both follow-up findings are covered by passing regressions. The final unchanged `scripts/build-win.ps1` run exited zero: native/managed builds, scanner self-test, the complete smoke suite and scan-scale checks passed. Two earlier complete runs failed different render-pool performance guards; all functional checks passed in both. These failures are retained below rather than omitted from the evidence.
+
+## Checks performed
+
+| Check | Command / action | Result | Evidence |
+|---|---|---|---|
+| Focused suite | `dotnet run --project tests/Nota.SmokeTest -c Release -- --articulations` | pass | 414 passes, zero failures; `articulations.log`. |
+| Tempo reproduction | Native self-test 36 via the actual Session renderer | pass | Natural/chased switches at nonzero positions, 120 → 60 and 120 → 240 BPM; each release remains at rendered frame 960. Clearing the map during the hold also preserves delivery. |
+| Bounded storage and lifecycle | Native self-test 37 | pass | Queue capacity rejects extra key-ons; every emitted key gets its release; small output buffers retry releases; launch/stop clears flushed pending keys. |
+| Duplicate-file reproduction | `ArticulationManagerTests` | pass | Real copied `.notamap` files with identical and differing contents; project-backed and library-only catalogs remain usable and deduplicate each ID. |
+| Full build, initial run | `scripts/build-win.ps1` | fail, exit 1 | Export guard reported 0% worker participation, below 20%; all articulation checks passed. `build-win.log`. |
+| Isolated render-pool suite | Smoke test `--perf` | pass, exit 0 | Worker participation 89%; parallel bounce CPU 968 ms vs serial 405 ms. `perf.log`. |
+| Full build, second run | `scripts/build-win.ps1` | fail, exit 1 | Bounce CPU guard reported 1275 ms parallel vs 400 ms serial; export participation and all articulation checks passed. `build-win-verified.log`. |
+| Full build, final run | `scripts/build-win.ps1` | pass, exit 0 | Bounce CPU 1094 ms vs 393 ms; export worker participation 60%; scanner, full smoke and scan-scale passed. `build-win-final.log`. |
+| Whitespace | `git diff --check` | pass | No whitespace errors. |
+
+No production code or guard thresholds were changed between the complete runs. The original PR description also records an intermittent 0%-worker export failure. Timing variation remains a test/environment concern; it is not evidence of a clean first run.
+
+## Output excerpts
+
+```text
+ARTICULATIONS PASSED
+[PASS] ... copied map files with duplicate IDs do not block the manager ...
+[PASS] ... a library-only catalog lists each duplicate ID once ...
+[PASS] ... (failed check: 0)
+PERF PASSED
+SCANNER SELFTEST PASSED
+SMOKE TEST PASSED
+SCAN SCALE PASSED
+```
+
+## Residual risks and recommendation
+
+Commit the two fixes independently and push them to PR #549, then resolve review threads `PRRT_kwDOUD4x7861QPvL` and `PRRT_kwDOUD4x7861QPvP`. The prior revision `96733e0e` passed Linux instruction-count CI; the follow-up commits require a new CI run. No local Linux/macOS build or manual sample-library audition is claimed. Local raw logs are ignored alongside these reports.
diff --git a/.specify/bugs/pr549-mute-perf/.gitignore b/.specify/bugs/pr549-mute-perf/.gitignore
new file mode 100644
index 00000000..397b4a76
--- /dev/null
+++ b/.specify/bugs/pr549-mute-perf/.gitignore
@@ -0,0 +1 @@
+*.log
diff --git a/.specify/bugs/pr549-mute-perf/assessment.md b/.specify/bugs/pr549-mute-perf/assessment.md
new file mode 100644
index 00000000..add6e913
--- /dev/null
+++ b/.specify/bugs/pr549-mute-perf/assessment.md
@@ -0,0 +1,22 @@
+# Bug Assessment: PR #549 muted releases and edit overhead
+
+- **Slug**: pr549-mute-perf
+- **Created**: 2026-11-09
+- **Source**: https://github.com/nota-daw/nota/pull/549 (github.com, HTTPS, allowlisted)
+- **Approved issue**: #547, approved and open
+- **Verdict**: valid
+- **Severity**: high for premature switch releases; medium for edit overhead
+
+## Reproduction and root causes
+
+Review thread `PRRT_kwDOUD4x7861Q6P7` reports that Session release timers stop while a track is muted. The silent-track path flushes instrument voices and advances the slot clock but retains queued releases. Unmuting into a momentary note using the same key lets an obsolete release cut the new hold. Solo gating takes the same path.
+
+The engine instruction gate on revision `8abb3ad1` failed `edit-warp-split` at +4.59% work versus the base (run `42622338564`). `cloneTrack` constructs a default Session player, including its now larger fixed release storage, then immediately replaces it with the old track's player. Avoid constructing and destroying playback state that a clone will never use.
+
+## Remediation and validation
+
+1. Clear pending Session releases when the silent-track path flushes voices. Add an end-to-end native regression that launches a latching switch, mutes or solo-gates during its hold, then unmutes into a momentary switch on the same key. Demonstrate failure on the old code.
+2. Allow `Track` construction with an existing Session player, and have `cloneTrack` pass it directly. Preserve the shared player's state across edits. Measure the actual warped-split/undo scenario before and after using identical binaries of an amplified local performance harness. Linux instruction-count validation remains CI-only on this Windows host.
+3. Run focused articulation tests and the required complete Windows build/scanner/smoke checks, commit the fixes independently, push to PR #549, and resolve the verified review thread.
+
+No audio-thread allocation, locks, ABI changes, or weakened performance thresholds. Changes stay within the articulation feature's approved issue. Raw local validation/benchmark output remains ignored.
diff --git a/.specify/bugs/pr549-mute-perf/fix.md b/.specify/bugs/pr549-mute-perf/fix.md
new file mode 100644
index 00000000..ad0fe39b
--- /dev/null
+++ b/.specify/bugs/pr549-mute-perf/fix.md
@@ -0,0 +1,22 @@
+# Bug Fix: PR #549 muted releases and edit overhead
+
+- **Slug**: pr549-mute-perf (from assessment)
+- **Fixed**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Status**: applied; Windows validation and Linux instruction gate passed
+
+## Changes
+
+`Engine_Render.cpp` clears pending articulation releases when a Session track becomes silent through mute or solo gating and its voices are flushed. Native self-test 38 exercises actual offline rendering: launch a latching key, silence the track during its hold, unmute into a momentary articulation using that key, and verify the obsolete release cannot interrupt it. The test fails on the old code at check 38 and passes with the fix.
+
+`Track.h` adds a constructor taking the existing Session player. `Engine::cloneTrack` passes it directly, eliminating construction and destruction of a temporary player and its fixed release storage during every edit. A separate constructor for fresh tracks keeps the clone path free of a runtime conditional. The shared player's playback state is preserved.
+
+## Validation and benchmark
+
+- Old-code reproduction: focused articulation suite exits 1, native failed check 38.
+- Fixed code: focused suite passes all 414 checks; native self-test returns zero.
+- Local performance harness uses the repository's `edit-warp-split` scenario, with 1000 repeated cycles and the same 8 splits/8 undos per cycle. Both engine DLLs run an identical Release harness; fades are disabled as in the Linux gate. Nine rounds alternate execution order.
+- Windows median wall times: before `8abb3ad1` 3.818 µs/edit, candidate 3.903 µs/edit (+2.2%). Ranges overlap: 3.731–4.525 and 3.740–4.345 µs. These measurements do not establish an instruction-count improvement; Linux/Valgrind CI supplies that evidence separately.
+- Complete Windows validation passed on the first full run: native/managed builds, scanner self-test, full smoke suite and scan-scale check. Linux performance run `42627356463` passed for PR source `9eb6382c`; `edit-warp-split` improved from +4.59% to +0.45% work versus the base, within the 1% limit. All engine scenarios and all three platform idle-CPU checks passed. See `test.md`.
+
+Raw CSV, chart and machine details are published under `pr549-mute-perf/` on the fork's `pr-assets` branch and linked from `test.md`, rather than committed to the source branch. No guard thresholds were changed. No audio-thread allocation or locking was introduced.
diff --git a/.specify/bugs/pr549-mute-perf/test.md b/.specify/bugs/pr549-mute-perf/test.md
new file mode 100644
index 00000000..95ec491d
--- /dev/null
+++ b/.specify/bugs/pr549-mute-perf/test.md
@@ -0,0 +1,44 @@
+# Bug Verification: PR #549 muted releases and edit overhead
+
+- **Slug**: pr549-mute-perf (from assessment/fix context)
+- **Tested**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified — functional regression and Linux instruction-count gate pass
+
+## Checks performed
+
+| Check | Result | Evidence |
+|---|---|---|
+| Old-code reproduction | expected failure | The rebuilt native engine with regression check 38 and the old mute path fails the focused suite at check 38 (`reproduce.log`, exit 1). |
+| Focused articulation suite | pass | 414 checks, zero failures; native self-test returns zero (`articulations.log`). |
+| Complete Windows build | pass, exit 0 | `scripts/build-win.ps1`: native and managed builds, scanner self-test, full smoke suite and scan-scale checks all pass on the first full run (`build-win.log`). |
+| Source whitespace | pass | `git diff --check`. |
+| Before/after edit benchmark | measured | Identical Release harness, 9 interleaved rounds, 1000 cycles of 8 splits and 8 undos, split fades disabled. See chart, raw data and machine details below. |
+| Linux instruction-count gate | pass | [Performance run 42627356463](https://github.com/nota-daw/nota/actions/runs/42627356463), PR source `9eb6382c`: all engine scenarios pass; `edit-warp-split` is +0.45% work versus the base, within the 1% limit. |
+| Cross-platform idle CPU | pass | Linux, macOS and Windows idle-CPU jobs all pass in the same performance workflow. |
+
+## Reproduction coverage
+
+Native check 38 renders the real engine/Session path. A latching key starts at frame 0; the track is muted or solo-gated during the 20 ms hold; on unmute a momentary articulation presses the same key. The old pending release at offset 448 must not cut the new key pressed at offset 357. Both mute and solo-gating cases pass after clearing the flushed queue.
+
+The allocation fix is commit `bc131d63`; it constructs graph clones with the existing Session player rather than allocating and discarding a fresh player and its release storage. The combined source tree was built and tested before committing.
+
+## Benchmark evidence
+
+Before: `8abb3ad1`. After: `bc131d63`. Windows Release/MSVC, AMD Ryzen 9 7900X, 24 logical CPUs.
+
+| Revision | Median µs/edit | Min | Max |
+|---|---:|---:|---:|
+| Before | 3.818 | 3.731 | 4.525 |
+| After | 3.903 | 3.740 | 4.345 |
+
+The +2.2% median wall-time difference has overlapping ranges. No Windows timing speedup or Linux instruction-count improvement is inferred from these numbers.
+
+The authoritative Linux/Valgrind result is separate: run `42627356463` compares base `ad5b1c6f` with PR merge `4a87a167` (PR source `9eb6382c`). It passes all engine scenarios. `edit-warp-split` is +0.45% instructions versus the base, down from +4.59% on `8abb3ad1`, and within the 1% gate. The mute review thread is resolved; no unresolved review threads remained when checked after this run.
+
+![Warped split/undo wall times](https://raw.githubusercontent.com/thoi1/nota/pr-assets/pr549-mute-perf/edit-warp-split.svg)
+
+[Raw CSV](https://github.com/thoi1/nota/blob/pr-assets/pr549-mute-perf/edit-warp-split.csv) · [Method, commits and machine](https://github.com/thoi1/nota/blob/pr-assets/pr549-mute-perf/summary.md)
+
+Assets are committed on `pr-assets`, not the source branch. Local logs and harness binaries remain ignored. No tests or performance thresholds were weakened. Linux/macOS were not built locally.
diff --git a/.specify/bugs/pr549-review/.gitignore b/.specify/bugs/pr549-review/.gitignore
new file mode 100644
index 00000000..8bf25ff8
--- /dev/null
+++ b/.specify/bugs/pr549-review/.gitignore
@@ -0,0 +1,2 @@
+# Local validation output; reports summarize the relevant results.
+*.log
diff --git a/.specify/bugs/pr549-review/assessment.md b/.specify/bugs/pr549-review/assessment.md
new file mode 100644
index 00000000..fdacd4c0
--- /dev/null
+++ b/.specify/bugs/pr549-review/assessment.md
@@ -0,0 +1,41 @@
+# Bug Assessment: PR #549 articulation playback and project map selection
+
+- **Slug**: pr549-review (generated from the PR number)
+- **Created**: 2026-11-09
+- **Source**: https://github.com/nota-daw/nota/pull/549
+- **URL policy**: github.com, HTTPS, allowlisted
+- **Approved scope**: nota-daw/nota#547 (`approved`, checked with GitHub CLI)
+- **Verdict**: valid
+- **Severity**: high — missing notes, stuck switches, wrong techniques and overwritten project settings
+
+## Report and reproduction
+
+The review identifies seven faults in the original PR:
+
+1. Seek into a latching phrase using 512-frame blocks at 48 kHz: the chased switch's 960-sample release falls outside the first block and is discarded.
+2. Loop a one-beat Session clip at 120 BPM with a +1500 ms offset: source passes more than one loop away are skipped, losing notes and switches.
+3. Launch a Session clip with a beat-zero note and a trigger lead, or legato into a phrase: its switch occurs before launch and is never restored.
+4. Apply a Session note offset to a recorded expression curve: expression remains at the original time.
+5. Save a shared map edit, undo the track changes, and reopen the manager: its library copy hides the restored project copy.
+6. Overlap clip A (articulation 1 at beats 0 and 2) with clip B (articulation 2 at beat 1): clip A's second switch was discarded before playback.
+7. Overlap momentary notes sharing a keyswitch: the shorter note releases a key still required by another note, including a different articulation using the same key.
+
+The engine performance check also fails on four inexpensive instrument scenarios (+1.38–1.59% instructions) and `edit-warp-split` (+1.17%). The full CI report was read with `gh run view 42585182796 --log-failed`.
+
+## Suspected code paths and root causes
+
+- `ArticulationSchedule.cpp`: stateless chase releases discarded by the block window; clip-local latching decisions; independent momentary releases.
+- `ArticulationTable.cpp`: removes repeated latching notes before other clips can be considered.
+- `Engine_Render.cpp`: neighboring Session passes only, no launch chase, unshifted expression, and articulation event array default initialization on every render.
+- `Engine.cpp`: graph scans before the cheap no-map timeline check during publication.
+- `ArticulationMapUsage.cs`: library-first deduplication by map ID.
+
+Confidence: high; all seven reports follow directly from the original code. Existing uncommitted fixes are present in these files and must be preserved and completed. Their fixed 32-pass limit still loses valid events, and their shortened chase hold does not preserve the specified 20 ms duration.
+
+## Proposed remediation
+
+Keep the existing draft's track-wide latching decisions, project-first catalog, no-map fast paths, and shifted expression. Derive Session pass ranges from event times and note ends without an arbitrary neighboring-pass limit. Preserve the last chase origin so a stateless scheduler can emit its 20 ms release in a later block. Check shared momentary keys across all audible notes and clips. Extend native self-tests and C ABI smoke tests for exact timing, small blocks, short loops, overlapping clips/keys, launch/legato, and map save/undo/reopen.
+
+## Risks and validation
+
+The audio thread must remain allocation-free, lock-free and free of I/O. Use immutable clip/table data and caller-owned fixed event arrays. Keep tracks without maps on their fast path. Run the focused articulation suite and the required Windows build/smoke/scanner script. Linux instruction-count validation cannot run locally: WSL has no installed distribution and virtualization is disabled; report this explicitly instead of claiming CI passed. No commit or push is part of this local repair.
diff --git a/.specify/bugs/pr549-review/fix.md b/.specify/bugs/pr549-review/fix.md
new file mode 100644
index 00000000..85407ea4
--- /dev/null
+++ b/.specify/bugs/pr549-review/fix.md
@@ -0,0 +1,43 @@
+# Bug Fix: PR #549 articulation review
+
+- **Slug**: pr549-review (reused from assessment)
+- **Fixed**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Status**: applied; split into focused commits for PR #549
+
+## Summary
+
+Completed the existing uncommitted review fixes. Playback resolves latching changes across the track, holds shared momentary keys until the last dependent note ends, restores switches on Session launches, and schedules Session notes and expression across every pass their shifted lifetimes require. The manager opens project copies ahead of differing library copies.
+
+## Changes
+
+| Files | Change |
+|---|---|
+| `ArticulationTable.cpp`, `.h` | Retain repeated latching points for track-wide decisions; preserve chord deduplication. |
+| `ArticulationSchedule.cpp`, `.h` | Track-wide selection by trigger time, shared-key holds across clips/articulations (including default channel 0 aliasing explicit channel 1), launch chase, full 20 ms chased releases, pass ranges without a fixed neighboring-pass cap, and Session momentary tails spanning loops. |
+| `Engine_Render.cpp` | Share shifted Session note/expression timing and per-note pass ranges; chase the first launch/legato block; retain chase origin across blocks. Specialize arrangement scheduling at compile time to skip articulation lookups and timing arithmetic when the track has neither a map nor an offset. |
+| `Engine.h`, `SessionPlayer.h` | Audio-thread chase origins on the arrangement and slot clocks; no locks, allocations or public ABI changes. |
+| `Engine.cpp` | Check timeline currency before scanning the playing graph, with a cheap no-map path. |
+| `ArticulationMapUsage.cs`, `ArticulationMapManager.cs`, `en.json` | Prefer the project's map; label differences from the library and permit saving the restored copy. |
+| `ArticulationEngineTests.cs`, `ArticulationManagerTests.cs` | C ABI short-loop onset regressions and the real save/apply/undo/reopen/edit sequence. |
+| `CHANGELOG.md`, `specs/085-articulation-maps/tasks.md`, `plan.md` | Describe fixes and chase-origin design; remove the draft's unsupported claim that the new performance gate passed. |
+
+## Tests
+
+Native scheduler/delivery checks 26–35 cover full 20 ms chase holds across 512-frame and one-frame segments, overlapping clips, shared keys across different articulations/clips, 48-pass offsets, shifted Session expression at the instrument input, long note releases, and regular/legato launch restoration through the Session renderer. Existing checks 1–25 remain in place.
+
+`dotnet run --project tests/Nota.SmokeTest -c Release -- --articulations` passed: 412 checks, zero failures, including both 1.5-second delayed onset cases and the native self-test returning zero.
+
+The complete Windows build/scanner/smoke/scan-scale script is recorded in `test.md` after completion. Logs are local ignored artifacts alongside these reports.
+
+## Deviations from assessment
+
+The draft shortened a chased hold to the first block. This was replaced by preserving the chase origin and emitting the release at its full 20 ms duration in a later block. Session notes and expression now share one enumeration rather than independently expanding a common 32-pass window. Long Session note tails also determine the release window.
+
+Inspection of `HEAD` confirmed that `ArtEv` was already trivially default-constructible in the original PR. The assessment's array-initialization hypothesis was incorrect; no performance improvement is attributed to changing that array. The actual performance edits are the no-map/no-offset loop specialization, avoiding out-of-line lookups, cheaper event-offset minimum, and cheap timeline checks ahead of the graph scan.
+
+The first validation attempt caught a stack overflow from a large local `Engine` in the new native test harness. It now uses `std::make_unique<Engine>()`; the focused suite passes after this correction. This allocation is test-only.
+
+## Follow-ups
+
+Linux/Valgrind instruction-count CI must validate the performance changes. No new CI pass is claimed; the original PR's performance failure was the remote result inspected during local verification. WSL cannot run on this machine. Unrelated deferred feature/convergence tasks remain open in the existing feature plan. The user subsequently authorized committing each fix to PR #549; the changes are organized as eight fix commits and a verification/documentation commit. No review-thread reply or PR description edit is included.
diff --git a/.specify/bugs/pr549-review/test.md b/.specify/bugs/pr549-review/test.md
new file mode 100644
index 00000000..547f5f12
--- /dev/null
+++ b/.specify/bugs/pr549-review/test.md
@@ -0,0 +1,52 @@
+# Bug Verification: PR #549 articulation review
+
+- **Slug**: pr549-review (reused from the assessment/fix context)
+- **Tested**: 2026-11-09
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: partial — all seven functional findings verified on Windows; Linux performance gate pending
+
+## Summary
+
+The final `scripts/build-win.ps1` run exited zero with the latest code, including the no-map/no-offset specialization and default/explicit MIDI channel alias regression. Native and managed builds, scanner self-test, full engine/application smoke suite, and large-folder plugin scan check all passed. No functional regression remains in the automated reproductions listed in the assessment.
+
+The Linux instruction-count gate cannot run on this Windows host: WSL has no installed distribution and cannot start without virtualization. Performance optimizations are implemented, but their CI result is not yet known. Validation was completed before committing or pushing these fixes.
+
+## Checks performed
+
+| Check | Command / action | Result | Evidence |
+|---|---|---|---|
+| Focused articulation suite | `dotnet run --project tests/Nota.SmokeTest -c Release -- --articulations` | pass | 412 passing checks, zero failures; `articulations.log`. |
+| Final native/managed build and regression suite | `scripts/build-win.ps1` in VS 2022 Developer PowerShell | pass, exit 0 | `build-win-verified.log`; `SCANNER SELFTEST PASSED`, `SMOKE TEST PASSED`, `SCAN SCALE PASSED`. |
+| Native scheduler and Session delivery probes | Included in the final full smoke suite via `ArticulationSelfTest` | pass | Returned zero; checks through 35 cover the seven findings and added edge cases. |
+| Source whitespace | `git diff --check` | pass | No whitespace errors. |
+| Linux performance gate | `scripts/perf-gate.sh` | not-run | Requires Linux/Valgrind; WSL cannot run here. |
+| Manual hosted-library / UI audition | Kontakt/sample library and map-manager window | not-run | Automated tests exercise scheduling, instrument delivery and manager data flow; no manual UI claim. |
+
+## Reproduction coverage
+
+1. **Chased switch release:** native checks 26 and 34 deliver the release exactly 960 samples after the chase at 48 kHz, across 512-frame and one-frame segments. Check 35 also verifies a later-block release through Session rendering.
+2. **Short-loop offsets:** native checks 29/30 and C ABI onset tests preserve +1500 ms across both 500 ms loops and 31.25 ms loops (48 passes). Check 33 preserves a release several passes after its source note.
+3. **Launch restoration:** checks 25/35 restore a switch whose lead precedes launch, including a real legato launch request through `SessionPlayer::maybeApply` and `renderSessionSlotRaw`.
+4. **Expression timing:** check 32 captures note-on and opening pressure at the same sample, with the initial curve value, for both positive and negative combined track/articulation offsets.
+5. **Project map selection:** the manager smoke test saves/applies a newer library map, undoes it on the tracks, reopens the catalog, and saves a small edit. Both tracks retain their restored offsets.
+6. **Overlapping clips:** check 27 preserves A → B → A latching changes across separate clips rather than discarding the second A.
+7. **Shared momentary holds:** checks 28/31 prevent early releases for overlapping notes and different articulations in separate clips. Default channel 0 and explicit channel 1 are tested as the same physical MIDI channel.
+
+## Output excerpts
+
+```text
+ARTICULATIONS PASSED
+[PASS] a +1500 ms offset survives 48 passes of a 31.25 ms Session loop (72000 samples, want 72000)
+[PASS] saving a small edit after undo preserves the restored project offsets on every track
+[PASS] ... (failed check: 0)
+SCANNER SELFTEST PASSED
+SMOKE TEST PASSED
+SCAN SCALE PASSED
+```
+
+The first full attempt exposed a stack overflow in the newly added test harness. Moving its local engine to the heap corrected it; the final full run above passes. Local logs are ignored by the report directory's `.gitignore`.
+
+## Residual risks and recommendation
+
+The seven functional fixes are verified by automated reproductions on Windows. Linux/macOS were not built locally, and the remote performance gate had not evaluated these changes at verification time. Keep performance task R1 open until Linux CI confirms the instruction-count limits. Existing deferred feature/convergence tasks are outside this review repair and remain recorded in the feature task list. The user subsequently authorized separate fix commits on PR #549; these results apply to their combined source tree.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebe40490..8a8de4e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,42 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
+### Fixed
+- Muting or solo-gating a Session track discards keyswitch releases for the flushed voices,
+ preventing them from cutting a new articulation after unmute. Clip edits reuse the track's
+ Session player directly instead of allocating and discarding temporary playback state.
+- Session articulation keyswitches retain their 20 ms release across tempo changes. Copied map
+ files with duplicate IDs no longer prevent the articulation map manager from opening.
+- Articulation playback keeps chased keyswitch releases across audio blocks, restores switches on
+ Session launches, and preserves notes, releases and expression when timing offsets span short
+ loops. Overlapping clips restore their own techniques, and overlapping momentary notes keep a
+ shared switch held until the last note ends. The map manager prefers the project's saved map
+ when the library has a different version, including after undo.
+
+### Added
+- **Articulation maps** (specs/085): an instrument track can hold a map of the playing techniques
+ of a sample library (Long, Staccato, Legato…) and the MIDI that selects each one. Import a Cubase
+ `.expressionmap`, a Studio One `.keyswitch` list or Nota's own `.notamap` — from the Track
+ inspector's Articulations section or by dropping the file on it — and a preview shows every
+ articulation and everything the file couldn't carry over before the map is used. Right-click
+ notes in the piano roll ▸ Articulation to choose one per note; playback sends the keyswitches,
+ controllers and program changes to the hosted plug-in just ahead of the notes, once per phrase
+ for a latching articulation and held with the note for a momentary one, and re-sends what is in
+ force after a seek or a loop wrap. Built-in instruments are left alone. A note whose articulation
+ was removed from the map plays the default and is marked. Studio One `.soundvariation` files are
+ not supported yet.
+- **Articulation map manager** (View ▸ Articulation maps…, or Edit maps… in the inspector): create,
+ import, duplicate, delete and export maps; add, copy, remove and reorder articulations; edit
+ their names, colour, group, latching or momentary trigger, MIDI actions and channels, note
+ offset, trigger lead, enabled state and the default. Save updates every track using the map as
+ one undo step and says how many.
+- **Track MIDI offset** (specs/085): a track's notes can play earlier (negative) or later, to make
+ up for a slow attack, without moving them; each articulation can add an offset of its own, and a
+ trigger lead sends its switch ahead of the note. The inspector and the manager show when each
+ articulation's notes actually play. Saved with the project.
+- **Notes coloured by articulation** (specs/085): the palette chip in the clip editor header draws
+ notes in their articulation's colour instead of the track's.
+
### Changed
- **The manual opens in the interface language** (#539): Help ▸ Documentation and each device's
Documentation item open the French manual (`/fr/`) when Nota runs in French, the Russian one
diff --git a/FEATURES.md b/FEATURES.md
index f3c0f324..0b66931d 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -424,6 +424,33 @@ docks as a panel under any of the three, or floats in its own window — see
as several clips at once. Selecting a clip of the track makes it active and scrolls to it;
a clip on another track opens that track; new clips on the track join. The mode is
remembered.
+- **Articulation maps** — an instrument track can hold a map of a sample library's playing
+ techniques (Long, Staccato, Legato…) and the MIDI that selects each: keyswitch notes,
+ controllers, program changes and bank select, each on the note's channel or one of its own.
+ - **Import** a Cubase `.expressionmap`, a Studio One `.keyswitch` list or a Nota `.notamap`
+ from the Track inspector (Import…, a pick from the library, or a file dropped on it); the
+ file is recognised by its content, and a preview lists every articulation with what the file
+ couldn't carry over (Cubase stores palette indices, not colours; neither format stores
+ latching or momentary). Studio One `.soundvariation` files are not read.
+ - **Per-note articulations**: right-click notes → **Articulation** sets the selection's, as one
+ undo step; a note without one plays the map's default. Playback sends a **latching**
+ articulation once per phrase (its keyswitch released 20 ms later) and holds a **momentary**
+ one with its note, ahead of the note at the same position, in Session slots too; after a
+ seek or a loop wrap it re-sends what is in force. Only hosted plug-ins (and racks holding
+ one) receive it. A note whose articulation was removed plays the default and carries a
+ warning mark.
+ - **MIDI offset** (Track inspector, ±2000 ms): the track's notes play earlier or later without
+ moving; each articulation adds a **note offset** of its own and a **trigger lead** that sends
+ its switch ahead of the note. The inspector and the manager say when each articulation's
+ notes play.
+ - **Map manager** (View → **Articulation maps…**, or **Edit maps…** in the inspector): the
+ library's maps and any a project track holds; create, import, duplicate, delete, export
+ `.notamap`; add, copy, remove and reorder articulations and edit their names, colour, group,
+ trigger, actions, offsets, enabled state and the default. **Save** updates every track using
+ the map in one undo step.
+ - **Note colours**: the palette chip in the clip editor header colours notes by articulation.
+ - Maps, offsets and note articulations are saved with the project, which opens without the
+ library.
- **Clip tools (generate and transform)**: a **Tools** rail beside the piano roll with
fifteen tools that write or rewrite notes. Six **generators** — *Rhythm* (a pattern that
leans on the strong beats), *Seed* (learns the clip's own intervals and rhythm, then
@@ -1202,7 +1229,8 @@ audio effects after it keep running and keep their settings; saved with the proj
separates the device tabs from the library tabs, and the active one carries an orange edge.
- **Track inspector**: the last rail tab shows the track the Devices panel shows — its name
(type to rename), Mute / Solo / Arm, record input and input monitoring (audio tracks) or
- MIDI from (instrument tracks), colour, row height and the freeze commands (Freeze, Live
+ MIDI from and **Articulations** — the map, its import, MIDI offset and Edit maps…
+ (instrument tracks), colour, row height and the freeze commands (Freeze, Live
freeze, Unfreeze, Flatten, and Edit source / Done / Discard on a live-freeze link). A
return shows its name, Mute and colour; the master its name. Changes made from the
header, the track menu or undo show in it straight away.
diff --git a/specs/085-articulation-maps/checklists/requirements.md b/specs/085-articulation-maps/checklists/requirements.md
new file mode 100644
index 00000000..cfd0bc12
--- /dev/null
+++ b/specs/085-articulation-maps/checklists/requirements.md
@@ -0,0 +1,42 @@
+# Specification Quality Checklist: Articulation maps
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-11-09
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details (languages, frameworks, APIs)
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] Success criteria are technology-agnostic (no implementation details)
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified
+- [x] Scope is clearly bounded
+- [x] Dependencies and assumptions identified
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+- [x] No implementation details leak into specification
+
+## Notes
+
+- MIDI vocabulary (keyswitch, controller change, program change, bank select, channel) is the
+ domain language of the feature, not implementation. FR-025 names the audio thread because the
+ constitution makes real-time safety a requirement; how it is met belongs to the plan.
+- The Nota Context section is the template's designated place for code areas.
+- The Studio One format question was settled by the owner's files and is recorded under
+ Clarifications. `.soundvariation` is still unverified; FR-005 says so.
+- Open items for the plan, not blockers for the spec: how Session clips get offsets, and whether
+ Automatic Measurement is feasible (FR-026 allows reporting that it is not).
+- The approved-issue step (constitution principle 0): the work implements #547 (`approved`).
diff --git a/specs/085-articulation-maps/contracts/c-abi.md b/specs/085-articulation-maps/contracts/c-abi.md
new file mode 100644
index 00000000..f271235e
--- /dev/null
+++ b/specs/085-articulation-maps/contracts/c-abi.md
@@ -0,0 +1,87 @@
+# Contract: C ABI additions (`nota_engine.h`)
+
+Pure C, no exceptions (AR-7). All functions are on the message thread. The audio thread never
+calls them; it reads the published snapshot. `nota_*` symbols are exported by wildcard on every
+platform, so no export list changes.
+
+## Implemented and verified
+
+```c
+typedef struct NotaNoteData {
+ /* ...existing fields... */
+ int32_t articulation_id; /* 0 = none; appended LAST so older field offsets are unchanged */
+} NotaNoteData;
+
+NOTA_API NotaResult nota_track_set_midi_offset_ms(NotaEngine*, int32_t track_id, double ms);
+NOTA_API double nota_track_get_midi_offset_ms(NotaEngine*, int32_t track_id);
+```
+
+C# `NotaNote` mirrors the struct with `ArticulationId` as its last field; the two layouts must
+stay identical (`StructLayout.Sequential`). Because the struct grew, **the managed code and the
+native library must be built together**; a stale DLL with a new managed build would read garbage.
+
+## To add
+
+```c
+typedef struct NotaArticulationEntry {
+ int32_t id; /* > 0, unique, ascending */
+ int32_t trigger_mode; /* 0 latching, 1 momentary */
+ double offset_ms; /* added to the track offset */
+ double lead_ms; /* >= 0 */
+ int32_t action_start; /* index into the action array */
+ int32_t action_count;
+} NotaArticulationEntry;
+
+typedef struct NotaArticulationAction {
+ int32_t kind; /* 0 keyswitch, 1 control change, 2 program change, 3 bank MSB, 4 bank LSB */
+ int32_t channel; /* 0 = the note's own, 1..16 explicit */
+ int32_t data1; /* pitch / cc / program, 0..127 */
+ int32_t data2; /* velocity / value, 0..127 */
+} NotaArticulationAction;
+
+/* Gives the track its articulation map: the compiled table plus the map file as opaque JSON
+ * (saved with the project and restored by undo). One undo step. default_id 0 = none.
+ * Returns NOTA_ERR_INVALID_ARG for unsorted/duplicate ids, a range that leaves the action array,
+ * out-of-range values, or counts < 0. Nothing is changed on error. */
+NOTA_API NotaResult nota_track_set_articulation_map(NotaEngine*, int32_t track_id,
+ int32_t default_id,
+ const NotaArticulationEntry* entries, int32_t entry_count,
+ const NotaArticulationAction* actions, int32_t action_count,
+ const char* map_json, int32_t map_json_len);
+
+/* Removes the map (notes keep their ids). One undo step. */
+NOTA_API NotaResult nota_track_clear_articulation_map(NotaEngine*, int32_t track_id);
+
+/* Copies the stored map JSON out (out = NULL -> just the length). 0 = no map. */
+NOTA_API int32_t nota_track_get_articulation_map_json(const NotaEngine*, int32_t track_id,
+ char* out, int32_t max_len);
+
+/* Self-test with a recording test instrument: 0 on pass, otherwise the failed check number. */
+NOTA_API int32_t nota_engine_articulation_selftest(NotaEngine*);
+```
+
+## Rules
+
+- The engine validates every field it is given; the managed side's validation is not trusted.
+- `entries` ids ascend strictly; each `[action_start, action_start+action_count)` lies within
+ `actions`.
+- Changing offsets or lead times on a map applies through `nota_track_set_articulation_map`; there
+ is no per-articulation setter.
+- `nota_track_set_midi_offset_ms` clamps to ±2000 ms and treats NaN as 0.
+- Managed: `IAudioEngine.SetTrackArticulationMap`, `ClearTrackArticulationMap`,
+ `GetTrackArticulationMapJson`, plus `NotaEngine.ArticulationSelfTest()`.
+
+## Instrument interface (C++, not part of the C ABI)
+
+```cpp
+class Instrument {
+ int32_t eventChannel = 0; // 0 = default channel 1; otherwise 1..16
+ virtual void programChange(int32_t /*program*/) {} // default: ignored
+ virtual bool takesArticulations() const { return false; }
+};
+```
+
+`PluginInstrument` uses the event's explicit MIDI channel (1–16), or channel 1 when it is 0,
+and maps `programChange` to a real MIDI program change. Bank select uses `controller(0, v)`
+and `controller(32, v)`. `takesArticulations()` is true for hosted plug-ins and racks containing
+one; built-in instruments do not receive articulation actions.
diff --git a/specs/085-articulation-maps/contracts/import-formats.md b/specs/085-articulation-maps/contracts/import-formats.md
new file mode 100644
index 00000000..99f67c45
--- /dev/null
+++ b/specs/085-articulation-maps/contracts/import-formats.md
@@ -0,0 +1,83 @@
+# Contract: import formats
+
+What the importers read. Everything below is taken from real files (a Babylonwaves Art Conductor
+map for Cinematic Studio Strings, supplied by the owner and read locally; they are third-party
+works and are not in the repo); anything not shown by those files is listed as unknown, not
+guessed. The smoke test checks the importers on small maps written in the same shape.
+
+## Cubase `.expressionmap` (XML, root `InstrumentMap`)
+
+Source: `expressionmaps/CSSS Violins 1 A.expressionmap`.
+
+```
+InstrumentMap
+ string name="name" map name
+ member "slotvisuals" -> list of USlotVisuals a copy of each slot's visuals (ignored)
+ member "slots" -> list of PSoundSlot one articulation each
+ obj PSlotThruTrigger "remote" remote key (status 144, data1) -- ignored
+ obj PSlotMidiAction "action"
+ member "midiMessages" -> list of POutputEvent ordered output: {status, data1, data2}
+ int channel (-1 = note's own), key, key2, controller1num, controller1value (editor mirrors)
+ member "sv" -> list of USlotVisuals text (short name), description, group,
+ articulationtype, symbol, displaytype
+ member "name" -> string "s" articulation name
+ int color Cubase palette INDEX (not RGB)
+```
+
+| Source | Becomes |
+|---|---|
+| `POutputEvent` status 144 | keyswitch note (`data1` pitch, `data2` velocity) |
+| status 176, `data1` = 0 / 32 | bank select MSB / LSB (`data2`) |
+| status 176, other `data1` | control change |
+| status 192 | program change (`data1`) |
+| any other status | warning, kept in `metadata["unsupported.midi"]`, not sent |
+| status low nibble 0 | channel = note's own; non-zero nibble n -> channel n + 1 |
+| slot `color` | `sourceColorIndex`; `colorArgb` stays null |
+| `sv/group` > 0 | `groupId`; the group's name stays empty (the file has none) and the interface shows a numbered, translated label |
+| slot with no name | name `#N` (its 1-based position): saved data is language-neutral, never interface text |
+| first slot with no name and no events | skipped, reported |
+
+Seen in the owner's file: 45 slots, 44 articulations, events 144 (88) and 176 (44), every
+articulation has three actions, channel -1 throughout, group 0 throughout.
+
+**Unknown** (no file shows it): program change and bank select events, non-zero groups,
+slot-level channels other than -1, latching vs momentary (not stored). Two interpretations are
+assumptions, not facts from a Cubase file: status 192 is a program change (MIDI standard), and a
+status low nibble of 0 means "the note's own channel" (the owner's file writes nibble 0 together with
+slot channel -1; whether Cubase treats nibble 0 as channel 1 is unknown). Both are covered by
+synthetic tests only and the import preview must label them unverified.
+
+## Studio One `.keyswitch` (XML, root `Music.KeySwitchList`)
+
+Sources: the owner's `CSSS Violins 1 Attribute.keyswitch` and `CSSS Lite Ensemble Attribute.keyswitch` (read locally, not in the repo).
+
+```
+<Music.KeySwitchList name="...">
+ <Attributes name="Long" id="1" pitch="24" activation="note24.1|note35.1|unknown"/>
+```
+
+| Token in `activation` | Becomes |
+|---|---|
+| `noteP.V` | keyswitch pitch P, velocity V (`note24.1` = Cubase 144/24/1) |
+| `noteP` | keyswitch pitch P, velocity 127 (`note35` = Cubase 144/35/127) |
+| `unknown` | nothing; reported (in the CSS twin it is the CC 58 action) |
+| anything else | warning, skipped |
+
+Entry `id` 0 / name `---` with an empty activation is the empty default and is skipped. Colours,
+groups, channels and switch mode do not exist in this format.
+
+Verified: all 44 entries of the Violins file have keyswitch notes equal to the Cubase map's for the
+same name (checked by script on the real files and by the smoke test).
+
+## Studio One `.soundvariation`
+
+**No example file has been supplied.** There is no parser, no claim of support and no test. When a
+real file arrives, the first task is to read it and extend this contract before writing code.
+
+## Common rules for every importer
+
+- Decide by content (`Sniff`), not extension.
+- Refuse files over 16 MiB; XML with `DtdProcessing.Prohibit` and no resolver.
+- Never modify the source file (a test hashes it before and after).
+- Return a map plus a list of messages (info, warning, error); an error returns no map.
+- Never throw to the caller for bad content; only I/O errors are caught and reported.
diff --git a/specs/085-articulation-maps/contracts/nota-articulation-map-file.md b/specs/085-articulation-maps/contracts/nota-articulation-map-file.md
new file mode 100644
index 00000000..9a5fa5e7
--- /dev/null
+++ b/specs/085-articulation-maps/contracts/nota-articulation-map-file.md
@@ -0,0 +1,55 @@
+# Contract: Nota articulation map file (JSON)
+
+Used in three places with the same shape: the library folder (`articulations/*.notamap`), the
+`export` command, and `TrackDto.ArticulationMap` inside a project (embedded as a JSON object, not a
+string). UTF-8, camelCase, written with `System.Text.Json`. Properties this version does not know
+are ignored on read (not preserved); a newer `version` is refused instead (see Rules).
+
+```json
+{
+ "format": "nota-articulation-map",
+ "version": 1,
+ "id": "3f9c...32 hex",
+ "name": "CSSS Violins 1 Attribute",
+ "instrumentName": "Cinematic Studio Strings",
+ "description": null,
+ "defaultArticulationId": 1,
+ "groups": [ { "id": 1, "name": "Group 1" } ],
+ "articulations": [
+ {
+ "id": 1,
+ "name": "Long",
+ "shortName": "Long",
+ "colorArgb": 4283215696,
+ "sourceColorIndex": 2,
+ "groupId": 0,
+ "trigger": "latching",
+ "actions": [
+ { "kind": "keyswitch", "channel": null, "data1": 24, "data2": 1 },
+ { "kind": "keyswitch", "channel": null, "data1": 35, "data2": 1 },
+ { "kind": "controlChange", "channel": null, "data1": 58, "data2": 81 }
+ ],
+ "noteOffsetMs": 0,
+ "triggerLeadMs": 0,
+ "enabled": true,
+ "metadata": { "description": "Long" }
+ }
+ ],
+ "metadata": { "source.format": "expressionmap", "source.file": "CSSS Violins 1 A.expressionmap" }
+}
+```
+
+## Rules
+
+- `format` must be `nota-articulation-map`; `version` higher than the reader supports is refused
+ with a message, not partially read.
+- `kind` is one of `keyswitch`, `controlChange`, `programChange`, `bankSelectMsb`, `bankSelectLsb`.
+- `trigger` is `latching` or `momentary`.
+- Loading repairs deterministically and reports what it repaired: a missing or duplicate
+ articulation id gets the next free id (notes keep pointing at the file's ids, so a repaired id is
+ reported as a warning); an action out of MIDI range is dropped; a default id that does not exist
+ becomes null; offsets are clamped to ±2000 ms and leads to 0..2000.
+- A file larger than 16 MiB, nested deeper than 64 levels, or that is not valid JSON is refused.
+- A missing name becomes the file name (or "#" + the map id inside a project); a missing map id gets a new one.
+- Disabled articulations are written and read like the others; only the engine table leaves them out.
+- Exporting then importing yields an equal map (tested).
diff --git a/specs/085-articulation-maps/data-model.md b/specs/085-articulation-maps/data-model.md
new file mode 100644
index 00000000..7cac32c3
--- /dev/null
+++ b/specs/085-articulation-maps/data-model.md
@@ -0,0 +1,82 @@
+# Data Model: Articulation maps
+
+Three representations of the same data, each for one job:
+
+1. **Managed model** (`Nota.Application.Articulations`): editing, import, export, UI.
+2. **Map file / project JSON**: the managed model serialised (see
+ `contracts/nota-articulation-map-file.md`).
+3. **Compiled engine table**: flat, immutable, read by the audio thread (see
+ `contracts/c-abi.md`).
+
+## Entities
+
+### ArticulationMap
+| Field | Type | Rule |
+|---|---|---|
+| Id | string (32 hex) | Stable across rename and export; a duplicate gets a new one |
+| Name | string | Required, non-empty |
+| InstrumentName | string | Library or instrument it is for; may be empty |
+| Description | string? | Optional |
+| Version | int | Format version of the serialised map (now 1) |
+| DefaultArticulationId | int? | Must name an existing articulation or be null |
+| Groups | list of ArticulationGroup | Ids unique, > 0 |
+| Articulations | ordered list of Articulation | Order is display order |
+| Metadata | string map | Provenance (`source.format`, `source.file`, `source.comments`); never interpreted |
+
+### Articulation
+| Field | Type | Rule |
+|---|---|---|
+| Id | int > 0 | Unique within the map, **never reused** after a delete (`NextArticulationId` = max + 1) |
+| Name, ShortName | string | Name required; short name defaults to a prefix of the name |
+| ColorArgb | uint? | `0xAARRGGBB`; null = Nota's default colour for this slot |
+| SourceColorIndex | int? | Cubase palette index kept from the file; not RGB |
+| GroupId | int | 0 = none, else an existing group id |
+| Trigger | Latching or Momentary | Default Latching |
+| Actions | ordered list of MidiAction | Order is send order; empty is allowed (sends nothing) |
+| NoteOffsetMs | double | Added to the track offset; clamp ±2000 |
+| TriggerLeadMs | double ≥ 0 | Clamp 0..2000 |
+| Enabled | bool | Disabled articulations are skipped (note plays as default) |
+| Metadata | string map | Descriptions, original ids, unsupported constructs, raw activation strings |
+
+### MidiAction
+| Field | Type | Rule |
+|---|---|---|
+| Kind | Keyswitch, ControlChange, ProgramChange, BankSelectMsb, BankSelectLsb | |
+| Channel | int? (1..16) | null = the note's own channel |
+| Data1 | int | Keyswitch pitch / CC number / program; 0..127 |
+| Data2 | int | Keyswitch velocity / CC value / bank value; 0..127 |
+
+Validation (`MidiAction.IsValid`): channel null or 1..16; all data 0..127. An invalid action is
+dropped with an import warning, never stored.
+
+### Note (existing, extended)
+| Field | Where | Rule |
+|---|---|---|
+| `articulation` (C++) / `articulation_id` (ABI) / `ArticulationId` (C#) / `Articulation` (JSON) | per note | 0 = none; otherwise an id in the track's map; copying a note copies the id |
+
+### Track timing
+`MidiOffsetMs` (double, clamp ±2000, default 0) per instrument track. Persisted only when non-zero.
+
+### Derived: articulation timeline (engine only, never saved)
+Per clip, built at publish time from notes + table: sorted entries
+`{ startBeat, articulationId, endBeat }`. Latching neighbours with the same id collapse into one
+entry; momentary entries are one per note. Rebuilt whenever the clip's notes or the track's
+table change. Used for: trigger events and "articulation in force at beat X".
+
+### Derived: compiled table (engine)
+`ArticulationTable { defaultId, entries[] sorted by id, actions[] }` where an entry holds
+`{ id, offsetMs, leadMs, trigger, actionStart, actionCount }` (times stay in milliseconds and are
+converted with the sample rate at schedule time). Lookup by id is a binary search. Id 0 resolves to `defaultId`. An id that is missing or disabled resolves to
+`defaultId` (FR-014).
+
+## State transitions
+
+- **Assign map to track**: engine track gets the JSON blob and compiled table (undoable).
+- **Edit map**: managed edits a copy; applying replaces blob and table on every track using that
+ map (one undo step per track, grouped by `beginUndoGroup`).
+- **Delete an articulation**: the id is removed from the map; notes keep the id; resolution falls
+ back to default and the UI shows the id as missing. The id is not reused.
+- **Remove map from track**: notes keep their ids; with no table nothing is sent (the ids are kept
+ so re-assigning the map restores them).
+- **Duplicate map**: new map id; articulation ids unchanged, so notes written for the original
+ still resolve against the copy.
diff --git a/specs/085-articulation-maps/plan.md b/specs/085-articulation-maps/plan.md
new file mode 100644
index 00000000..421bdad0
--- /dev/null
+++ b/specs/085-articulation-maps/plan.md
@@ -0,0 +1,152 @@
+# Implementation Plan: Articulation maps
+
+**Branch**: `feat/articulation-maps` (PR #549 → `develop`) | **Date**: 2026-11-09 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `/specs/085-articulation-maps/spec.md`
+
+## Summary
+
+Add per-track articulation maps and per-note articulations. A map is engine state on the
+instrument track (JSON blob for save and undo, compiled immutable table for the audio thread),
+published with the graph snapshot (AR-5). The scheduler shifts note times by track offset plus
+articulation offset, and emits articulation MIDI (keyswitch, controller, program, bank) from a
+separate sorted event list, so MIDI effects cannot disturb it. A per-clip articulation timeline,
+built when the clip is published, retains every latching point; playback resolves deduplication
+across the track by trigger time. Arrangement scheduling uses immutable clips, the table, and
+the block's last chase origin. Session latching releases retain emitted channel/key pairs and
+remaining rendered frames in fixed audio-thread-owned storage, so tempo changes cannot skip a
+20 ms release. The queue never grows and still drains when the map is removed.
+Importers read the two real file formats seen (Cubase expression map,
+Studio One keyswitch list). UI: map manager, inspector section, note menu, note colours,
+drag and drop. Decisions and evidence: [research.md](research.md).
+
+## Nota: Read Before Planning
+
+Consulted: `ARCHITECTURE.md` AR rules (AR-4 queue, AR-5 snapshots, AR-6 audio-thread limits, AR-7
+pure C ABI), `DESIGN.md` for the UI, and `CONTRIBUTING.md` for licensing. The `nota-features`,
+`nota-docs` and `nota-shortcuts` skills apply at the end (FEATURES.md, manual, shortcuts).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine, plug-in host), C# / .NET 10 (managed app, Avalonia 12).
+
+**Primary Dependencies**: None new. XML parsing is `System.Xml` from the base library; JSON is
+`System.Text.Json`. JUCE stays in `pluginhost/` (the `PluginInstrument` change).
+
+**Storage**: Project file (`TrackDto.ArticulationMap`, `TrackDto.MidiOffsetMs`,
+`NoteDto.Articulation`, format version 30) and a user library folder
+`NotaPaths.SubDir("articulations")`.
+
+**Audio-Thread Impact**: Yes, in the render path. The audio thread reads an immutable table and
+per-clip timeline through the graph snapshot; the track offset is a relaxed atomic. No allocation,
+lock or I/O: articulation events use a fixed 256-event stack array, and Session latching releases
+use fixed-capacity audio-thread-owned storage. Overflow never grows the buffers; wiring dropped
+event counts into the render call sites remains T092. Tables and timelines are built on the message
+thread. `Instrument::takesArticulations()` gates switch delivery to hosted plug-ins or racks
+containing one; built-ins still receive offset musical notes without articulation actions.
+
+**Testing**: `tests/Nota.SmokeTest`: pure managed tests (importers, file format, model), engine
+tests through a recording `Probe : Instrument` exposed as `nota_engine_articulation_selftest`, and
+project round trips. Real Kontakt playback is a manual owner check.
+
+**Target Platform**: Windows x64 first (the build available); no platform-specific code, so Linux
+and macOS are not expected to differ.
+
+**Project Type**: Desktop app (native engine + Avalonia UI).
+
+**Performance Goals**: No new dropouts on the existing perf test; scheduling cost O(notes in block
++ log articulations) per track per block.
+
+**Constraints**: Offsets in milliseconds independent of tempo; ±2000 ms; no invented library
+measurements. Native builds are verified locally on Windows and in CI on all three platforms;
+the initial dependency blocker in research R12 is historical.
+
+**Scale/Scope**: Maps of ~50 articulations per track; clips with thousands of notes.
+
+## Constitution Check
+
+*GATE: pass before research; re-checked after design.*
+
+| Principle | Status |
+|---|---|
+| 0. Approved issue first | Pass: #547, labelled `approved`. (The work started locally before the issue was linked; that waiver is now closed.) |
+| I. Real-time safety | Pass by design (table and timeline immutable and published with the snapshot; scratch and Session release queue fixed-size; pending keys and chase origins audio-thread-owned). Native scheduler/Session probes and audio-thread review cover the fixes. Source `6c876cf5` passes the Linux instruction-count gate (all 63 scenarios, run `42629193021`). |
+| II. Boundary discipline | Pass: only POD structs and `nota_*` C functions cross; no JUCE outside `pluginhost/`. |
+| III. Licensing | Pass: no dependency. Every new file needs the SPDX header (done for the files written so far). |
+| IV. Verification gate | Pass: full local Windows build/smoke/scanner/scan-scale and 414 focused articulation checks; CI build and smoke pass on macOS, Windows and Linux (run `42629193115`). |
+| V. One logical change | The feature is large; delivery is split into the phases below, each independently buildable and testable. |
+| VI. Docs in sync | CHANGELOG and FEATURES.md updated; EN/RU manual built and checked, patch attached for upstream integration. No new shortcut. See review-evidence.md. |
+| VII. Spec-first | **Deviation to correct**: code (note id, track offset, scheduler shift, model, importers, importer tests) was written before this plan. It is provisional; `/speckit-tasks` lists it as tasks to review and `/speckit-converge` must pass over it. |
+| VIII. Rules not weakened | Pass. |
+
+Post-design re-check: unchanged. The one new risk is the timeline going stale if a note edit skips the
+publish step (research R5); Phase B's first task closes it.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/085-articulation-maps/
+├── plan.md
+├── research.md
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── c-abi.md
+│ ├── nota-articulation-map-file.md
+│ └── import-formats.md
+├── checklists/requirements.md
+└── tasks.md # created by /speckit-tasks, not by this command
+```
+
+### Source Code (what this feature touches)
+
+```text
+src/native/nota.engine/
+├── include/nota/nota_engine.h # note field, offset, map functions, self-test
+├── src/abi/nota_engine_track.cpp # ABI implementations
+├── src/engine/MidiClip.h # Note.articulation, clip timeline
+├── src/engine/Track.h # offset, map blob, compiled table
+├── src/engine/ArticulationTable.h/.cpp # NEW: table, timeline builder, lookup
+├── src/engine/Engine*.cpp # set/clear map, cloneTrack, noteFrom/ToData, scheduler, self-test
+├── src/devices/Instrument.h # eventChannel, programChange
+└── pluginhost/hosting/PluginInstrument.cpp # channel and program change to real MIDI
+
+src/managed/
+├── Nota.Application/Articulations/ # model, importers (written), export, library port
+├── Nota.Infrastructure/ # P/Invoke, project DTOs, migrations, library store
+└── Nota.App/ # manager, inspector section, note menu/colours, drop
+
+tests/Nota.SmokeTest/ # ArticulationImportTests (inline maps; no vendor files), engine tests
+```
+
+**Structure Decision**: Extend existing layers; no new project. The engine type lives in its own
+file pair so `Engine_Render.cpp` (RT-hot) only gains the scheduling calls.
+
+## Delivery phases
+
+Each phase builds, passes its tests, and is usable alone. Tasks are generated from these.
+
+- **Phase A: Foundations (partly written).** Note id and track offset through engine, ABI, C# and
+ project; format 30. Importers and model; importer tests. Close R5's choke-point question.
+ *Blocked on the native build for the engine half.*
+- **Phase B: Scheduling.** Table and timeline; `ArtEv` stream; keyswitch hold; chase on seek, loop and
+ start; `eventChannel` and `programChange` through `PluginInstrument`; engine self-test.
+- **Phase C: Edge handling.** Negative offset near the loop seam (lookahead), Session slots, deleted or
+ disabled articulations, overflow behaviour.
+- **Phase D: Manager and assignment.** Library store, manager window, inspector section, offsets UI
+ with effective-offset readout, export/import of Nota files, undo.
+- **Phase E: Notes in the piano roll.** Context menu, note colours and Note Color Mode (no
+ Articulation Lane: dropped at the owner's request); check every C# place that rebuilds notes by field.
+- **Phase F: Drag and drop, presets, measurement.** Explorer drop onto manager and inspector (header
+ if feasible); user-saved offset presets; measurement feasibility, implemented only if verified.
+- **Phase G: Docs and verification.** CHANGELOG, FEATURES.md, manual, shortcuts, full build and smoke
+ test, the owner's Kontakt checks, `/speckit-converge`.
+
+## Complexity Tracking
+
+| Violation | Why Needed | Simpler Alternative Rejected Because |
+|-----------|------------|-------------------------------------|
+| Constitution VII (code before plan) | Early slices were written before the Spec Kit process was applied | Deleting working code adds risk; tasks mark it for review and converge covers it |
+| Separate `ArtEv` stream in `playEvents` | Keyswitches must bypass MIDI FX and keep action order | Putting them in `MidiEv` lets the arpeggiator touch them and `std::sort` reorder them |
diff --git a/specs/085-articulation-maps/quickstart.md b/specs/085-articulation-maps/quickstart.md
new file mode 100644
index 00000000..b7801440
--- /dev/null
+++ b/specs/085-articulation-maps/quickstart.md
@@ -0,0 +1,80 @@
+# Quickstart: validating articulation maps
+
+How to prove the feature works end to end. Each scenario says what it needs and what must happen.
+Contracts: [`contracts/`](contracts/); data: [`data-model.md`](data-model.md).
+
+## Prerequisites
+
+- Windows x64, MSVC Build Tools 2022, CMake, Ninja, .NET SDK 10, PowerShell 7.
+- **Native engine built.** This needs the CMake dependencies available offline (see `research.md`
+ R12). Until then only the managed scenarios (A, B) can run.
+- No vendor map files are in the repo (they are third-party works). Scenarios A and B need your
+ own: a Cubase `.expressionmap` and the Studio One `.keyswitch` list for the same library. The
+ smoke test covers the importers on small maps it writes itself.
+- Scenario G needs Kontakt with Cinematic Studio Strings on the owner's machine.
+
+## Automated
+
+```powershell
+# Managed only (no engine needed): importers
+dotnet run --project tests/Nota.SmokeTest -- --articulations
+
+# Everything (builds native + managed + smoke test)
+pwsh -NoProfile -File .\scripts\build-win.ps1
+```
+
+## Scenarios
+
+**A. Import a Cubase map** (manual, with your own file; the importer itself is covered by the smoke test on inline maps). For example `CSSS Violins 1 A.expressionmap` gives 44 articulations,
+Long first with keyswitch 24/1, keyswitch 35/1, CC 58 = 81 in that order; the empty slot is
+reported as skipped; the file's SHA-256 is unchanged.
+
+**B. Import a Studio One list and compare** (manual, with your own files). For example `CSSS Violins 1 Attribute.keyswitch` gives
+44 articulations; for each, its keyswitch notes equal the Cubase map's keyswitch notes of the same
+name; the `unknown` action is reported.
+
+**C. Offsets** (automated, needs engine). On a track with a recording test instrument: track offset
+-100 ms and Legato -150 ms put a Legato note-on 250 ms before its grid position at 120 and at 60
+BPM (same milliseconds, different beats); the notes in the clip are unchanged; offset 0 matches the
+old behaviour sample for sample.
+
+**D. Keyswitch timing** (automated, needs engine). With lead 30 ms the actions arrive 30 ms before
+the note-on, in the file's order, before the note; a latching keyswitch is released 20 ms later; a
+momentary one with its note; a chord with two articulations triggers each once.
+
+**E. Seek, loop and restart** (automated, needs engine). Seeking into a phrase, a loop wrap and
+Stop/Play each send the articulation in force once before the first note, never twice, and leave no
+held keyswitch after Stop.
+
+**F. Persistence and undo** (automated). Save then reopen restores the map, the track offset and
+every note's articulation; a v29 project opens unchanged; assigning a map, changing a note's
+articulation and editing a map each undo and redo; a deleted articulation leaves its notes playing as
+the default.
+
+**G. Real library** (manual, owner). Import the Cubase map, assign it to a Kontakt track with CSS
+Violins, put Long, Legato and Staccato notes in a clip, press play: Kontakt must switch to the right
+sound for each note (watch its keyswitch display). Set the track offset to about -80 ms and check
+the attacks land on the beat by ear and against a click. **Not claimed to work until the owner has
+done this.**
+
+**H. Drag and drop** (manual). Drag `.expressionmap` and `.keyswitch` files from Explorer onto the
+Articulation Map Manager, then onto the track inspector's Articulation section: a preview with
+warnings appears, accepting assigns the map. A renamed text file is refused.
+
+**I. Colours** (manual). Switch Note Color Mode: notes recolour, selection stays visible; switch
+back and the track colours return.
+
+## Results
+
+- **H (2026-11-09, owner, Windows):** import from the inspector's file picker and drop from Explorer both open the preview; Assign to track puts the map on the track. Reported: works. Editing a map is not available yet (US5).
+- **T043 (2026-11-09, owner):** an articulation set from the note menu did not play until the note was moved. Cause: the piano roll's changed-clip test (SameNotes) compared notes field by field and skipped ArticulationId, so an articulation-only edit was never sent to the engine. Fixed with NotaNote.Same (all fields; a smoke test fails if a field is ever left out) and engine self-test check 22 (an articulation-only edit makes the clip's timeline stale and it is rebuilt). Waiting for the owner's re-test.
+- **T043 re-test (2026-11-09, owner):** articulation set from the note menu plays without moving the note. Works.
+- **G (2026-11-09, owner, Windows, Kontakt + Cinematic Studio Strings, Violins 1):** the Cubase map assigned in the inspector, articulations set per note in the piano roll; on playback Kontakt switches articulation with each phrase. Works. Not yet checked by ear: offset compensation (no inspector field yet).
+- **A–F (2026-11-09, T073, Windows, full smoke test 5401 pass / 0 fail, 153 articulation checks):**
+ - *Note: A and B were run on the owner's Art Conductor files while they were local test fixtures; the files were then removed (third-party works) and the smoke test now checks the same rules on small inline maps.*
+ - **A — passes.** The Cubase map imports 44 articulations; the empty slot is skipped and reported; Long is first with Keyswitch 24/1, Keyswitch 35/1, CC 58 = 81 in file order; importing never modifies the file (SHA-256 compared).
+ - **B — passes.** The Studio One list imports 44; every keyswitch matches the Cubase map's for the same name (44 ok, 0 off); the `unknown` action is reported.
+ - **C — passes.** Track −100 ms + Legato −150 ms plays the note 250 ms early at 120 BPM and at 60 BPM (12000 samples both times); the clip's notes are unchanged; with no offset the Session-slot note loop is unchanged.
+ - **D — passes, one claim untested.** Lead (30 ms before), file order, the 20 ms latching release and the momentary hold are self-test checks 2–6 and 16. Not tested: a chord with two articulations. By design (data-model, `buildArticulationTimeline`) a chord's highest note sets the latching articulation, so two latching articulations in one chord send one switch, not one each; two momentary ones each send their own.
+ - **E — passes, one claim untested.** A seek into a phrase, a landing inside a held momentary note and a loop wrap each send what is in force once (self-test 11–15), never twice. Not tested: no keyswitch left held after Stop. By design Stop's all-notes-off reaches every channel an articulation used (`PluginInstrument::allNotesOff`), but no check exercises it.
+ - **F — passes, one claim covered indirectly.** Save and reopen restore the map, the track offset and each note's articulation; a v29 project migrates with no offsets or articulations; assigning a map, a note's articulation and the track offset each undo and redo; removing an articulation keeps the notes' ids. That such a note plays the default is the engine's `ArticulationTable::resolve` fallback, which the self-test doesn't hit with a missing id.
diff --git a/specs/085-articulation-maps/research.md b/specs/085-articulation-maps/research.md
new file mode 100644
index 00000000..f13f6748
--- /dev/null
+++ b/specs/085-articulation-maps/research.md
@@ -0,0 +1,215 @@
+# Research: Articulation maps
+
+Phase 0 of `/speckit-plan`. Each decision names what was verified in the repository and what
+was not. "Unverified" means no code or file in this checkout proves it.
+
+## R1. Where articulation data lives in the engine
+
+- **Decision**: The map is engine state on the **instrument track**, as two things published
+ together with the graph snapshot: (a) an opaque JSON blob (what the project saves and undo
+ restores) and (b) a compiled, immutable `ArticulationTable` the audio thread reads. A note
+ carries only an integer articulation id.
+- **Rationale**: The engine owns undo (`pushUndo`, graph snapshots through `republishWithTrack`).
+ If the map lived only in managed code, undo would restore notes but not the map. Putting it in
+ the track makes assign, edit, undo, redo, duplicate-track and save all follow the existing path
+ (AR-5: immutable snapshot published, the audio thread never sees a half-built table).
+- **Alternatives**: Managed-only catalog with the engine holding a copy (rejected: two sources of
+ truth, undo drift). Per-note inline actions (rejected: bloats notes, loses "edit the map once").
+- **Verified**: `Track` fields are copied in `cloneTrack` (`Engine.cpp` ~675) and the duplicate
+ path (`Engine_Tracks.cpp` ~3672); clip controllers are already shared immutable `shared_ptr`s
+ (`MidiClip.h`), the same pattern.
+
+## R2. How articulation MIDI reaches the instrument
+
+- **Decision**: Articulation actions are **not** put in the note stream. The scheduler builds a
+ separate, sorted `ArtEv` list per block and `playEvents` merges it with notes and expression.
+ `ArtEv` = `{off, seq, kind, channel, data1, data2}`; equal offsets keep `seq` (action order).
+- **Rationale**: MIDI effects (`applyMidiEffects`, e.g. the arpeggiator) transform the note
+ stream after `gatherInstrumentNotes`. A keyswitch placed in it would be arpeggiated or
+ filtered. Keyswitches must bypass MIDI FX. `std::sort(midiEvLess)` is not stable, so actions
+ that must stay in file order need their own sequence key.
+- **Alternatives**: Prepend keyswitch notes to the note list (rejected: MIDI FX, sort order).
+ Send from the message thread (rejected: breaks sample accuracy and AR-4/AR-6).
+- **Verified**: `computeInstrumentMidi` sorts, runs the DrumRack swing and MIDI FX, then
+ `playEvents` delivers; `playEvents` already merges `MidiEv` and `ExprEv` by offset and has a
+ timed-events path for hosted plug-ins.
+
+## R3. Channel, program change and bank select on the `Instrument` interface
+
+- **Recipient gate (implemented)**: `Instrument::takesArticulations()` defaults to false;
+ hosted plug-ins return true, as do racks containing one. Built-in instruments therefore
+ receive no articulation actions. This avoids treating a library's keyswitch as a musical
+ note on a built-in synth. Note timing offsets still apply. The user guide documents the gate.
+- **Decision**: Add `int32_t eventChannel = 0` beside `eventOffset` (0 = the note's own / channel
+ 1) and `virtual void programChange(int32_t program)` (default: ignore). Bank select goes
+ through the existing `controller()` path with CC 0 and CC 32. `PluginInstrument` uses
+ `eventChannel + 1` instead of its hardcoded `1`, and maps `programChange` to
+ `juce::MidiMessage::programChange`. Built-ins ignore both.
+- **Rationale**: `eventOffset` already shows how to hand per-event data to an instrument without
+ changing every `noteOn` signature across built-in instruments.
+- **Verified**: `PluginInstrument.cpp` hardcodes channel 1 in `noteOn`, `noteOff`, `controller`,
+ `allNotesOff`; `controller()` accepts ctl 0..127 as a CC with the value quantised through
+ `u7(v) = lround(v*127)`, so a CC value N is sent as `N/127.0f` and round-trips exactly.
+- **Unverified**: that Kontakt reacts to program change or bank select. CSS needs neither (its
+ files use keyswitch notes and CC 58, seen in the owner's files).
+- **Implemented (T018)**: `PluginInstrument` sends every engine-driven event on `chan()` (the
+ articulation's channel, else 1) and remembers which channels it used, so `allNotesOff`
+ flushes channel 1 plus only those (a plug-in never driven off channel 1 still gets exactly one
+ message). Its `MidiBuffer` is pre-sized to 8 KiB, so the extra messages don't allocate.
+ `RackInstrument` forwards the channel with controllers and program changes to every chain.
+- **Limit (racks)**: a keyswitch *note* sent to an Instrument Rack goes through the rack's note
+ fan-out like any note: chain key/velocity zones and chain MIDI effects apply, and it reaches
+ the chain on channel 1. A plug-in hosted directly on the track has neither limit. Documented
+ for the user manual (T079).
+
+## R4. Offsets and the lead time (the scheduling rule)
+
+- **Decision**: `effective = nominal + trackOffsetMs + articulationOffsetMs`;
+ `trigger = effective - leadMs`. Milliseconds convert to samples with the device sample rate
+ (`ms * sr / 1000`), not through samples-per-beat. A note-on is emitted in the block that contains
+ its **effective** time; the actions in the block that contains the **trigger** time. Note-off
+ uses the same shift as note-on (length preserved).
+- **Rationale**: The engine decides what plays by comparing sample positions with the block window
+ (`gatherInstrumentNotes`). Shifting the sample position is the smallest change that preserves
+ every existing rule (clip active, clip end, seams, chase).
+- **Consequences (documented limits, spec FR-023)**:
+ - Playback that starts inside `[effective, nominal)` of a note: its note-on is already past.
+ The existing chase rule re-triggers it late only if the note is still held (`offS > blockStart`);
+ a shorter note is not played. This is the "cannot be scheduled early" case.
+ - A positive offset can push a note past a loop end; the transport wraps first, so it is not played
+ in that pass.
+ - A negative offset on a note at the loop start cannot sound before the wrap in the first
+ version. Lookahead across the loop seam is a later task (see Plan, Phase C).
+- **Verified**: the first slice (track offset applied to `onS`/`offS` in `gatherInstrumentNotes`)
+ is already written; it is not yet built or tested.
+
+## R5. Keyswitch state without runtime state
+
+- **Decision**: The scheduler is stateless per block. At publish time (message thread) each clip
+ with a map gets a derived, immutable **articulation timeline**: notes sorted by start, with
+ consecutive latching notes of the same articulation collapsed to one change point; momentary
+ articulations stay one entry per note. At run time a block emits the change points whose trigger
+ time falls in the block; on a seek, loop wrap or start (`chaseNotes_`) it also emits the
+ articulation in force at the block start, found by binary search, at offset 0.
+- **Rationale**: Dedupe ("no duplicate triggers") and "restore state after a seek" both need to
+ know the previous articulation. Scanning all notes per block for it is O(n²) in the worst case;
+ keeping state on the audio thread breaks on seeks. A precomputed timeline makes both exact and
+ allocation-free.
+- **Choke point (T012, traced 2026-11-09)**: `Engine::publishRaw` (`Engine.cpp`). Every graph the
+ audio thread can see passes through it: `publish` → `publishRaw`; `republishWithTrack` →
+ `republishWithTrackRaw` → `publishRaw` (84 + 23 callers); 30 direct callers including undo/redo
+ (`restored = true`). The only other `graphHist_.publish` is the constructor's empty graph.
+ All 37 writes to `notes` / `midiClips` in `src/engine/*.cpp` (note set, recording incl. session
+ takes and pickup shifts, split, trim, slice, consolidate, move between tracks, duplicate, take
+ retry) are made on a fresh `cloneTrack` copy or on a new local clip pushed into one, before that
+ copy is published. No code edits notes on a published track in place.
+- **Where the timeline is rebuilt**: in `publishRaw`, beside the existing `settleTakeJoins` pass,
+ which already does the same thing for derived take joins: for each track of the new graph that
+ is **not** shared with the current `authoring_` graph (a fresh clone the audio thread has never
+ seen), rebuild the timeline of every MIDI clip and Session slot clip from its notes and the
+ track's table; with no table, clear them (a clone copies its source's timelines). Tracks shared
+ with the current graph are untouched. Restored tracks (undo, redo) were published before with a
+ timeline that matches their notes and table, so they need nothing. A track without a map costs
+ nothing.
+- **Cost**: O(n log n) per clip of an edited track that has a map, on the message thread; a
+ live piano-roll drag (`setClipNotesLive`) pays it per frame. To be measured in T072.
+- **Alternatives**: Re-send the keyswitch before every note (rejected: breaks legato scripts and
+ FR-021 "no duplicate triggers"). Hold "last sent" in the instrument (rejected: wrong after a seek).
+
+## R6. Latching and momentary keyswitch release
+
+- **Decision**: A latching keyswitch note is released after a fixed 20 ms hold (a named constant);
+ a momentary one is released when its note ends. Both are scheduled by time, statelessly, like
+ note-offs. Controller, program and bank actions have no release.
+- **Rationale**: Cubase sends a keyswitch note-on and a note-off right away for its "direct"
+ articulations. 20 ms is long enough for any script to see it and short enough to avoid
+ overlapping the next trigger.
+- **Unverified**: the exact hold some Kontakt scripts want. Exposed as a constant; if a library
+ needs more, make it a per-articulation field.
+
+## R7. Session clips
+
+- **Decision**: Session slots get the same offset and articulation path, implemented after the
+ Arrangement one by sharing one helper. `renderSessionSlotRaw` already scans the current and next
+ loop iteration, so a shifted note near the slot end naturally lands in the next iteration.
+- **Verified**: `renderSessionSlotRaw` iterates `it = i0..i0+1` and tests `onAbs` against `[p, p+db)`.
+
+## R8. Persistence
+
+- **Decision**: `TrackDto.ArticulationMap` (the map as Nota's file format, spec in
+ `contracts/nota-articulation-map-file.md`), `TrackDto.MidiOffsetMs` and `NoteDto.Articulation`
+ (the last two already written), format version 30 with a no-op migration. A user library folder
+ `NotaPaths.SubDir("articulations")` holds the same JSON for reuse across projects.
+- **Verified**: `NotaPaths.SubDir`, the `PresetStore` pattern and `[JsonExtensionData]` exist.
+ Unknown properties survive a load/save cycle, so older builds that read a v30 file lose nothing
+ they did not understand (they refuse files with a higher version, as today).
+
+## R9. Importers (what is and is not known)
+
+| Format | Evidence | Parsed | Not stored in the file |
+|---|---|---|---|
+| Cubase `.expressionmap` | Real file: Art Conductor "CSSS Violins 1 A" (45 slots) | names, short names, descriptions, order, output events `{status,data1,data2}` (144 note, 176 CC), palette colour index, group number | switch mode, RGB colour, group names |
+| Studio One `.keyswitch` | Real file: "CSSS Violins 1 Attribute" (+ Lite Ensemble); entries cross-checked against the Cubase twin | names, ids, keyswitch notes (`noteP.V`), original activation string | colours, groups, channels, the CC that CSS uses (`unknown`) |
+| Studio One `.soundvariation` | **No file seen** | **nothing: not implemented** | n/a |
+
+- Cross-check result (from the real files): all 44 non-empty entries have the same keyswitch notes
+ in both formats; `noteP.V` is velocity V and `noteP` is velocity 127; `unknown` is the CC 58
+ action the keyswitch format cannot hold.
+- Not verified because no file shows it: program change and bank select in Cubase maps, non-zero
+ groups, the slot-level channel field when it is not -1, momentary vs latching.
+- The importers use `System.Xml` (base class library), DTD processing prohibited, size bounded.
+
+## R10. Library presets and automatic measurement
+
+- **Library Preset mode**: Nota will **not** ship recommended offsets it cannot source. Presets are
+ user-saved sets of offsets that can be applied and overridden. Values for a named library are
+ added only when the owner supplies them or measurement produces them.
+- **Automatic Measurement**: plausible, **unverified**. The engine can bounce a track's audio offline
+ (`freeze` begin/end) and has offline rendering. A measurement would need an ABI to inject a
+ probe keyswitch and note into the track's instrument during an offline render, then an
+ onset detector (`TempoDetect` has an onset-novelty envelope to reuse). Whether a hosted
+ Kontakt instance renders correctly in that offline path is unknown and needs the owner's
+ machine. Scheduled last (Phase F); the report must say "not verified" unless it is.
+
+## R11. UI integration points (located; behaviour not yet read)
+
+- Piano-roll note colour: `NoteGrid.Render` in `PianoRollView.cs` uses `_o.ColorOf(i)` for the
+ normal branch; selected, ghost and locked branches are separate. Hook point for Articulation Color.
+- Note context menu: a right-click path on `NoteGrid` was **not located**; the first UI task finds it.
+ `MenuFlyout` + `MenuKit.Item` is the pattern (`ShowResetMenu`, controller picker).
+- Inspector: new "Articulations" section in `TrackInspectorView.cs`, gated by `IsInstrument`.
+- Drop: `BrowserView.ExternalPaths` and the Mosaic SFZ drop (`HookDrop`) are the patterns.
+- **Note rebuilds (T011, audited 2026-11-09).** Searched `src/managed` for `new NotaNote(`,
+ target-typed `new(x.Pitch…)`, initializers and `default(NotaNote)`, and `src/native` for `Note`
+ built from fields:
+
+ | Site | What it does | Verdict |
+ |---|---|---|
+ | `Nota.Mcp/Tools/MidiTools.cs` `ToEngine`/`FromEngine` | MCP `get_clip_notes` → agent edits → `set_clip_notes` | **Was lossy; fixed**: optional `Articulation` on the MCP `Note` record, mapped both ways |
+ | `Nota.Mcp/Tools/SessionTools.cs` `ToEngine`/`FromEngine` | same for Session slots | **Was lossy; fixed** the same way |
+ | `Nota.App/PianoRollView.cs:2409` | a click draws a new note | new note: none is correct |
+ | `Nota.App/DrumPatternView.cs:181` | step sequencer creates notes | new note: none is correct |
+ | `Nota.App/MainWindow.Convert.cs` (4 sites) | audio → MIDI conversion | new notes: none is correct |
+ | `Nota.Application/Midi/MidiFileReader.cs:102` | MIDI file import | new notes: none is correct |
+ | `Nota.Application/Ports/IClipAi.cs:38` | AI-generated notes | new notes: none is correct |
+ | `Nota.Application/Twin/TwinPatterns.cs:307` | pattern generator | new notes: none is correct |
+ | `Engine_Render.cpp` 479/535 (`collectRecorded`) | recorded notes into a take | new notes: none is correct |
+ | `Engine_Tracks.cpp` `noteFromData` | ABI → `Note` | carries the id (T004) |
+
+ `MidiTransforms`, `NoteOverwrite` and `ClipSet` (named earlier as suspects) copy notes as values
+ (`var c = n; c.StartBeat = …`) and never rebuild them; the struct copy keeps `ArticulationId`.
+ Native split, trim, consolidate and duplicate copy `Note` by value. Behavioural proof that edits
+ keep the id is T045.
+
+## R12. Build and test environment
+
+- **Resolved 2026-11-09**: the native CMake configure downloads CPM and its pinned dependencies
+ (nlohmann_json, JUCE, miniaudio, signalsmith and others). No offline cache existed, so the owner
+ allowed the download. They now live in `src/native/nota.engine/build/_deps` (git-ignored). The
+ native engine builds with MSVC x64 + Ninja (324 steps, 0 errors), the scanner self-test passes,
+ and the full smoke test passes.
+- Managed code builds today without the engine (`Nota.Application` compiled). Engine-dependent
+ smoke tests need the native library.
+- The importer tests are pure managed code and can run as soon as the smoke-test project builds.
+- Git Bash exists (`C:\Program Files\Git\bin\bash.exe`), so `.specify/scripts/bash/*` can run
+ if needed; no script here needs a branch.
diff --git a/specs/085-articulation-maps/review-evidence.md b/specs/085-articulation-maps/review-evidence.md
new file mode 100644
index 00000000..eaa7c5e7
--- /dev/null
+++ b/specs/085-articulation-maps/review-evidence.md
@@ -0,0 +1,51 @@
+# PR #549 documentation and evidence
+
+Approved issue: [#547](https://github.com/nota-daw/nota/issues/547).
+PR: [#549](https://github.com/nota-daw/nota/pull/549).
+Prepared using `.claude/skills/nota-pr/SKILL.md` and `.claude/skills/nota-docs/SKILL.md`.
+
+## User documentation
+
+The English and Russian articulation-map manual pages explain import, per-note assignment,
+colours, track/articulation offsets, trigger lead, editing, export, project persistence and
+the timing limits at playback/loop starts. The related piano-roll and track pages link to them.
+The native recipient gate, rack restrictions, unsupported `.soundvariation`, existing-group
+editing, action ordering and deferred measurement/presets are stated explicitly.
+
+- [English guide](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/user-guide.md)
+- [Russian guide](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/user-guide.ru.md)
+- [Manual repository patch](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/nota-docs.patch)
+
+The patch targets `nota-daw/nota-docs` develop `05732b0`, includes a deterministic
+`articulations` scene for its normal screenshot runner, and normalizes Windows path separators
+in the docs checker. It is committed separately in the local `../nota-docs` repository and
+attached for integration; it has not been published to the upstream manual site.
+
+Validation: three manual screenshots captured; `npm run build` passes (322 pages),
+`npm run check` passes with zero errors. Existing documentation warnings and French translation
+gaps remain visible in the checker output. No keyboard shortcut was added by this feature.
+
+## UI evidence
+
+[Screenshot index and reproduction](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/screenshots.md).
+Real Avalonia UI, Studio Dark, 2× rendering, isolated demo data. Inspector and piano-roll
+before/after pairs use the same dimensions, theme, track name and note geometry. The before UI
+comes from `ad5b1c6f`; the after UI comes from `6c876cf5`. No vendor files or personal data
+are included. The demo's MIDI mappings and latency values are illustrative.
+
+## Engine evidence
+
+- [Charts, tables, machine and reproduction](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/summary.md)
+- [Full canonical CI report](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/report.md)
+- [All scenario rows as CSV](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/engine-comparison.csv)
+- [Cross-platform CI](https://github.com/nota-daw/nota/actions/runs/42629193115): Windows, macOS and Linux pass.
+- [Performance CI](https://github.com/nota-daw/nota/actions/runs/42629193021): all 63 engine scenarios and all three idle-CPU jobs pass.
+
+Both workflows test source `6c876cf5`; subsequent changes in this documentation batch do not
+change engine or application behaviour. Windows full native/managed/smoke/scanner/scan-scale
+validation also passed locally; the focused articulation suite passes all 414 checks, including
+38 native probes. The render-pool checks remain unchanged.
+
+The latest split/undo instruction change is −0.10% against the base. The attached Windows
+before/after timing has overlapping ranges and is reported without claiming a speedup.
+The controlled mapped-library benchmark (T072) and remaining convergence items stay open.
diff --git a/specs/085-articulation-maps/spec.md b/specs/085-articulation-maps/spec.md
new file mode 100644
index 00000000..cdd6c7ec
--- /dev/null
+++ b/specs/085-articulation-maps/spec.md
@@ -0,0 +1,343 @@
+# Feature Specification: Articulation maps
+
+**Feature Branch**: none (worked on the checked-out `develop` branch, local only)
+
+**Created**: 2026-11-09
+
+**Status**: Draft
+
+**Input**: User description: "A native Articulation Map system for orchestral sample libraries (Kontakt, Cinematic Studio Strings and similar), with the workflows of Cubase Expression Maps and Studio One / Fender Studio Pro Sound Variations: import both formats, assign a map to an instrument track, give each MIDI note an articulation, colour notes by articulation, edit articulations in a lane under the piano roll, and compensate each library's attack latency with a track-level offset plus a per-articulation offset and an independent keyswitch lead time."
+
+Issue: [#547](https://github.com/nota-daw/nota/issues/547) (`approved`). Out of this feature's scope by the owner's choice: the issue's articulation lane (FR-016, removed) and automatic latency measurement (US6, deferred).
+
+## Nota Context
+
+**Feature area** *(pick the main one)*:
+
+- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table
+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [x] UI (Avalonia, `src/managed/Nota.App`) — follow `DESIGN.md` (Studio)
+- [x] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:
+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),
+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR
+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),
+[`FEATURES.md`](../../FEATURES.md).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Import a library's articulation map (Priority: P1)
+
+A composer who owns Cinematic Studio Strings (with the Babylonwaves Art Conductor files)
+drops a Cubase expression map, or a Studio One keyswitch list, onto Nota. A preview lists
+every articulation with its name, colour and the MIDI it sends, plus anything Nota could not
+carry over. They accept; the map is kept in Nota's library and they assign it to their
+Kontakt track.
+
+**Why this priority**: Without a map there are no articulations. Real libraries ship these
+files, so importing them is the fastest route to a usable setup.
+
+**Independent Test**: Import `CSSS Violins 1 A.expressionmap` and
+`CSSS Violins 1 Attribute.keyswitch`; both give 44 articulations whose keyswitch notes
+agree with each other; a damaged or unrelated file is refused with a clear message.
+
+**Acceptance Scenarios**:
+
+1. **Given** a Cubase expression map, **When** the user imports it, **Then** each
+ articulation keeps its name, short name, order, colour information, and its MIDI actions in
+ the order the file lists them.
+2. **Given** a Studio One keyswitch list, **When** the user imports it, **Then** each
+ articulation keeps its name and keyswitch notes, and any action the format cannot describe
+ is reported, not dropped silently.
+3. **Given** a file with a wrong extension or the wrong content, **When** the user imports it,
+ **Then** Nota decides by content and refuses what it cannot read, without crashing.
+4. **Given** an imported file, **When** the import finishes, **Then** the source file on disk is
+ unchanged.
+5. **Given** a file dropped from Windows Explorer onto the Articulation Map Manager or the
+ track's Articulation section, **When** it is released, **Then** the same preview and import
+ happen as from the file picker.
+
+---
+
+### User Story 2 - Give notes articulations (Priority: P1)
+
+In the piano roll the user selects notes, right-clicks, and chooses an articulation from
+the list of the track's assigned map. Each note remembers its articulation. Playback sends
+the library the MIDI it needs, before the note, so the right sound plays.
+
+**Why this priority**: This is the point of the feature: expressive control per note.
+
+**Independent Test**: Assign Staccato to one note of a chord and Legato to another; play; the
+library receives the matching keyswitch before each note; undo restores the previous
+articulations; save and reopen keeps them.
+
+**Acceptance Scenarios**:
+
+1. **Given** a track with an assigned map, **When** the user right-clicks selected notes,
+ **Then** the Articulation menu lists the map's articulations, "Default" and "Clear".
+2. **Given** several selected notes, **When** one articulation is chosen, **Then** exactly
+ those notes change, in one undo step.
+3. **Given** overlapping notes or a chord with different articulations, **When** played,
+ **Then** each note triggers its own articulation and no other note is affected.
+4. **Given** notes with articulations, **When** they are copied, duplicated, quantized,
+ transposed, split, looped or moved, **Then** the articulation stays with the note.
+5. **Given** an articulation deleted from its map, **When** a note still refers to it,
+ **Then** the note plays as the map's default and the interface marks it as missing.
+
+---
+
+### User Story 3 - Compensate sample-library latency (Priority: P1)
+
+String libraries speak late, and each articulation has its own delay. The user sets a track
+offset (for example −80 ms) and a per-articulation offset (for example Legato −150 ms) and
+Nota plays each note that much earlier, without moving it on the page. The keyswitch has its
+own lead time so it arrives before the note.
+
+**Why this priority**: Without it the notes land late and the music feels sloppy; this is
+the difference between a notation tool and a playable orchestral setup.
+
+**Independent Test**: With track offset −100 ms and Legato −150 ms, a Legato note sounds
+250 ms before its grid position; the keyswitch with a 30 ms lead sounds 30 ms before that;
+the notes in the piano roll have not moved.
+
+**Acceptance Scenarios**:
+
+1. **Given** a track offset and an articulation offset, **When** a note plays, **Then** it is
+ played at its position plus both offsets, and the inspector shows that sum.
+2. **Given** a trigger lead time, **When** the note plays, **Then** the articulation's MIDI is
+ sent that much earlier than the (offset) note and the note's own time does not change.
+3. **Given** a negative offset on a note at the very start of the project, **When** playback
+ starts there, **Then** it is not lost or delayed; what cannot be played early is stated.
+4. **Given** playback that starts, loops or is moved in the middle of a phrase, **When**
+ the first note arrives, **Then** the articulation it needs is already selected, with no
+ duplicated trigger and no stuck note.
+
+---
+
+### User Story 4 - See articulations on the notes (Priority: P2)
+
+Notes are coloured by articulation. (An Articulation Lane under the piano roll was dropped from
+this feature at the owner's request; articulations are chosen through the note menu.)
+
+**Why this priority**: It makes a dense orchestral part readable at a glance, but the music
+works without it.
+
+**Independent Test**: Switch Note Color Mode to Articulation Color; notes take their
+articulation colours and selected notes stay clearly visible; switch back and track colours
+return.
+
+**Acceptance Scenarios**:
+
+1. **Given** Articulation Color mode, **When** notes have articulations, **Then** each is drawn in
+ its articulation colour; selected, muted and ghost notes stay distinguishable.
+
+---
+
+### User Story 5 - Manage maps (Priority: P2)
+
+A manager window lists maps and lets the user create, rename, duplicate, delete, edit,
+reorder, recolour and export them, and assign one to a track.
+
+**Why this priority**: Imports are rarely perfect (colours, switch modes, offsets), so users
+must be able to adjust them.
+
+**Independent Test**: Duplicate an imported map, edit an articulation's colour and offsets,
+assign it to one track; a second track using the original map is unaffected.
+
+**Acceptance Scenarios**:
+
+1. **Given** a map used by several tracks, **When** it is edited, **Then** the change applies to
+ every track using that map, and the manager says how many; "Duplicate" gives an independent copy.
+2. **Given** any edit in the manager, **When** the user presses undo, **Then** the previous
+ state returns.
+3. **Given** a map, **When** exported, **Then** a Nota file is written that imports back to an
+ equal map.
+
+---
+
+### User Story 6 - Offset presets and measurement (Priority: P3)
+
+Offsets can be typed in (Manual), taken from saved recommendations for a library (Library
+Preset, each overridable), or measured from the instrument's real audio (Automatic
+Measurement) with a confidence value the user accepts or rejects.
+
+**Why this priority**: Manual offsets already deliver the value; presets and measurement save time.
+
+**Independent Test**: Apply a library preset, override one articulation; run a measurement on
+a test instrument with a known delay and get that delay back within tolerance.
+
+**Acceptance Scenarios**:
+
+1. **Given** a library preset, **When** applied, **Then** offsets fill in and each remains editable.
+2. **Given** a measurement run, **When** it completes, **Then** Nota shows the suggested offset and a
+ confidence, and applies it only on acceptance.
+3. **Given** audio that gives no usable onset, **When** measured, **Then** Nota says so and suggests nothing.
+
+---
+
+### Edge Cases
+
+- A file that is truncated, empty, huge, or contains entity declarations → refused with a
+ message; never a crash or a hang.
+- A MIDI value outside 0–127, or a message type Nota does not send (for example pitch bend in
+ an action list) → reported, that action skipped, the rest of the articulation kept.
+- A map with two articulations that share a name or an id → each keeps its own stable id.
+- An articulation with no usable action → listed, selectable, sends nothing, and says so.
+- Two notes at the same time with different articulations on one instrument → both
+ articulations are sent in a defined order, and the later note's wins afterwards.
+- A Session slot clip or a MIDI clip with notes shorter than the keyswitch hold → the keyswitch
+ still ends cleanly.
+- A track with no map assigned, or an old project → plays exactly as before.
+- Notes outside the clip range, or clips that overlap → follow the existing rules for them.
+- A map assigned to a track whose instrument ignores channels, programs or banks → those
+ actions are skipped and the interface says so.
+- Tempo changes during playback → offsets stay in milliseconds, not beats.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Nota MUST hold articulation maps containing a stable map id, name, instrument or
+ library name, optional description, default articulation, groups, ordered articulations and a
+ format version.
+- **FR-002**: Each articulation MUST have a stable id (never reused within its map), full name,
+ short name, colour, group, trigger mode (latching or momentary), MIDI channel setting
+ (note's own or 1–16), ordered MIDI actions, a note timing offset, a trigger lead time and an
+ enabled flag.
+- **FR-003**: MIDI actions MUST support keyswitch notes, controller changes, program changes and
+ bank select (MSB and LSB), in any number and order per articulation, each with an optional
+ explicit channel.
+- **FR-004**: Nota MUST import Cubase `.expressionmap` files, preserving names, short names,
+ order, colour information, groups when present and the order of MIDI actions.
+- **FR-005**: Nota MUST import Studio One keyswitch lists (`.keyswitch`) in the format verified
+ from a real file, and MUST import `.soundvariation` files once a real example has been supplied
+ and verified.
+- **FR-006**: Importers MUST decide by file content, not extension, MUST NOT modify the source
+ file, MUST bound the file size and refuse entity expansion, and MUST report every construct
+ they cannot carry over instead of dropping it silently.
+- **FR-007**: The user MUST be able to import by file picker and by dropping files from Windows
+ Explorer onto the Articulation Map Manager and the track's Articulation section (and, if
+ feasible, a track header), with a preview and warnings before accepting.
+- **FR-008**: Imported and created maps MUST be stored in Nota's own library and in the project
+ that uses them, so a project opens without the library.
+- **FR-009**: A manager MUST allow creating, importing, renaming, duplicating, deleting,
+ editing, reordering, recolouring, setting the default, and exporting maps in Nota's own
+ format, and assigning a map to an instrument track.
+- **FR-010**: Editing a map used by several tracks MUST apply to all of them and say so;
+ duplicating MUST produce an independent copy.
+- **FR-011**: Every MIDI note MUST be able to carry an articulation, stored as the articulation's
+ stable id, not its label.
+- **FR-012**: The piano-roll note context menu MUST list the assigned map's articulations plus
+ Default and Clear, for one note, many notes, chords and overlapping notes, as one undo step.
+- **FR-013**: A note's articulation MUST survive copy and paste, Alt/Shift duplication,
+ quantize, transpose, velocity editing, clip duplication, splitting, looping, deletion of other
+ notes, undo and redo, saving and loading.
+- **FR-014**: A note referring to an articulation that no longer exists MUST play as the default
+ and be shown as missing.
+- **FR-015**: Notes MUST be drawn in their articulation colour when Note Color Mode is
+ "Articulation Color" and in the track colour when it is "Track Color", using the existing note
+ drawing; selected, muted and ghost notes MUST stay distinguishable.
+- **FR-016**: *Removed at the owner's request* (an Articulation Lane under the piano roll). The
+ number is kept so later requirements keep theirs.
+- **FR-017**: Each instrument track MUST have a MIDI playback offset in milliseconds (positive
+ delays, negative advances), shown in the track inspector and saved with the project. It MUST
+ change when notes play and never where they are stored.
+- **FR-018**: The effective note offset MUST be the track offset plus the articulation offset,
+ applied once, and shown in the interface.
+- **FR-019**: Each articulation's MIDI actions MUST be sent at the effective note time minus its
+ trigger lead time. The lead time MUST NOT move the note.
+- **FR-020**: Timing MUST be computed with the engine's real time and sample conversion, in
+ milliseconds converted at the current sample rate and tempo, never as a fixed number of beats.
+- **FR-021**: Playback MUST handle chords, overlapping notes, clip boundaries, looping, seeking
+ and transport restart without duplicated triggers, missed articulation changes or stuck notes.
+ After a seek, loop wrap or start in the middle of a phrase, the articulation in force at that
+ point MUST be selected before the first note sounds.
+- **FR-022**: Latching keyswitches MUST be released shortly after pressing; momentary ones MUST be
+ released with the note. Bank select MUST be sent before program change.
+- **FR-023**: Notes whose compensated start lies before playback began MUST NOT be silently
+ dropped; cases that cannot be played early MUST be documented in the user manual.
+- **FR-024**: Articulation MIDI MUST reach built-in instruments harmlessly (ignored) and hosted
+ plug-ins as real MIDI: channel, controller, program change and bank select.
+- **FR-025**: The audio thread MUST NOT allocate, lock, perform I/O or log for this feature; the
+ maps in use MUST reach it as an immutable prepared table.
+- **FR-026**: Offset values MUST be enterable manually, filled from a library preset with
+ per-articulation overrides, and measured automatically only if real audio analysis is
+ implemented and verified; otherwise Nota MUST say exactly what is missing.
+- **FR-027**: Projects without maps or offsets MUST open and play exactly as before; malformed
+ articulation data in a project MUST NOT prevent it from loading.
+- **FR-028**: All new user-visible strings MUST use the localization keys; new controls follow
+ `DESIGN.md`; user-visible changes get a `CHANGELOG.md` entry.
+
+### Key Entities
+
+- **Articulation map**: a named set of articulations for one instrument or library, with a
+ default, groups, a version and its provenance (where it was imported from).
+- **Articulation**: one playing technique, with names, colour, group, trigger mode, channel,
+ ordered MIDI actions, a note offset and a trigger lead.
+- **MIDI action**: one message that selects an articulation: keyswitch note, controller change,
+ program change, or bank select.
+- **Articulation group**: a set of mutually exclusive articulations in one map.
+- **Track timing offset**: the per-track playback shift in milliseconds.
+- **Note articulation**: the stable id on a note that links it to an articulation of its track's map.
+- **Import result**: the map plus every message about what was kept, changed or left out.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: Both real Cinematic Studio Strings files import with 44 articulations each, with
+ identical keyswitch notes between the two formats and no unreported loss.
+- **SC-002**: A user can import a map and assign it to a track in under one minute, without
+ leaving Nota.
+- **SC-003**: A note with track offset −100 ms and articulation offset −150 ms sounds 250 ms
+ before its position, within one audio block of the requested time, at any tempo.
+- **SC-004**: A keyswitch with a 30 ms lead arrives 30 ms before its note, in 100 % of notes in
+ a test pass, including after seeks and loop wraps, with no duplicate or stuck notes.
+- **SC-005**: Assigning an articulation to selected notes changes only those notes, in 100 % of
+ tested selections, and undo restores every one.
+- **SC-006**: Saving and reopening a project with maps, offsets and note articulations restores
+ all of them exactly; a project saved before this feature opens and plays unchanged.
+- **SC-007**: Playing a project with articulations adds no audio dropouts compared with the same
+ project without them, on the project's existing performance test.
+- **SC-008**: Every file that is damaged or not a map is refused with a message in 100 % of tested
+ cases; none crashes or hangs Nota.
+
+## Clarifications
+
+### Session 2026-11-09
+
+- Q: Which Studio One file is the Sound Variation format? → A: The owner supplied Studio One
+ keyswitch lists with the extension `.keyswitch` (root `Music.KeySwitchList`), verified against
+ the matching Cubase map. No `.soundvariation` file has been seen. Both extensions are accepted
+ by content; `.soundvariation` stays unverified until an example exists.
+- Q: Do colours come across from Cubase? → A: The file stores a Cubase palette index, not RGB.
+ Nota keeps the index and shows its own colour for it until the user sets one; it does not copy
+ Cubase's palette from memory.
+
+## Assumptions
+
+- Cubase and Studio One do not store latching or momentary mode in the files seen; imported
+ articulations default to latching and the user can change them.
+- Offsets are per instrument track and apply to Arrangement MIDI clips; Session clips are
+ addressed by the plan (see the plan's research).
+- The Studio One keyswitch list does not carry the controller selecting each CSS articulation;
+ users who need it import the Cubase map instead. This is reported at import.
+- Hosted plug-ins (Kontakt and others) receive MIDI on the channel set by the articulation or the
+ note's own channel; built-in instruments ignore channels, programs and banks.
+- Verifying real playback in Kontakt needs the owner's library; automated tests use a test
+ instrument that records the MIDI it receives.
+- The feature implements the approved issue #547 (see the top of this file).
+- No new third-party dependency is needed: XML parsing uses the .NET base library.
+
+## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*
+
+- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)
+- [x] No new dependency (XML parsing is in the .NET base library)
+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5)
+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`
+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`
+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)
+- [ ] UI change → follows `DESIGN.md` (Studio design language)
diff --git a/specs/085-articulation-maps/tasks.md b/specs/085-articulation-maps/tasks.md
new file mode 100644
index 00000000..26f6c4ff
--- /dev/null
+++ b/specs/085-articulation-maps/tasks.md
@@ -0,0 +1,284 @@
+---
+
+description: "Task list for articulation maps"
+---
+
+# Tasks: Articulation maps
+
+**Input**: Design documents from `/specs/085-articulation-maps/`
+
+**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/](contracts/), [quickstart.md](quickstart.md)
+
+**Tests**: Included. The owner's request lists the tests to write, and Constitution IV requires the smoke test to cover engine behaviour changes.
+
+**Organization**: Grouped by user story (spec.md). `[x]` = written **and** verified by a passing test on 2026-11-09 (full smoke test: 5300 pass, 0 fail). That code was written before the plan (plan, Constitution VII); T071 reviews it.
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependency on an unfinished task)
+- **[Story]**: US1–US6 from spec.md
+- Engine `src/native/nota.engine/`, managed `src/managed/`, UI `src/managed/Nota.App/`, tests `tests/Nota.SmokeTest/`
+
+---
+
+## Phase 1: Setup (Shared Infrastructure)
+
+**Purpose**: Fixtures, build environment, feature pointer
+
+- [x] T001 Copy the owner's real files into `tests/Nota.SmokeTest/Fixtures/expressionmaps/CSSS Violins 1 A.expressionmap` and `tests/Nota.SmokeTest/Fixtures/keyswitches/` (Violins 1, Lite Ensemble); never modify them — *removed before the PR (2026-11-09, owner's choice): they are third-party works (Babylonwaves Art Conductor) and can't be relicensed under AGPL; the tests that needed them were dropped*
+- [x] T002 Configure and build the native engine with MSVC x64 + Ninja in `src/native/nota.engine/build` (dependencies fetched with the owner's permission, research R12)
+- [x] T003 [P] Point Spec Kit at the feature in `.specify/feature.json`
+
+---
+
+## Phase 2: Foundational (Blocking Prerequisites)
+
+**Purpose**: Note id, track offset, map table, ABI, persistence: everything every story needs
+
+**⚠️ CRITICAL**: No user story can be finished before this phase
+
+### Done and verified
+
+- [x] T004 Add `int32_t articulation = 0` to `Note` in `src/native/nota.engine/src/engine/MidiClip.h`; append `int32_t articulation_id` **last** to `NotaNoteData` in `src/native/nota.engine/include/nota/nota_engine.h`; convert in `noteFromData` / `noteToData` (negative → 0) in `src/native/nota.engine/src/engine/Engine_Tracks.cpp`
+- [x] T005 [P] Append `public int ArticulationId` **last** to `NotaNote` in `src/managed/Nota.Application/Engine/EngineContracts.cs` (layout must match `NotaNoteData`)
+- [x] T006 Add `std::atomic<double> midiOffsetMs_` with accessors to `src/native/nota.engine/src/engine/Track.h`; copy it in `cloneTrack` (`Engine.cpp`) and the duplicate path (`Engine_Tracks.cpp`); `setTrackMidiOffsetMs` clamps to "±2000 ms" and treats NaN as 0 in `Engine_Recording.cpp`
+- [x] T007 Expose `nota_track_set_midi_offset_ms` / `nota_track_get_midi_offset_ms` in `nota_engine.h` and `src/abi/nota_engine_track.cpp`; P/Invoke in `Nota.Infrastructure/Interop/NativeMethods.Tracks.cs`; wrappers in `NotaEngine.Tracks.cs`; `IAudioEngine.SetTrackMidiOffsetMs` / `GetTrackMidiOffsetMs`
+- [x] T008 Project format v30: `TrackDto.MidiOffsetMs` (omitted when 0) and `NoteDto.Articulation` (omitted when none) in `Nota.Infrastructure/Persistence/ProjectModel.cs`, capture/apply in `ProjectService.cs`, no-op `Migration(29)` in `ProjectMigrations.cs`
+- [x] T009 [P] Managed model per data-model.md in `src/managed/Nota.Application/Articulations/ArticulationMap.cs` (ids "never reused after a delete", channel "null or 1..16", data "0..127")
+- [x] T010 Engine round-trip tests in `tests/Nota.SmokeTest/ArticulationEngineTests.cs`: ABI layout, one-note edit isolation, undo/redo, clamping, duplicate track, save/reopen, v29 migration
+
+### To do
+
+- [x] T011 Audit every place that rebuilds a `NotaNote` from its fields (`new NotaNote(`) in `src/managed/` (known: `Nota.Mcp/Tools/MidiTools.cs`, `Nota.Mcp/Tools/SessionTools.cs`, `Nota.Application/Twin/TwinPatterns.cs`, `Nota.Application/Midi/MidiTransforms.cs`, `Nota.Application/Editing/NoteOverwrite.cs`, `Nota.Application/Editing/ClipSet.cs`) and carry `ArticulationId` wherever a note is transformed rather than created (FR-013); list each site and its verdict in research.md R11
+- [x] T012 Trace every write to `clip.notes` / `MidiClip` in `src/native/nota.engine/src/engine/*.cpp` (note edits, recording, split, trim, consolidate, duplicate) to the publish step (`republishWithTrack`, `republishWithTrackRaw`, `publishRaw`) and record the choke point for timeline rebuilds in research.md R5
+- [x] T013 Create `src/native/nota.engine/src/engine/ArticulationTable.h` / `.cpp` (SPDX header): immutable `ArticulationTable { defaultId, entries sorted by id, actions }`, entry `{ id, offsetMs, leadMs, trigger, actionStart, actionCount }`, `resolve(id)` by binary search where "id 0, a missing id or a disabled one resolves to defaultId"; add the files to `src/native/nota.engine/CMakeLists.txt`
+- [x] T014 Add the per-clip articulation timeline builder to `ArticulationTable.cpp`: entries `{ startBeat, articulationId, endBeat }` sorted by start; "latching neighbours with the same id collapse into one entry; momentary entries are one per note"; stored on `MidiClip` as `std::shared_ptr<const ArticulationTimeline>`; rebuilt at the T012 choke point on the message thread only
+- [x] T015 Store the map JSON blob and `std::shared_ptr<const ArticulationTable>` on `Track` in `src/native/nota.engine/src/engine/Track.h`; copy both in `cloneTrack` (`Engine.cpp`) and the duplicate path (`Engine_Tracks.cpp`)
+- [x] T016 Implement `Engine::setTrackArticulationMap` / `clearTrackArticulationMap` / `trackArticulationMapJson` in `src/native/nota.engine/src/engine/Engine_Tracks.cpp` as one undo step each (`cloneTrack` + `republishWithTrack`), validating per contracts/c-abi.md ("ids ascend strictly; each [action_start, action_start+action_count) lies within actions"; nothing changes on error) and rebuilding the track's clip timelines
+- [x] T017 Add `NotaArticulationEntry`, `NotaArticulationAction`, `nota_track_set_articulation_map`, `nota_track_clear_articulation_map`, `nota_track_get_articulation_map_json` to `src/native/nota.engine/include/nota/nota_engine.h` and `src/native/nota.engine/src/abi/nota_engine_track.cpp`
+- [x] T018 [P] Add `int32_t eventChannel = 0` and `virtual void programChange(int32_t)` (default ignored) to `src/native/nota.engine/src/devices/Instrument.h`; in `src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp` send note, CC, all-notes-off on `eventChannel + 1` instead of the hardcoded 1 and map `programChange` to `juce::MidiMessage::programChange`; bank select stays `controller(0|32, v/127)` — *verified in Kontakt + Cinematic Studio Strings by the owner, 2026-11-09: keyswitch notes and CC 58 on channel 1 switch the articulation. Not exercised by a real plug-in yet: explicit channels 2–16, program change, bank select (covered by engine self-test check 20 only)*
+- [x] T019 Managed interop for T017: structs in `Nota.Application/Engine/EngineContracts.cs`, P/Invoke in `Nota.Infrastructure/Interop/NativeMethods.Tracks.cs`, wrappers in `NotaEngine.Tracks.cs`, `IAudioEngine.SetTrackArticulationMap` / `ClearTrackArticulationMap` / `GetTrackArticulationMapJson`
+- [x] T020 [P] Create `src/managed/Nota.Application/Articulations/ArticulationMapCompiler.cs`: managed map → sorted entries + flat actions for T019 (channel null → 0)
+- [x] T021 [P] Create `src/managed/Nota.Application/Articulations/ArticulationMapFile.cs`: read/write the Nota format per contracts/nota-articulation-map-file.md ("format must be nota-articulation-map", higher version refused, repairs reported, "larger than 16 MiB … or not valid JSON is refused", offsets clamped "±2000 ms and leads to 0..2000")
+- [x] T022 Persist the map per track: `TrackDto.ArticulationMap` in `Nota.Infrastructure/Persistence/ProjectModel.cs`; capture from `GetTrackArticulationMapJson` and apply through T020/T019 in `ProjectService.cs`; a malformed map is a load warning, never a failed load (FR-027); note in the v30 comment and migration that the field is absent in v29
+- [x] T023 Tests in `tests/Nota.SmokeTest/ArticulationEngineTests.cs` and new `tests/Nota.SmokeTest/ArticulationFileTests.cs`: file round trip yields an equal map; repairs and refusals; the engine rejects unsorted/duplicate ids and out-of-range action spans; set/clear map undo and redo; duplicate track keeps the map; save/reopen restores it; a project with a broken map still loads
+
+**Checkpoint**: A map can be given to a track through the ABI, saved, undone and duplicated
+
+---
+
+## Phase 3: User Story 1 - Import a library's articulation map (Priority: P1) 🎯 MVP
+
+**Goal**: Import Cubase and Studio One files, preview, keep in the library, assign to a track
+
+**Independent Test**: Import a Cubase map and the Studio One list for the same library (manual, your own files; the smoke test uses inline maps): the same keyswitches from both; a damaged or unrelated file is refused with a message; the source file is unchanged; the map lands on the selected track
+
+### Done and verified
+
+- [x] T024 [P] [US1] Cubase importer per contracts/import-formats.md in `src/managed/Nota.Application/Articulations/ExpressionMapImporter.cs`
+- [x] T025 [P] [US1] Studio One keyswitch-list importer in `src/managed/Nota.Application/Articulations/KeySwitchListImporter.cs`
+- [x] T026 [US1] Import messages through `Loc` (`articulations.import.*` keys in `src/managed/Nota.Application/Localization/en.json`); saved names language-neutral (`#N`)
+- [x] T027 [US1] Importer tests on the real fixtures and hostile input in `tests/Nota.SmokeTest/ArticulationImportTests.cs` — *now on small inline maps in both formats (the real-file checks were dropped with the fixtures)*
+
+### To do
+
+- [x] T028 [US1] Create `src/managed/Nota.Application/Articulations/ArticulationImport.cs`: pick the importer by content (`Sniff`), never by extension; `.notamap` through T021; a `.soundvariation` or unknown file returns an error message saying the format is not supported (FR-005), never a guess
+- [x] T029 [P] [US1] Library port `IArticulationLibrary` in `src/managed/Nota.Application/Articulations/IArticulationLibrary.cs` and store `src/managed/Nota.Infrastructure/Articulations/ArticulationLibraryStore.cs` over `NotaPaths.SubDir("articulations")` (`*.notamap`, list / get / save / delete by map id, atomic write)
+- [x] T030 [US1] Import preview dialog in `src/managed/Nota.App/ArticulationImportPreview.cs`: articulations (name, short name, colour swatch, actions as text), messages grouped by severity with unverified items labelled (contracts/import-formats.md), Accept / Cancel; DESIGN.md tokens, `Loc` keys — *verified by the owner in the running app, 2026-11-09*
+- [x] T031 [US1] Articulations section in `src/managed/Nota.App/TrackInspectorView.cs` for instrument tracks: assigned map name and count, Import…, Assign from library, Remove; edits call `Edited()` — *verified by the owner in the running app, 2026-11-09*
+- [x] T032 [US1] File picker for `.expressionmap`, `.keyswitch`, `.notamap` and All files from the inspector section, through T028 → T030 → T029 + T019 — *verified by the owner in the running app, 2026-11-09*
+- [x] T033 [US1] Drop from Windows Explorer onto the inspector Articulations section (`BrowserView.ExternalPaths` pattern, `DragDrop.AddDropHandler`): files read at drop, decided by content, same preview as the picker — *verified by the owner in the running app, 2026-11-09*
+- [x] T034 [P] [US1] Tests in `tests/Nota.SmokeTest/ArticulationImportTests.cs`: T028 dispatch by content (renamed files, `.soundvariation` refused), T029 store in a scratch `NOTA_DATA_DIR` (save, list, get, delete), import → compile → `SetTrackArticulationMap` → `GetTrackArticulationMapJson` round trip
+- [x] T035 [US1] Run quickstart scenario H by hand (drop from Explorer onto the inspector); record the result in quickstart.md
+
+**Checkpoint**: A real map can be imported and assigned without leaving Nota
+
+---
+
+## Phase 4: User Story 2 - Give notes articulations (Priority: P1)
+
+**Goal**: Per-note articulation from the piano roll; playback sends the library its MIDI before each note
+
+**Independent Test**: Chord with Staccato and Legato; the test instrument receives each keyswitch before its note, once; undo restores; save/reopen keeps it
+
+- [x] T036 [US2] Add `ArtEv { off, seq, kind, channel, data1, data2 }` to `src/native/nota.engine/src/engine/EngineTypes.h` and a per-track buffer in `RenderScratch`, pre-sized in `publishRaw` like `blockMidi` (AR-6: "on overflow events are dropped and counted, never allocated") — *done differently: `ArtEv` and the scheduler live in `src/native/nota.engine/src/engine/ArticulationSchedule.{h,cpp}`; the block's events go in a fixed stack array in `renderInstrumentRaw` (articulation MIDI never crosses tracks, so no `RenderScratch` buffer is needed); overflow dropped and counted. Verified by T041.*
+- [x] T037 [US2] In `src/native/nota.engine/src/engine/Engine_Render.cpp` emit, from each active clip's timeline, the actions whose trigger time falls in the block, in action order (`seq`), into the `ArtEv` buffer, outside the MIDI-FX chain (research R2) — *verified by T041*
+- [x] T038 [US2] Merge `ArtEv` into `playEvents` in `Engine_Render.cpp`: same offset → articulation actions before note-ons; set `eventChannel` per event; keyswitch → `sendNoteOn`/`sendNoteOff`, CC and bank → `deliverExpr` path, program → `programChange`; both the segmented and the timed-events paths — *verified by T041 (check 20: actions ahead of the note at the same offset, on their channel, channel reset); gated by the new `Instrument::takesArticulations()` (built-ins: no; hosted plug-ins and racks holding one: yes)*
+- [x] T039 [US2] Keyswitch release in `Engine_Render.cpp`: latching released after a named 20 ms hold constant, momentary at its note's end; bank MSB before LSB before program (FR-022) — *verified by T041 (checks 3, 6, 15, 16)*
+- [x] T040 [US2] Chase in `Engine_Render.cpp`: on seek, loop wrap and start (`chaseNotes_`) emit the articulation in force at the block start (timeline binary search) at offset 0 before chased notes; never twice for one change; release held keyswitches on stop and seek (FR-021) — *verified by T041 (checks 11–14); stop/seek release relies on the existing `allNotesOff` flush*
+- [x] T041 [US2] Engine self-test `Engine::articulationSelfTest` with a recording `Probe : Instrument` (segmented and timed) in `Engine_Render.cpp`, exposed as `nota_engine_articulation_selftest` (`nota_engine.h`, ABI, `NotaEngine.ArticulationSelfTest()`): order, chord with two articulations, overlapping notes, dedupe of repeated latching notes, seek into a phrase, loop wrap, stop with no held keyswitch, overflow counting — *21 checks, passing; `tests/Nota.SmokeTest/ArticulationEngineTests.cs` calls it*
+- [x] T042 [US2] Session slots: same timeline and `ArtEv` path in `renderSessionSlotRaw` (`Engine_Render.cpp`), looping over `it = i0..i0+1` (research R7) — *verified: `scheduleSlotArticulations` (self-test checks 23–25: a switch per pass, one-shot slots, an early switch reaching back across the loop end)*
+- [x] T043 [US2] Articulation submenu in the piano-roll note context menu in `src/managed/Nota.App/PianoRollView.cs` (`NoteGrid`; locate its right-click path first): the assigned map's enabled articulations + Default + Clear, applied to the selection with one `Commit`; hidden when the track has no map — *verified by the owner in the running app, 2026-11-09 (after the `NotaNote.Same` fix)*
+- [x] T044 [US2] Missing articulation (FR-014): a note whose id is not in the map shows a marker and a tooltip in `PianoRollView.cs`; it plays as the default (engine T013) — *written: a warning notch at the start of a note whose articulation the map no longer holds, and a tooltip; map cached for 500 ms; seen working by the owner in the app, 2026-11-09*
+- [x] T045 [P] [US2] Tests in `tests/Nota.SmokeTest/ArticulationEngineTests.cs`: the self-test passes; offline render with a map plays keyswitches on a test track; editing operations keep `ArticulationId` (copy/paste, Alt/Shift duplicate, quantize, transpose, velocity edit, clip duplicate, split, loop) through the managed editing APIs found in T011 — *verified: duplicate, split, trim, copy/paste, consolidate, Session slot and slot→arrangement keep each note's articulation; the roll's multi-clip split/merge and resize too; the clip tools (earlier); `NotaNote.Same` covers every field*
+- [x] T046 [US2] Manual quickstart G with Kontakt + CSS on the owner's machine; record the result in `specs/085-articulation-maps/quickstart.md`; not claimed working until done — *done 2026-11-09: CSS in Kontakt switches articulation per phrase*
+
+**Checkpoint**: Notes switch articulations in playback
+
+---
+
+## Phase 5: User Story 3 - Compensate sample-library latency (Priority: P1)
+
+**Goal**: Track offset + articulation offset move the note; lead time moves only the trigger
+
+**Independent Test**: Track −100 ms + Legato −150 ms → note 250 ms early at 60 and 120 BPM; keyswitch 30 ms before it; notes unmoved
+
+- [x] T047 [US3] Apply the track offset to arrangement note-on and note-off in `gatherInstrumentNotes` (`Engine_Render.cpp`), milliseconds × sample rate, notes unmoved (verified: ±100 ms = 4800 samples at 48 kHz)
+- [x] T048 [US3] Add the articulation offset in the same place ("effective = nominal + trackOffsetMs + articulationOffsetMs", applied once) and schedule actions at "trigger = effective − leadMs" (FR-018–FR-020) in `Engine_Render.cpp` — *verified: −100 + −150 ms = 250 ms early at 120 and 60 BPM (12000 samples); lead verified by T041 check 5*
+- [x] T049 [US3] Track and articulation offsets for Session slots in `renderSessionSlotRaw` (`Engine_Render.cpp`) — *verified: a slot's note moves 4800 samples for ±100 ms; with no offset the slot's note loop is unchanged (beat-based block test kept)*
+- [ ] T050 [US3] Negative offsets at a loop start: lookahead across the loop seam in `Engine_Render.cpp`, or, if it can't be done allocation-free, keep the documented limit (research R4) and test that nothing is dropped or doubled — *deferred by the owner, 2026-11-09: the limit stays as documented in research R4 (a note at a loop start with a negative offset sounds late on each repeat)*
+- [x] T051 [US3] Make the track offset one undo step (`cloneTrack` + `republishWithTrack`) in `Engine_Recording.cpp`; keep the atomic read on the audio thread — *verified: one undo step, redo restores, the same value adds none*
+- [x] T052 [US3] Track MIDI offset field in the inspector (`src/managed/Nota.App/TrackInspectorView.cs`): typed milliseconds via `ValueText`, display culture (U+2212 minus), range "±2000 ms" — *written: "MIDI offset" box in the inspector's Articulations section (types −80, -80 ms, −0.08 s; Enter / leave sets, Esc reverts); seen working by the owner in the app, 2026-11-09*
+- [x] T053 [US3] Effective-offset readout per articulation (track + articulation) in `src/managed/Nota.App/TrackInspectorView.cs` and `src/managed/Nota.App/ArticulationMapManager.cs` (FR-018) — *written for the inspector (rule tested: `ArticulationText.EffectiveOffsets`) and the manager: a line under Note offset, "Plays at −250 ms (−100 ms track + −150 ms articulation)", using the selected track's offset when it holds the map, else the one its tracks share, else "adds to each track's offset" (rule tested: `ArticulationMapUsage.TrackOffsetFor`); both seen working by the owner in the app, 2026-11-09*
+- [x] T054 [P] [US3] Tests in `tests/Nota.SmokeTest/ArticulationEngineTests.cs`: −100 + −150 = −250 ms at 120 and 60 BPM within one block (SC-003); lead 30 ms before its note (SC-004); offset undo/redo; Session slot offset — *verified: SC-003 at 120 and 60 BPM, lead (self-test 5), offset undo/redo, Session slot offset*
+
+**Checkpoint**: Attacks land on the grid with compensation
+
+---
+
+## Phase 6: User Story 4 - See articulations on the notes (Priority: P2)
+
+**Goal**: Note Color Mode (the Articulation Lane was dropped at the owner's request, FR-016)
+
+**Independent Test**: Articulation Color recolours notes and keeps the selection visible
+
+- [x] T055 [P] [US4] Note Color Mode (Track Color / Articulation Color) in the piano-roll settings (`LaneSettings`) with persistence, in `src/managed/Nota.App/PianoRollView.cs` — *written: a palette chip in the clip editor header beside the speaker (`ClipEditorView.NoteColourControl`), app-wide like audition, saved as `Settings.PianoRollNoteColorByArticulation` (off by default); every open roll redraws on a flip; seen working by the owner in the app, 2026-11-09*
+- [x] T056 [US4] Pure colour resolver `src/managed/Nota.Application/Articulations/ArticulationColours.cs`: `ColorArgb`, else a default per articulation from palette tokens (no hex outside `NotaPalette.Ink()`) — *written and tested: `Shown` (own articulation, else the default it plays as; a missing or disabled id keeps the track colour, FR-014) and `PaletteSlot` (source index, else id; stable across reordering); the view reads the slot's track-palette colour at render time, so it follows the theme; seen working by the owner, 2026-11-09*
+- [x] T057 [US4] Use T056 in the normal branch of `NoteGrid.Render` (`_o.ColorOf(i)`) in `PianoRollView.cs`; selected, ghost, locked and out-of-scale branches unchanged — *written: `ColorOf` returns the articulation colour when the mode is on, so notes, velocity stems and expression pens agree; the selected / ghost / locked branches and the out-of-scale fade are untouched; seen working by the owner in the app, 2026-11-09*
+- ~~T058 [US4] Articulation Lane~~ — *removed at the owner's request (FR-016 dropped)*
+- [x] T059 [P] [US4] Tests: T056 resolver (pure) in `tests/Nota.SmokeTest/ArticulationUiTests.cs`; the design and localization checks pass — *verified: 8 checks (own, default, missing, disabled, no default / no map, palette slot, stable across reorder); full smoke 5401 / 0*
+- [x] T060 [US4] Manual quickstart I (colours, selection visible, switching back to track colours); record the result in `specs/085-articulation-maps/quickstart.md` — *done 2026-11-09: the owner reports colours, selection and switching back all work*
+
+---
+
+## Phase 7: User Story 5 - Manage maps (Priority: P2)
+
+**Goal**: The Articulation Map Manager
+
+**Independent Test**: Duplicate a map, edit it, assign to one track; a track on the original is unaffected; export → import is equal
+
+- [x] T061 [US5] Manager window `src/managed/Nota.App/ArticulationMapManager.cs`: maps from the library and the project; create, import, rename, duplicate, delete; articulation list add / remove / reorder; edit names, colour, group, trigger mode, channel, actions, offset, lead, enabled, default; export `.notamap`; DESIGN.md, `Loc` — *written: three columns (maps · articulations · details), edits on a working copy, unsaved changes asked about on switching map and closing, Save / Revert / Export… / Assign to track; design, label and localization checks pass; seen working by the owner in the app, 2026-11-09. Groups can be chosen from the map's own groups, not created or renamed*
+- [x] T062 [US5] Applying an edit updates every track using that map id in one undo group (`BeginUndoGroup`/`EndUndoGroup`) and the manager says how many (FR-010), in `src/managed/Nota.App/ArticulationMapManager.cs` — *written: Save → `lib.Save` + `ArticulationMapUsage.ApplyEverywhere`, status "Saved · N tracks updated" (the rule is tested, T066); seen working by the owner in the app, 2026-11-09*
+- [x] T063 [US5] Drop from Explorer onto the manager in `src/managed/Nota.App/ArticulationMapManager.cs` (same path as T033) — *written: the window takes the first dropped file, decides by content, previews, adds to the library; seen working by the owner in the app, 2026-11-09*
+- [ ] T064 [US5] If feasible in `src/managed/Nota.App/ArrangementView.cs`: drop a map file onto an instrument track header to import and assign; otherwise record why in research.md — *deferred by the owner, 2026-11-09: maps are dropped on the inspector section or the manager*
+- [x] T065 [US5] Open the manager from the inspector section (`src/managed/Nota.App/TrackInspectorView.cs`) and the app menu (`src/managed/Nota.App/MainWindow.*.cs`); shortcut via `nota-shortcuts` if one is added — *written: "Edit maps…" in the inspector, View → "Articulation maps…" and the command palette (`view.articulationMaps`, bound — palette check passes); no shortcut added, so the Shortcuts pane is unchanged; seen working by the owner in the app, 2026-11-09*
+- [x] T066 [P] [US5] Tests in `tests/Nota.SmokeTest/ArticulationEngineTests.cs` and `tests/Nota.SmokeTest/ArticulationFileTests.cs`: duplicate independence, edit reaches all tracks with that map in one undo step, export → import equality, deleting an articulation keeps notes' ids (data-model "the id is not reused") — *verified in `ArticulationManagerTests.cs`: duplicate independence, edit on every track as one undo, removed ids retired across save, notes keep a removed articulation's id after Save, and write → read → write is stable for the Nota, Cubase and Studio One maps (what the manager's unsaved-changes test relies on)*
+
+---
+
+## Phase 8: User Story 6 - Offset presets and measurement (Priority: P3)
+
+**Goal**: Manual, user-saved Library Preset, and Automatic Measurement only if verified
+
+**Independent Test**: Apply a saved preset and override one value; measurement returns a known test delay within tolerance, or the UI states the blocker
+
+- [ ] T067 [P] [US6] Offset presets: user-saved sets of offsets per map in `src/managed/Nota.Application/Articulations/OffsetPreset.cs` and the T029 store; apply with per-articulation overrides; no built-in values (research R10) — *deferred by the owner, 2026-11-09 (US6)*
+- [ ] T068 [US6] Measurement spike: offline render a track's instrument with an injected probe note (freeze/offline path) and estimate onset with the `TempoDetect` novelty envelope; record whether a hosted plug-in renders in that path, in research.md R10 — *deferred by the owner, 2026-11-09 (US6)*
+- [ ] T069 [US6] Only if T068 verifies it: measurement with confidence, accept / reject, in `src/managed/Nota.App/ArticulationMapManager.cs`; otherwise the Automatic option is disabled with a tooltip naming the blocker (FR-026) — *deferred by the owner, 2026-11-09 (US6): no Automatic option is shown*
+- [ ] T070 [P] [US6] Tests in `tests/Nota.SmokeTest/ArticulationEngineTests.cs`: preset apply and override; measurement on a built-in instrument with a known synthetic delay (if T069 implemented) — *deferred by the owner, 2026-11-09 (US6)*
+
+---
+
+## Phase 9: Polish & Cross-Cutting Concerns
+
+- [x] T071 [P] Run `/speckit-converge` on `specs/085-articulation-maps/` over the code written before the plan (Constitution VII deviation): T004–T010, T024–T027, T047 — *done 2026-11-09: 27 FRs, 8 SCs, 21 acceptance scenarios, 10 edge cases, 12 plan decisions and 9 constitution principles checked; 7 findings appended as Phase 10 (T090–T096), none critical or high; one reported item (English literals in ProjectService warnings) dropped as the layer's existing convention*
+- [ ] T072 Perf check (SC-007), with and without a mapped track — *the canonical Linux/Valgrind gate now passes all 63 scenarios on source `6c876cf5` (run `42629193021`), with charts, raw data and method linked in [review-evidence.md](review-evidence.md). This gate tests ordinary engine scenarios; a reproducible mapped-library versus unmapped comparison remains open. The earlier author-reported 536/628 ms timing has no raw artifact and is not treated as a completed controlled benchmark.*
+- [x] T073 Run quickstart.md scenarios A–F and record the results — *done 2026-11-09: A, B, C pass; D, E, F pass with one claim each not directly tested — recorded in quickstart.md Results*
+- [x] T074 Review every new line on the audio thread in `Engine_Render.cpp` for allocation, locks, I/O, logging (Constitution I) — *done 2026-11-09: no allocation, lock, I/O or logging on the new audio-thread code; two fixes — PluginInstrument's MidiBuffers reserve room for a block's articulation MIDI (kMaxBlockArt × 9 bytes on top of the notes' 8192), and a static_assert that Track::midiOffsetMs_ is lock-free. Seen, not changed: the notes' own worst case (1024 notes + 1024 expression events) already exceeded the 8192 bytes before this feature*
+
+### Nota closing tasks *(the PR gates)*
+
+- [x] T075 Run `pwsh -NoProfile -File .\scripts\build-win.ps1` from a VS x64 developer shell until native + managed + smoke test + plugin scan check are green — *done 2026-11-09: native, scanner self-test, managed, smoke test and plugin scan check green (5671 pass, 0 fail). The first run failed one check, the render-pool timing guard ("render threads do 0 % of the work"), known to fail the same way on unchanged develop; the rerun passed*
+- [x] T076 [P] AGPL-3.0-only SPDX two-line header on every new source file (`src/managed/Nota.Application/Articulations/*.cs`, `src/native/nota.engine/src/engine/ArticulationTable.*`, `tests/Nota.SmokeTest/Articulation*.cs`, new `src/managed/Nota.App/*` files) — *done 2026-11-09: all 24 new files carry the two-line AGPL-3.0-only header*
+- [x] T077 [P] New dependency: none (XML is the .NET base library) → N/A — *done 2026-11-09: no package, FetchContent or find_package added; CMake gains only the two new source files*
+- [x] T078 [P] `CHANGELOG.md` `[Unreleased]` entry for articulation maps and the track MIDI offset — *done 2026-11-09: Added — articulation maps, the map manager, track MIDI offset, notes coloured by articulation*
+- [ ] T079 FEATURES.md and user manual — *FEATURES.md is updated. EN/RU articulation-map pages, links from the track and piano-roll pages, screenshots and capture tooling are prepared and committed separately in `../nota-docs`. `npm run build` and `npm run check` pass (zero errors). The patch is [attached to PR #549](https://github.com/thoi1/nota/blob/pr-assets/pr549-documentation/nota-docs.patch); upstream manual integration remains pending, so this task stays open. The guide includes FR-023 loop-start limits. No keyboard shortcut was added.*
+- [x] T080 Engine behaviour change → smoke test extended in `tests/Nota.SmokeTest/` (T010, T023, T041, T045, T054); confirm all pass — *done 2026-11-09: full smoke test with the rebuilt engine 5401 pass / 0 fail, 153 articulation checks (T010, T023, T041 self-test 25 checks, T045, T054, T059, T066)*
+
+---
+
+## Dependencies & Execution Order
+
+- **Setup (Phase 1)**: done
+- **Foundational (Phase 2)**: T011–T023 block every story. Order: T012 → T013 → T014 → T015 → T016 → T017 → T019 → T022; T018, T020, T021 in parallel; T023 last
+- **US1 (P1)**: after Phase 2. T028 → T030 → T031 → T032 / T033; T029 parallel
+- **US2 (P1)**: after Phase 2. T036 → T037 → T038 → T039 → T040 → T041; T042 after T038; UI T043–T044 parallel to the engine work once T019 exists
+- **US3 (P1)**: T048 needs T037 (actions) and T013 (offsets in the table); T049 needs T042
+- **US4, US5 (P2)**: after US1 (a map must exist to show); independent of each other
+- **US6 (P3)**: after US5 (manager hosts it)
+- **Polish**: after the stories in scope
+
+### Parallel opportunities
+
+- Phase 2: T018 (plug-in host), T020 (compiler), T021 (file format) in different files
+- US1: T029 (store) alongside T028/T030
+- US2: T043/T044 (piano roll) alongside T036–T041 (engine)
+- US4: T055 and T056 together
+
+## Parallel Example: Phase 2
+
+```text
+Task: "T018 eventChannel + programChange in Instrument.h and PluginInstrument.cpp"
+Task: "T020 ArticulationMapCompiler.cs"
+Task: "T021 ArticulationMapFile.cs"
+```
+
+## Implementation Strategy
+
+### MVP
+
+Phase 2 + US1 + US2 + US3 (all P1): import a real map, articulate notes, hear them switch in time. Stop and validate with quickstart G on Kontakt before P2 work.
+
+### Incremental delivery
+
+1. Phase 2 → a map on a track through the ABI, saved and undoable
+2. US1 → import and assign from the UI
+3. US2 → per-note articulations play
+4. US3 → compensation
+5. US4 / US5 → readability and editing
+6. US6 → presets; measurement only if verified
+
+## Notes
+
+- Nothing is committed automatically (owner's rule); no branch, no push
+- `.soundvariation` stays unsupported until a real file is supplied; then extend contracts/import-formats.md first
+- A task is checked only when its test passes, not when it compiles
+
+## Phase 10: Convergence
+
+*Appended by `/speckit-converge` (T071), 2026-11-09. IDs start at T090: the intro's "T089 reviews it" is a stale reference (the review is T071), so T081–T089 are left unused to keep it unambiguous.*
+
+- [ ] T090 Send bank select before program change within each articulation, whatever order its actions are listed in, per FR-022 (partial) — `ArticulationTable::build` keeps list order and `sendActions` sends it as is
+- [ ] T091 Say in the Track inspector when the track's instrument takes no articulation MIDI (a built-in, or a rack without a plug-in), so the skipped actions aren't silent, per spec Edge Cases "instrument ignores channels, programs or banks" (missing) — the engine gates on `Instrument::takesArticulations()` but nothing reaches the UI
+- [ ] T092 Count articulation events dropped on a full block buffer during playback, per plan "on overflow events are dropped and counted" (partial) — the render call sites don't pass `dropped`
+- [x] T093 Make the chase re-send the articulation whose switch fired last in time (the latest trigger before the landing point), not the last by beat, so a seek gives the same state as straight playback when per-articulation offsets or leads reorder the triggers, per FR-021 (partial) — *done with the PR #549 review fixes: the scheduler decides latching switches by trigger time across the whole track, and the chase takes the last switch before the landing point (self-test 11, 25, 27)*
+- [ ] T094 Let the manager create, rename and remove articulation groups, or record that groups come only from imported files, per FR-001 / FR-009 (partial)
+- [x] T095 Record `Instrument::takesArticulations()` — *documented in research R3 and the C ABI contract: hosted plug-ins and racks containing one receive articulation actions; built-ins do not. The user guide explains the recipient gate and rack limits.*
+- [x] T096 Correct the C ABI contract and task reference — *the self-test returns 0 on pass or the failing probe number; the implemented API is marked verified; explicit channel handling and the recipient gate match the code. The intro now names T071.*
+
+## PR #549 review fixes
+
+*2026-11-09: the CI perf gate and the automated review (Greptile, 7 comments) on PR #549. The user authorized separate fix commits for the PR; verification is recorded in `.specify/bugs/pr549-review/test.md`.*
+
+- [x] R1 Perf gate: remove the no-map rendering and publication overhead — *revision `96733e0e` passed Linux/Valgrind CI, run `42617643537`. Revision `8abb3ad1` regressed `edit-warp-split` by +4.59% instructions (run `42622338564`): graph clones allocated a fresh Session player with release storage before replacing it. Clones now reuse the existing player during construction. PR source `9eb6382c` passed Linux/Valgrind CI, run `42627356463`: `edit-warp-split` is +0.45%, within the 1% limit; all engine scenarios pass. The no-map note specialization and cheap timeline checks remain in place.*
+- [x] R2 A chase in a block shorter than the 20 ms hold dropped its keyswitch release, leaving the key held — *the arrangement retains its chase origin; Session retains actual keys and remaining rendered frames so tempo changes cannot skip the release (self-tests 26, 34–37)*
+- [x] R3 Session slot, short loop with a large offset: notes and switches more than one pass away were lost — *pass ranges follow shifted starts, note ends, leads and holds with no arbitrary pass cap (self-tests 29, 30, 33; C ABI smoke: +1500 ms spans 3 passes of a 500 ms loop and 48 passes of a 31.25 ms loop)*
+- [x] R4 Session slot launch dropped a switch whose lead falls before the launch — *the first block after a launch (also legato) chases what is in force (self-tests 25, 35)*
+- [x] R5 Session slot offsets moved notes but not their recorded expression — *notes and expression share the same shifted times and pass enumeration; a timed-instrument probe verifies opening pressure for positive and negative combined track/articulation offsets (self-test 32)*
+- [x] R6 Manager: a library copy with the same id hid a different project copy; Save could overwrite restored settings — *the catalog lists the project's copy, flagged "differs from your library"; Save writes it to the library (smoke test)*
+- [x] R7 Overlapping clips: one clip's latching switches were thinned without regard to another clip — *timelines keep every latching point; whether it sends is decided at playback across all clips (self-test 27)*
+- [x] R8 Overlapping momentary notes sharing a keyswitch: the first to end released the key the other still held — *a key is released only when no other momentary note holds it, including different articulations in separate clips (self-tests 28, 31)*
+- [x] R9 Session tempo changes during a latching switch's 20 ms hold could skip the release — *fixed-capacity pending keys count rendered frames for both natural and chased switches; due releases have priority, map removal still drains them, and launch/stop clears flushed keys (self-tests 36, 37)*
+- [x] R10 Duplicate readable `.notamap` files with the same ID made the manager's catalog throw — *the lookup keeps the first copy per ID and continues to prefer project maps; manager regressions cover project-backed and library-only catalogs*
+- [x] R11 Muted/solo-gated Session tracks retained obsolete queued releases after flushing voices — *discard pending releases on the silent-track path; native check 38 reproduces the old failure and verifies unmuting into a momentary hold of the same key*
+
+
+## PR #549 documentation attachments
+
+- [x] Update the PR description from the template with the final behaviour, validation and remaining limits.
+- [x] Capture comparable inspector and piano-roll screenshots, plus the manager and import preview.
+- [x] Attach before/after benchmark charts, tables, raw data, measured revisions and reproduction instructions on `pr-assets`.
+- [x] Prepare and validate the EN/RU manual update as a separate docs-repository patch.
+- [ ] Publish the attached manual patch to the upstream documentation site (separate repository).
+
+See [review-evidence.md](review-evidence.md) for the attachment index and exact validation scope.
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.cs
index 8ebcd95a..2d5a2efd 100644
--- a/src/managed/Nota.App/App.axaml.cs
+++ b/src/managed/Nota.App/App.axaml.cs
@@ -56,6 +56,7 @@ public partial class App : Avalonia.Application
services.AddSingleton<IProjectStore, ProjectStore>();
services.AddSingleton<IProjectHistory>(_ => new ProjectHistory(AppInfo.Version));
services.AddSingleton<IPresetStore, PresetStore>();
+ services.AddSingleton<Nota.Application.Articulations.IArticulationLibrary>(_ => new Nota.Infrastructure.Articulations.ArticulationLibraryStore()); // specs/085
services.AddSingleton<IFactoryPresets, FactoryPresetCatalog>();
services.AddSingleton<IPresetAudition, PresetAudition>();
services.AddSingleton<IDrumKits, DrumKitService>();
diff --git a/src/managed/Nota.App/ArticulationImportPreview.cs b/src/managed/Nota.App/ArticulationImportPreview.cs
new file mode 100644
index 00000000..f57be2b3
--- /dev/null
+++ b/src/managed/Nota.App/ArticulationImportPreview.cs
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// What an articulation map file holds, before it lands on a track (specs/085, US1): every
+// articulation with its colour and MIDI, and everything the import couldn't carry over, grouped
+// by how much it matters. Accept returns true; the caller assigns and stores the map. A file that
+// couldn't be read shows only its errors, with Close.
+
+using System.Linq;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Nota.Application.Articulations;
+using Nota.Application.Localization;
+
+namespace Nota.App;
+
+public sealed class ArticulationImportPreview : NotaWindow
+{
+ /// <param name="acceptLabel">The accept button's text; null = "Assign to track" (the inspector's import).</param>
+ public ArticulationImportPreview(string fileName, ArticulationImportResult result, string? acceptLabel = null)
+ {
+ Title = Loc.T("articulations.preview.title");
+ Width = 560;
+ Height = 560;
+ CanResize = true;
+ MinWidth = 420;
+ MinHeight = 320;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner;
+ Background = NotaPalette.Panel;
+
+ var body = new StackPanel { Spacing = 14 };
+ var map = result.Map;
+ body.Children.Add(new TextBlock
+ {
+ Text = map?.Name ?? fileName, FontSize = 15, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary,
+ TextTrimming = TextTrimming.CharacterEllipsis,
+ });
+ body.Children.Add(new TextBlock
+ {
+ Text = map is null ? fileName : Loc.F("articulations.preview.subtitle", ArticulationText.Count(map), fileName),
+ FontSize = 11, Foreground = NotaPalette.TextTertiary, TextTrimming = TextTrimming.CharacterEllipsis,
+ });
+
+ foreach (var (severity, ink) in new[] { (ImportSeverity.Error, NotaPalette.Danger), (ImportSeverity.Warning, NotaPalette.Warning), (ImportSeverity.Info, NotaPalette.TextSecondary) })
+ {
+ var msgs = result.Messages.Where(m => m.Severity == severity).ToList();
+ if (msgs.Count == 0) continue;
+ var list = new StackPanel { Spacing = 4 };
+ foreach (var m in msgs)
+ list.Children.Add(new TextBlock { Text = m.Text, FontSize = 11, LineHeight = 16, Foreground = ink, TextWrapping = TextWrapping.Wrap });
+ body.Children.Add(Section(severity switch
+ {
+ ImportSeverity.Error => Loc.T("articulations.preview.errors"),
+ ImportSeverity.Warning => Loc.T("articulations.preview.warnings"),
+ _ => Loc.T("articulations.preview.notes"),
+ }, list));
+ }
+
+ if (map is not null && map.Articulations.Count > 0)
+ {
+ var rows = new StackPanel { Spacing = 2 };
+ foreach (var a in map.Articulations) rows.Children.Add(Row(a));
+ body.Children.Add(Section(Loc.T("articulations.preview.articulations"), rows));
+ }
+
+ var accept = new Button { Content = acceptLabel ?? Loc.T("articulations.preview.assign"), Classes = { "primary" }, IsVisible = map is not null };
+ accept.Click += (_, _) => Close(true);
+ var cancel = new Button { Content = map is null ? Loc.T("common.close") : Loc.T("common.cancel"), Classes = { "ghost" } };
+ cancel.Click += (_, _) => Close(false);
+ var buttons = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right,
+ Margin = new Thickness(20, 12, 20, 20), Children = { cancel, accept },
+ };
+
+ var scroll = new ScrollViewer
+ {
+ Content = body, Padding = new Thickness(20, 20, 20, 0),
+ HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
+ };
+ var root = new DockPanel();
+ DockPanel.SetDock(buttons, Dock.Bottom);
+ root.Children.Add(buttons);
+ root.Children.Add(scroll);
+ SetBody(root);
+ }
+
+ private static Control Section(string head, Control body)
+ => new StackPanel { Spacing = 8, Children = { SessionView.SectionHead(head), body } };
+
+ private static TextBlock Wrapped(TextBlock t) { t.TextWrapping = TextWrapping.Wrap; return t; }
+
+ // One articulation: swatch, name (short name), and the MIDI it sends.
+ private static Control Row(Articulation a)
+ {
+ var swatch = new Border
+ {
+ Width = 10, Height = 10, CornerRadius = NotaRadius.Badge, Background = Swatch(a),
+ VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 4, 8, 0),
+ };
+ string head = a.ShortName.Length > 0 && a.ShortName != a.Name ? $"{a.Name} ({a.ShortName})" : a.Name;
+ var text = new StackPanel
+ {
+ Spacing = 1,
+ Children =
+ {
+ new TextBlock { Text = head, FontSize = 11, Foreground = a.Enabled ? NotaPalette.TextPrimary : NotaPalette.TextDisabled, TextTrimming = TextTrimming.CharacterEllipsis },
+ Wrapped(ClipEditorKit.Mono(ArticulationText.Actions(a), 10, NotaPalette.TextTertiary)),
+ },
+ };
+ var row = new DockPanel { Margin = new Thickness(0, 2) };
+ DockPanel.SetDock(swatch, Dock.Left);
+ row.Children.Add(swatch);
+ row.Children.Add(text);
+ return row;
+ }
+
+ // The articulation's own colour, else the track palette colour for its slot
+ // (ArticulationColours.PaletteSlot) — the same colour its notes take in the piano roll.
+ internal static IBrush Swatch(Articulation a)
+ {
+ if (a.ColorArgb is uint argb) return new SolidColorBrush(Color.FromUInt32(argb));
+ return ArrangementView.TrackBrush(ArticulationColours.PaletteSlot(a, ArrangementView.PaletteBases) * ArrangementView.PaletteShades);
+ }
+
+ /// <summary>The same colour as <see cref="Swatch"/>, as a value for drawing: read at render time,
+ /// so a palette slot follows the theme.</summary>
+ internal static Color ColourOf(Articulation a)
+ => a.ColorArgb is uint argb ? Color.FromUInt32(argb)
+ : ArrangementView.TrackColorForIndex(ArticulationColours.PaletteSlot(a, ArrangementView.PaletteBases) * ArrangementView.PaletteShades);
+}
diff --git a/src/managed/Nota.App/ArticulationMapManager.cs b/src/managed/Nota.App/ArticulationMapManager.cs
new file mode 100644
index 00000000..4ff7a926
--- /dev/null
+++ b/src/managed/Nota.App/ArticulationMapManager.cs
@@ -0,0 +1,922 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The articulation map manager (specs/085, US5: T061–T063, T065). Three columns: the maps (the
+// library's, plus any a project track holds that the library doesn't), the open map's
+// articulations, and the selected articulation's details — names, colour, group, trigger, offset,
+// lead, enabled, default and its MIDI actions in send order.
+//
+// Edits go to a working copy. Save writes it to the library and puts it on every track holding the
+// map's id, as one undo step, and says how many (FR-010); Revert throws the copy away. Switching map
+// or closing with unsaved changes asks first. The editing rules (ids never reused, a removed default
+// cleared, actions kept in order, a map checked before saving) live in ArticulationMapEdits, where
+// the smoke test checks them. Files dropped from Explorer import like Import… does.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Avalonia.Platform.Storage;
+using Avalonia.Threading;
+using Nota.Application;
+using Nota.Application.Articulations;
+using Nota.Application.Localization;
+
+namespace Nota.App;
+
+public sealed class ArticulationMapManager : NotaWindow
+{
+ private static ArticulationMapManager? _open;
+
+ /// <summary>Shows the manager (one per app), on the map of the track <paramref name="selectedTrack"/>
+ /// names when it has one. <paramref name="selectedTrack"/> is asked again for Assign.</summary>
+ // The open manager is brought back whatever state it is in (.specify/bugs/articulation-manager-reopen):
+ // one that was shown and is no longer visible is replaced, a minimized one (owned, so it has no
+ // taskbar button) is restored, and it is shown and activated after the click has finished, as
+ // the Lens and Scope windows are, so the clicked window doesn't take activation back.
+ internal static void Open(Window owner, IAudioEngine engine, Func<int> selectedTrack)
+ {
+ var log = App.Services?.GetService(typeof(ILogSink)) as ILogSink;
+ if (_open is { _wasShown: true, IsVisible: false } gone)
+ {
+ log?.Info("Articulation maps: the open manager wasn't visible any more; opening a new one");
+ if (_open == gone) _open = null;
+ }
+ if (_open is { } w)
+ {
+ log?.Info($"Articulation maps: bringing back the open manager ({w.WindowState}, visible {w.IsVisible})");
+ if (w.WindowState == WindowState.Minimized) w.WindowState = WindowState.Normal;
+ if (!w.Dirty) w.Reload(w.TrackMapId());
+ Dispatcher.UIThread.Post(w.Activate, DispatcherPriority.Background);
+ return;
+ }
+ var m = new ArticulationMapManager(engine, selectedTrack);
+ _open = m;
+ m.Opened += (_, _) => m._wasShown = true;
+ m.Closed += (_, _) => { if (_open == m) _open = null; };
+ Dispatcher.UIThread.Post(() => { m.Show(owner); m.Activate(); }, DispatcherPriority.Background);
+ }
+
+ private bool _wasShown;
+
+ private const double OffsetRangeMs = ArticulationMapCompiler.MaxOffsetMs, LeadRangeMs = ArticulationMapCompiler.MaxLeadMs;
+
+ private readonly IAudioEngine _engine;
+ private readonly IArticulationLibrary? _lib;
+ private readonly Func<int> _selectedTrack;
+
+ private List<(ArticulationMap Map, bool OnlyInProject, bool DiffersFromLibrary)> _catalog = new();
+ private int _mapIndex = -1;
+ private ArticulationMap? _work; // the open map, being edited
+ private string? _savedJson; // what it was when opened or last saved
+ private int _artId; // the selected articulation, 0 = none
+ private bool _building; // lists being refilled: ignore their selection events
+ private bool _closeConfirmed;
+ private string? _flash; // a one-off status ("Saved · 3 tracks updated") until the next edit
+
+ private readonly ListBox _maps = new() { SelectionMode = SelectionMode.Single };
+ private readonly ListBox _arts = new() { SelectionMode = SelectionMode.Single };
+ private readonly TextBlock _mapsEmpty = Hint(Loc.T("articulations.manager.empty"));
+ private readonly TextBox _mapName = Field();
+ private readonly TextBox _instrument = Field();
+ private readonly StackPanel _mapHead = new() { Spacing = 8 };
+ private readonly ContentControl _details = new();
+ private TextBlock? _effective; // under Note offset: when this articulation's notes play (FR-018)
+ private readonly TextBlock _status = new() { FontSize = 11, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ private readonly Button _duplicate, _delete, _export, _assign, _revert, _save;
+ private readonly Button _artAdd, _artCopy, _artRemove, _artUp, _artDown;
+ private readonly Dictionary<int, (Border Swatch, TextBlock Name, TextBlock Meta, TextBlock Badge)> _rows = new();
+
+ private ArticulationMapManager(IAudioEngine engine, Func<int> selectedTrack)
+ {
+ _engine = engine;
+ _selectedTrack = selectedTrack;
+ _lib = App.Services?.GetService(typeof(IArticulationLibrary)) as IArticulationLibrary;
+
+ Title = Loc.T("articulations.manager.title");
+ Width = 920;
+ Height = 640;
+ MinWidth = 760;
+ MinHeight = 440;
+ CanResize = true;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner;
+ Background = NotaPalette.Panel;
+
+ // ---- maps column
+ var newMap = TextButton(Loc.T("articulations.manager.new"), Loc.T("articulations.manager.new_tip"), NewMap);
+ var import = TextButton(Loc.T("articulations.manager.import"), Loc.T("articulations.manager.import_tip"), () => _ = PickAndImport());
+ _duplicate = TextButton(Loc.T("articulations.manager.duplicate"), Loc.T("articulations.manager.duplicate_tip"), () => _ = DuplicateMap());
+ _delete = TextButton(Loc.T("articulations.manager.delete"), Loc.T("articulations.manager.delete_tip"), () => _ = DeleteMap());
+ _maps.SelectionChanged += (_, _) => { if (!_building) _ = SwitchMap(_maps.SelectedIndex); };
+ var mapsCol = Column(Loc.T("articulations.manager.maps"),
+ new Panel { Children = { _maps, _mapsEmpty } },
+ new WrapPanel { Children = { newMap, import, _duplicate, _delete } },
+ Hint(Loc.T("articulations.manager.drop_hint")));
+
+ // ---- articulations column
+ _mapName.TextChanged += (_, _) => { if (_building || _work is null) return; _work.Name = _mapName.Text ?? ""; Edited(); };
+ _instrument.TextChanged += (_, _) => { if (_building || _work is null) return; _work.InstrumentName = _instrument.Text ?? ""; Edited(); };
+ ToolTip.SetTip(_mapName, Loc.T("articulations.manager.name_tip"));
+ ToolTip.SetTip(_instrument, Loc.T("articulations.manager.instrument_tip"));
+ _mapHead.Children.Add(Labelled(Loc.T("articulations.manager.name"), _mapName));
+ _mapHead.Children.Add(Labelled(Loc.T("articulations.manager.instrument"), _instrument));
+ _arts.SelectionChanged += (_, _) =>
+ {
+ if (_building || _work is null) return;
+ int k = _arts.SelectedIndex;
+ _artId = k >= 0 && k < _work.Articulations.Count ? _work.Articulations[k].Id : 0;
+ BuildDetails();
+ UpdateButtons();
+ };
+ _artAdd = IconButton(GlyphKind.Plus, Loc.T("articulations.manager.add_tip"), AddArticulation);
+ _artCopy = IconButton(GlyphKind.Duplicate, Loc.T("articulations.manager.copy_tip"), CopyArticulation);
+ _artRemove = IconButton(GlyphKind.Trash, Loc.T("articulations.manager.remove_tip"), RemoveArticulation);
+ _artUp = IconButton(GlyphKind.ChevronUp, Loc.T("articulations.manager.up_tip"), () => MoveArticulation(-1));
+ _artDown = IconButton(GlyphKind.ChevronDown, Loc.T("articulations.manager.down_tip"), () => MoveArticulation(1));
+ var artsCol = Column(Loc.T("articulations.manager.articulations"),
+ _arts,
+ new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { _artAdd, _artCopy, _artRemove, _artUp, _artDown } },
+ null, head: _mapHead);
+
+ // ---- details column
+ var detailsScroll = new ScrollViewer { Content = _details, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };
+ var detailsCol = Column(Loc.T("articulations.manager.details"), detailsScroll, null, null);
+
+ var columns = new Grid { ColumnDefinitions = new ColumnDefinitions("220,280,*") };
+ Grid.SetColumn(artsCol, 1);
+ Grid.SetColumn(detailsCol, 2);
+ artsCol.BorderBrush = detailsCol.BorderBrush = NotaPalette.Rule;
+ artsCol.BorderThickness = detailsCol.BorderThickness = new Thickness(1, 0, 0, 0);
+ columns.Children.Add(mapsCol);
+ columns.Children.Add(artsCol);
+ columns.Children.Add(detailsCol);
+
+ // ---- footer
+ _export = TextButton(Loc.T("articulations.manager.export"), Loc.T("articulations.manager.export_tip"), () => _ = Export());
+ _assign = TextButton(Loc.T("articulations.manager.assign"), Loc.T("articulations.manager.assign_tip"), Assign);
+ _revert = TextButton(Loc.T("articulations.manager.revert"), Loc.T("articulations.manager.revert_tip"), Revert);
+ _save = TextButton(Loc.T("articulations.manager.save"), Loc.T("articulations.manager.save_tip"), Save);
+ _save.Classes.Add("primary");
+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { _export, _assign, _revert, _save } };
+ var footer = new DockPanel { Margin = new Thickness(16, 10, 16, 14) };
+ DockPanel.SetDock(buttons, Dock.Right);
+ footer.Children.Add(buttons);
+ footer.Children.Add(_status);
+ var footerHost = new Border { BorderBrush = NotaPalette.Rule, BorderThickness = new Thickness(0, 1, 0, 0), Child = footer };
+
+ var root = new DockPanel();
+ DockPanel.SetDock(footerHost, Dock.Bottom);
+ root.Children.Add(footerHost);
+ root.Children.Add(columns);
+ HookDrop(root);
+ SetBody(root);
+
+ // An undo, the MCP or the inspector can change a track's map while this is open; with no
+ // edits pending, coming back to the window shows what is there now.
+ Activated += (_, _) => { if (!Dirty) Reload(_work?.Id); else UpdateFooter(); };
+ Reload(TrackMapId());
+ }
+
+ // ---- state ---------------------------------------------------------------------------------
+
+ private bool Dirty => _work is not null && _savedJson != ArticulationMapFile.Write(_work);
+ private bool OnlyInProject => _mapIndex >= 0 && _mapIndex < _catalog.Count && _catalog[_mapIndex].OnlyInProject;
+ // The project's copy differs from the library's: Save writes the project's into the library.
+ private bool DiffersFromLibrary => _mapIndex >= 0 && _mapIndex < _catalog.Count && _catalog[_mapIndex].DiffersFromLibrary;
+ private Articulation? Selected => _work?.Find(_artId);
+
+ // The map of the selected track, to open on.
+ private string? TrackMapId()
+ {
+ int t = _selectedTrack();
+ return t > 0 ? ArticulationMapAssignment.Read(_engine, t)?.Id : null;
+ }
+
+ // A deep copy through the file format, so the working copy shares nothing with the library's.
+ private static ArticulationMap Copy(ArticulationMap m) => ArticulationMapFile.Read(ArticulationMapFile.Write(m), m.Name).Map ?? m.DuplicateAs(m.Name);
+
+ // Refill the map list and open the map with id <paramref name="openId"/> (else the first).
+ private void Reload(string? openId)
+ {
+ _catalog = ArticulationMapUsage.Catalog(_engine, _lib);
+ int k = openId is null ? -1 : _catalog.FindIndex(x => x.Map.Id == openId);
+ if (k < 0 && _catalog.Count > 0) k = Math.Clamp(_mapIndex, 0, _catalog.Count - 1);
+ _building = true;
+ _maps.Items.Clear();
+ foreach (var (m, onlyInProject, differs) in _catalog) _maps.Items.Add(MapRow(m, onlyInProject, differs));
+ _maps.SelectedIndex = k;
+ _building = false;
+ _mapsEmpty.IsVisible = _catalog.Count == 0;
+ Load(k);
+ }
+
+ private void Load(int k)
+ {
+ _mapIndex = k;
+ _work = k >= 0 && k < _catalog.Count ? Copy(_catalog[k].Map) : null;
+ _savedJson = _work is null ? null : ArticulationMapFile.Write(_work);
+ if (_work is not null && _work.Find(_artId) is null) _artId = _work.Articulations.FirstOrDefault()?.Id ?? 0;
+ _flash = null;
+ _building = true;
+ _mapName.Text = _work?.Name ?? "";
+ _instrument.Text = _work?.InstrumentName ?? "";
+ _building = false;
+ _mapHead.IsVisible = _work is not null;
+ BuildArticulations();
+ BuildDetails();
+ UpdateFooter();
+ }
+
+ // Something in the working copy changed: the status and buttons follow.
+ private void Edited()
+ {
+ _flash = null;
+ UpdateFooter();
+ }
+
+ private async System.Threading.Tasks.Task<bool> ConfirmDiscard()
+ {
+ if (!Dirty || _work is null) return true;
+ return await new ConfirmWindow(Loc.T("articulations.manager.title"),
+ Loc.F("articulations.manager.discard_confirm", MapLabel(_work)), Loc.T("articulations.manager.discard"), Loc.T("common.cancel")).ShowDialog<bool>(this);
+ }
+
+ private async System.Threading.Tasks.Task SwitchMap(int k)
+ {
+ if (k == _mapIndex) return;
+ if (Dirty)
+ {
+ _building = true;
+ _maps.SelectedIndex = _mapIndex; // stay put until the answer
+ _building = false;
+ if (!await ConfirmDiscard()) return;
+ _building = true;
+ _maps.SelectedIndex = k;
+ _building = false;
+ }
+ Load(k);
+ }
+
+ protected override void OnClosing(WindowClosingEventArgs e)
+ {
+ base.OnClosing(e);
+ if (_closeConfirmed || !Dirty) return;
+ e.Cancel = true;
+ Dispatcher.UIThread.Post(async () =>
+ {
+ if (!await ConfirmDiscard()) return;
+ _closeConfirmed = true;
+ Close();
+ });
+ }
+
+ private static string MapLabel(ArticulationMap m) => m.Name.Length > 0 ? m.Name : Loc.T("articulations.manager.untitled");
+ private static string ArtLabel(Articulation a) => a.Name.Length > 0 ? a.Name : "#" + a.Id.ToString(NotaNum.Culture);
+
+ // ---- maps ----------------------------------------------------------------------------------
+
+ private static Control MapRow(ArticulationMap m, bool onlyInProject, bool differs)
+ {
+ string meta = onlyInProject ? Loc.F("articulations.manager.meta_project", ArticulationText.Count(m))
+ : differs ? Loc.F("articulations.manager.meta_differs", ArticulationText.Count(m))
+ : ArticulationText.Count(m);
+ return new StackPanel
+ {
+ Spacing = 1, Margin = new Thickness(0, 2),
+ Children =
+ {
+ new TextBlock { Text = MapLabel(m), FontSize = 11, Foreground = NotaPalette.TextPrimary, TextTrimming = TextTrimming.CharacterEllipsis },
+ new TextBlock { Text = meta, FontSize = 10, Foreground = NotaPalette.TextTertiary, TextTrimming = TextTrimming.CharacterEllipsis },
+ },
+ };
+ }
+
+ // Keeps a map in the library; says so when the library can't take it. True when kept.
+ private async System.Threading.Tasks.Task<bool> Keep(ArticulationMap map)
+ {
+ if (_lib is null) return false;
+ try { _lib.Save(map); return true; }
+ catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ await Notice(Loc.F("articulations.manager.save_failed", ex.Message));
+ return false;
+ }
+ }
+
+ private System.Threading.Tasks.Task Notice(string text)
+ => new ConfirmWindow(Loc.T("articulations.manager.title"), text, Loc.T("common.close"), null).ShowDialog<bool>(this);
+
+ private async void NewMap()
+ {
+ if (!await ConfirmDiscard()) return;
+ var map = new ArticulationMap { Name = Loc.T("articulations.manager.new_name"), Metadata = { ["source"] = "nota" } };
+ if (await Keep(map)) Reload(map.Id);
+ }
+
+ private async System.Threading.Tasks.Task DuplicateMap()
+ {
+ if (_work is null || !await ConfirmDiscard()) return;
+ var source = _catalog[_mapIndex].Map; // the saved map, not unsaved edits that were just discarded
+ var copy = source.DuplicateAs(Loc.F("articulations.manager.copy_name", MapLabel(source)));
+ if (await Keep(copy)) Reload(copy.Id);
+ }
+
+ private async System.Threading.Tasks.Task DeleteMap()
+ {
+ if (_work is null || OnlyInProject || _lib is null) return;
+ var map = _catalog[_mapIndex].Map;
+ bool ok = await new ConfirmWindow(Loc.T("articulations.manager.title"),
+ Loc.F("articulations.manager.delete_confirm", MapLabel(map)), Loc.T("articulations.manager.delete"), Loc.T("common.cancel")).ShowDialog<bool>(this);
+ if (!ok) return;
+ try { _lib.Delete(map.Id); }
+ catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException)
+ {
+ await Notice(Loc.F("articulations.manager.delete_failed", ex.Message));
+ }
+ _savedJson = null;
+ _work = null; // nothing left to discard
+ Reload(null);
+ }
+
+ private async System.Threading.Tasks.Task PickAndImport()
+ {
+ var files = await this.PickFilesAsync(new FilePickerOpenOptions
+ {
+ Title = Loc.T("articulations.preview.title"),
+ AllowMultiple = false,
+ FileTypeFilter = new[]
+ {
+ new FilePickerFileType(Loc.T("articulations.inspector.file_type")) { Patterns = ArticulationImport.PickerExtensions.Select(x => "*" + x).ToArray() },
+ new FilePickerFileType(Loc.T("articulations.inspector.all_files")) { Patterns = new[] { "*" } },
+ },
+ });
+ if (files.Count > 0 && files[0].TryGetLocalPath() is { Length: > 0 } path) await ImportFromFile(path);
+ }
+
+ // Import → preview → (accepted) into the library, then open it. The file is only read.
+ private async System.Threading.Tasks.Task ImportFromFile(string path)
+ {
+ if (!await ConfirmDiscard()) return;
+ var result = ArticulationImport.ImportFile(path);
+ bool ok = await new ArticulationImportPreview(System.IO.Path.GetFileName(path), result, Loc.T("articulations.manager.add_to_library")).ShowDialog<bool>(this);
+ if (!ok || result.Map is not { } map) return;
+ if (await Keep(map)) Reload(map.Id);
+ }
+
+ // Explorer → window, like the inspector's drop (T033): accepted on sight, decided by content.
+ private void HookDrop(Control target)
+ {
+ DragDrop.SetAllowDrop(target, true);
+ DragDrop.AddDragOverHandler(target, (_, e) =>
+ {
+ if (BrowserView.CurrentDrag is not null || !BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.None; return; }
+ e.DragEffects = DragDropEffects.Copy;
+ e.Handled = true;
+ });
+ DragDrop.AddDropHandler(target, (_, e) =>
+ {
+ if (BrowserView.CurrentDrag is not null) return;
+ var file = BrowserView.ExternalPaths(e).FirstOrDefault(System.IO.File.Exists);
+ if (file is null) return;
+ e.Handled = true;
+ Dispatcher.UIThread.Post(() => _ = ImportFromFile(file)); // after the drop returns: the dialogs are modal
+ });
+ }
+
+ // ---- articulations -------------------------------------------------------------------------
+
+ private void BuildArticulations()
+ {
+ _building = true;
+ _arts.Items.Clear();
+ _rows.Clear();
+ int sel = -1;
+ if (_work is not null)
+ for (int i = 0; i < _work.Articulations.Count; i++)
+ {
+ var a = _work.Articulations[i];
+ _arts.Items.Add(ArtRow(a));
+ if (a.Id == _artId) sel = i;
+ }
+ _arts.SelectedIndex = sel;
+ _building = false;
+ UpdateButtons();
+ }
+
+ private Control ArtRow(Articulation a)
+ {
+ var swatch = new Border { Width = 10, Height = 10, CornerRadius = NotaRadius.Badge, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 3, 8, 0) };
+ var name = new TextBlock { FontSize = 11, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = ClipEditorKit.Mono("", 10, NotaPalette.TextTertiary);
+ meta.TextTrimming = TextTrimming.CharacterEllipsis;
+ var badge = new TextBlock { Text = Loc.T("articulations.manager.default_badge"), FontSize = 9, Foreground = NotaPalette.TextMuted, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(6, 2, 0, 0) };
+ _rows[a.Id] = (swatch, name, meta, badge);
+ RefreshRow(a);
+ var row = new DockPanel { Margin = new Thickness(0, 2) };
+ DockPanel.SetDock(swatch, Dock.Left);
+ DockPanel.SetDock(badge, Dock.Right);
+ row.Children.Add(swatch);
+ row.Children.Add(badge);
+ row.Children.Add(new StackPanel { Spacing = 1, Children = { name, meta } });
+ return row;
+ }
+
+ // An edit that doesn't change the list's shape: the row follows in place, so typing a name
+ // neither rebuilds the list nor moves its scroll.
+ private void RefreshRow(Articulation a)
+ {
+ if (!_rows.TryGetValue(a.Id, out var r)) return;
+ r.Swatch.Background = ArticulationImportPreview.Swatch(a);
+ r.Name.Text = ArtLabel(a);
+ r.Name.Foreground = a.Enabled ? NotaPalette.TextPrimary : NotaPalette.TextDisabled;
+ r.Meta.Text = ArticulationText.Actions(a);
+ r.Badge.IsVisible = _work?.DefaultArticulationId == a.Id;
+ }
+
+ private void RefreshRows()
+ {
+ if (_work is null) return;
+ foreach (var a in _work.Articulations) RefreshRow(a);
+ }
+
+ private void AddArticulation()
+ {
+ if (_work is null) return;
+ _artId = ArticulationMapEdits.Add(_work, Loc.F("articulations.manager.add_name", ArticulationMapEdits.NextId(_work)));
+ Structure();
+ }
+
+ private void CopyArticulation()
+ {
+ if (_work is null || Selected is not { } a) return;
+ int id = ArticulationMapEdits.Copy(_work, a.Id, Loc.F("articulations.manager.copy_name", ArtLabel(a)));
+ if (id > 0) _artId = id;
+ Structure();
+ }
+
+ private void RemoveArticulation()
+ {
+ if (_work is null || Selected is not { } a) return;
+ int k = _work.Articulations.IndexOf(a);
+ ArticulationMapEdits.Remove(_work, a.Id);
+ _artId = _work.Articulations.Count == 0 ? 0 : _work.Articulations[Math.Min(k, _work.Articulations.Count - 1)].Id;
+ Structure();
+ }
+
+ private void MoveArticulation(int delta)
+ {
+ if (_work is null || Selected is not { } a) return;
+ if (ArticulationMapEdits.Move(_work, a.Id, delta)) Structure();
+ }
+
+ // An edit that changes the list (add, copy, remove, reorder): rebuild it and the details.
+ private void Structure()
+ {
+ BuildArticulations();
+ BuildDetails();
+ Edited();
+ }
+
+ // ---- details -------------------------------------------------------------------------------
+
+ private void BuildDetails()
+ {
+ _effective = null;
+ if (_work is null || Selected is not { } a)
+ {
+ _details.Content = Hint(_work is null ? "" : Loc.T("articulations.manager.no_selection"));
+ return;
+ }
+ var map = _work;
+ var s = new StackPanel { Spacing = 10, Margin = new Thickness(0, 0, 8, 12) };
+
+ var name = Field(a.Name);
+ name.TextChanged += (_, _) => { a.Name = name.Text ?? ""; RefreshRow(a); Edited(); };
+ ToolTip.SetTip(name, Loc.T("articulations.manager.art_name_tip"));
+ var shortName = Field(a.ShortName);
+ shortName.TextChanged += (_, _) => { a.ShortName = shortName.Text ?? ""; Edited(); };
+ ToolTip.SetTip(shortName, Loc.T("articulations.manager.short_name_tip"));
+ s.Children.Add(Labelled(Loc.T("articulations.manager.name"), name));
+ s.Children.Add(Labelled(Loc.T("articulations.manager.short_name"), shortName));
+ s.Children.Add(Labelled(Loc.T("articulations.manager.colour"), Colours(a)));
+
+ // Group: only the map's groups (the formats define them); "No group" is always there.
+ var groups = new List<(int Id, string Label)> { (0, Loc.T("articulations.manager.no_group")) };
+ groups.AddRange(map.Groups.Select(g => (g.Id, ArticulationText.Group(g))));
+ string groupLabel = groups.FirstOrDefault(g => g.Id == a.GroupId).Label ?? groups[0].Label;
+ var groupChip = SessionView.Chip(groupLabel, false, b => SessionView.Pick(b, groups, v => v == a.GroupId, v => { a.GroupId = v; Edited(); BuildDetails(); }));
+ ToolTip.SetTip(groupChip, Loc.T("articulations.manager.group_tip"));
+ s.Children.Add(SessionView.Row(Loc.T("articulations.manager.group"), groupChip));
+
+ var trigger = SessionView.Segmented(new[] { Loc.T("articulations.manager.latching"), Loc.T("articulations.manager.momentary") },
+ a.Trigger == TriggerMode.Momentary ? 1 : 0, i => { a.Trigger = i == 1 ? TriggerMode.Momentary : TriggerMode.Latching; Edited(); }, compact: true);
+ ToolTip.SetTip(trigger, Loc.T("articulations.manager.trigger_tip"));
+ s.Children.Add(SessionView.Row(Loc.T("articulations.manager.trigger"), trigger));
+
+ var enabled = new CheckBox { Content = Loc.T("articulations.manager.enabled"), IsChecked = a.Enabled, FontSize = 11 };
+ enabled.IsCheckedChanged += (_, _) => { a.Enabled = enabled.IsChecked == true; RefreshRow(a); Edited(); };
+ ToolTip.SetTip(enabled, Loc.T("articulations.manager.enabled_tip"));
+ var isDefault = new CheckBox { Content = Loc.T("articulations.manager.make_default"), IsChecked = map.DefaultArticulationId == a.Id, FontSize = 11 };
+ isDefault.IsCheckedChanged += (_, _) =>
+ {
+ if (isDefault.IsChecked == true) map.DefaultArticulationId = a.Id;
+ else if (map.DefaultArticulationId == a.Id) map.DefaultArticulationId = null;
+ RefreshRows();
+ Edited();
+ };
+ ToolTip.SetTip(isDefault, Loc.T("articulations.manager.default_tip"));
+ s.Children.Add(new WrapPanel { Children = { enabled, isDefault }, ItemSpacing = 16 });
+
+ s.Children.Add(SessionView.Row(Loc.T("articulations.manager.note_offset"),
+ MsBox(a.NoteOffsetMs, -OffsetRangeMs, OffsetRangeMs, Loc.T("articulations.manager.note_offset_tip"), v => a.NoteOffsetMs = v)));
+ _effective = Hint("");
+ s.Children.Add(_effective);
+ RefreshEffective();
+ s.Children.Add(SessionView.Row(Loc.T("articulations.manager.lead"),
+ MsBox(a.TriggerLeadMs, 0, LeadRangeMs, Loc.T("articulations.manager.lead_tip"), v => a.TriggerLeadMs = v)));
+
+ // Actions, in send order.
+ var actions = new StackPanel { Spacing = 6 };
+ for (int i = 0; i < a.Actions.Count; i++) actions.Children.Add(ActionRow(a, i));
+ if (a.Actions.Count == 0) actions.Children.Add(Hint(Loc.T("articulations.action.none")));
+ var addAction = TextButton(Loc.T("articulations.manager.add_action"), Loc.T("articulations.manager.add_action_tip"), () =>
+ {
+ a.Actions.Add(new MidiAction { Kind = MidiActionKind.Keyswitch, Data1 = 24, Data2 = 100 });
+ RefreshRow(a);
+ Edited();
+ BuildDetails();
+ });
+ addAction.HorizontalAlignment = HorizontalAlignment.Left;
+ s.Children.Add(new StackPanel
+ {
+ Spacing = 8, Margin = new Thickness(0, 6, 0, 0),
+ Children = { SessionView.SectionHead(Loc.T("articulations.manager.actions")), actions, addAction },
+ });
+ _details.Content = s;
+ }
+
+ // The track palette as swatches, the articulation's own colour ringed, and Auto (the colour its
+ // palette index or id gives). A swatch stores the colour itself: a map carries RGB, not an index.
+ private Control Colours(Articulation a)
+ {
+ int bases = ArrangementView.PaletteBases, shades = ArrangementView.PaletteShades;
+ var grid = new UniformGrid { Columns = bases };
+ for (int shade = 0; shade < shades; shade++)
+ for (int b = 0; b < bases; b++)
+ {
+ int idx = b * shades + shade;
+ uint argb = ArrangementView.TrackColorForIndex(idx).ToUInt32();
+ bool on = a.ColorArgb == argb;
+ var sw = new Border
+ {
+ Height = 14, Margin = new Thickness(1.5), CornerRadius = NotaRadius.Badge, Background = ArrangementView.TrackBrush(idx),
+ BorderBrush = on ? NotaPalette.TextPrimary : Brushes.Transparent, BorderThickness = new Thickness(on ? 1.5 : 0),
+ Cursor = new Cursor(StandardCursorType.Hand),
+ };
+ sw.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(sw).Properties.IsLeftButtonPressed) return;
+ a.ColorArgb = argb;
+ RefreshRow(a);
+ Edited();
+ BuildDetails();
+ };
+ grid.Children.Add(sw);
+ }
+ var auto = SessionView.Chip(Loc.T("common.auto"), a.ColorArgb is null, _ =>
+ {
+ a.ColorArgb = null;
+ RefreshRow(a);
+ Edited();
+ BuildDetails();
+ });
+ ToolTip.SetTip(auto, Loc.T("articulations.manager.colour_auto_tip"));
+ auto.HorizontalAlignment = HorizontalAlignment.Left;
+ return new StackPanel { Spacing = 6, Children = { grid, auto } };
+ }
+
+ // One action: kind · channel · its data · reorder and remove.
+ private Control ActionRow(Articulation a, int index)
+ {
+ var x = a.Actions[index];
+ var kinds = new List<(MidiActionKind Kind, string Label)>
+ {
+ (MidiActionKind.Keyswitch, Loc.T("articulations.manager.kind_keyswitch")),
+ (MidiActionKind.ControlChange, Loc.T("articulations.manager.kind_cc")),
+ (MidiActionKind.ProgramChange, Loc.T("articulations.manager.kind_program")),
+ (MidiActionKind.BankSelectMsb, Loc.T("articulations.manager.kind_bank_msb")),
+ (MidiActionKind.BankSelectLsb, Loc.T("articulations.manager.kind_bank_lsb")),
+ };
+ var kindChip = SessionView.Chip(kinds.First(k => k.Kind == x.Kind).Label, false, b => SessionView.Pick(b, kinds, v => v == x.Kind, v =>
+ {
+ x.Kind = v;
+ x.Data1 = Math.Clamp(x.Data1, 0, 127);
+ x.Data2 = Math.Clamp(x.Data2, 0, 127);
+ RefreshRow(a);
+ Edited();
+ BuildDetails();
+ }));
+ ToolTip.SetTip(kindChip, Loc.T("articulations.manager.kind_tip"));
+
+ var channels = new List<(int Ch, string Label)> { (0, Loc.T("articulations.manager.note_channel")) };
+ for (int c = 1; c <= 16; c++) channels.Add((c, Loc.F("articulations.manager.channel_n", c)));
+ var chanChip = SessionView.Chip(x.Channel is int ch ? Loc.F("articulations.manager.channel_n", ch) : Loc.T("articulations.manager.note_channel"), false,
+ b => SessionView.Pick(b, channels, v => v == (x.Channel ?? 0), v =>
+ {
+ x.Channel = v == 0 ? null : v;
+ RefreshRow(a);
+ Edited();
+ BuildDetails();
+ }));
+ ToolTip.SetTip(chanChip, Loc.T("articulations.manager.channel_tip"));
+
+ var data = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
+ void Data(int value, bool noteName, string tip, Action<int> set) => data.Children.Add(MidiBox(value, noteName, tip, v => { set(v); RefreshRow(a); Edited(); }));
+ switch (x.Kind)
+ {
+ case MidiActionKind.Keyswitch:
+ Data(x.Data1, true, Loc.T("articulations.manager.key_tip"), v => x.Data1 = v);
+ Data(x.Data2, false, Loc.T("articulations.manager.velocity_tip"), v => x.Data2 = v);
+ break;
+ case MidiActionKind.ControlChange:
+ Data(x.Data1, false, Loc.T("articulations.manager.cc_tip"), v => x.Data1 = v);
+ Data(x.Data2, false, Loc.T("articulations.manager.value_tip"), v => x.Data2 = v);
+ break;
+ case MidiActionKind.ProgramChange:
+ Data(x.Data1, false, Loc.T("articulations.manager.program_tip"), v => x.Data1 = v);
+ break;
+ default:
+ Data(x.Data2, false, Loc.T("articulations.manager.value_tip"), v => x.Data2 = v);
+ break;
+ }
+
+ void Reorder(int delta) { if (ArticulationMapEdits.MoveAction(a, index, delta)) { RefreshRow(a); Edited(); BuildDetails(); } }
+ var up = IconButton(GlyphKind.ChevronUp, Loc.T("articulations.manager.up_tip"), () => Reorder(-1));
+ var down = IconButton(GlyphKind.ChevronDown, Loc.T("articulations.manager.down_tip"), () => Reorder(1));
+ var remove = IconButton(GlyphKind.Trash, Loc.T("articulations.manager.remove_action_tip"), () =>
+ {
+ a.Actions.RemoveAt(index);
+ RefreshRow(a);
+ Edited();
+ BuildDetails();
+ });
+ up.IsEnabled = index > 0;
+ down.IsEnabled = index < a.Actions.Count - 1;
+
+ var tools = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, Children = { up, down, remove } };
+ var row = new DockPanel();
+ DockPanel.SetDock(tools, Dock.Right);
+ row.Children.Add(tools);
+ row.Children.Add(new WrapPanel { ItemSpacing = 4, LineSpacing = 4, Children = { kindChip, chanChip, data } });
+ return row;
+ }
+
+ // A MIDI data value: a number 0–127 or, for a keyswitch, a note name. Enter or leaving sets it;
+ // Esc puts it back; text that isn't a value is ignored.
+ private static TextBox MidiBox(int value, bool noteName, string tip, Action<int> set)
+ {
+ string Show(int v) => noteName ? SamplerModel.NoteName(v) : v.ToString(NotaNum.Culture);
+ string shown = Show(value);
+ var box = new TextBox
+ {
+ Text = shown, FontSize = 11, FontFamily = NotaFonts.MonoFamily, Height = NotaSize.Shell, MinHeight = 0, Width = 52,
+ VerticalContentAlignment = VerticalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Right,
+ };
+ ToolTip.SetTip(box, tip);
+ void Commit()
+ {
+ string text = (box.Text ?? "").Trim();
+ if (text == shown) return;
+ if (ArticulationMapEdits.ParseMidiValue(text, noteName) is not int v) { box.Text = shown; return; }
+ shown = Show(v);
+ box.Text = shown;
+ set(v);
+ }
+ Keys(box, () => shown);
+ box.LostFocus += (_, _) => Commit();
+ return box;
+ }
+
+ private static string Ms(double ms) => NotaNum.Unit(Math.Round(ms), "0", "ms");
+
+ // Milliseconds typed like the inspector's MIDI offset ("−80", "-80 ms", "−0.08 s"), held to the range.
+ private TextBox MsBox(double value, double min, double max, string tip, Action<double> set)
+ {
+ string shown = Ms(value);
+ var box = new TextBox
+ {
+ Text = shown, FontSize = 11, Height = NotaSize.Shell, MinHeight = 0, Width = 96,
+ VerticalContentAlignment = VerticalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Right,
+ };
+ ToolTip.SetTip(box, tip);
+ void Commit()
+ {
+ string text = (box.Text ?? "").Trim();
+ if (text == shown) return;
+ double? pos = ValueText.Solve(text, shown, p => Ms(min + (max - min) * p));
+ if (pos is not double p) { box.Text = shown; return; }
+ double ms = Math.Round(min + (max - min) * p);
+ shown = Ms(ms);
+ box.Text = shown;
+ set(ms);
+ Edited();
+ }
+ Keys(box, () => shown);
+ box.LostFocus += (_, _) => Commit();
+ return box;
+ }
+
+ // Enter commits (by leaving the box), Esc restores what it showed.
+ private static void Keys(TextBox box, Func<string> shown)
+ {
+ box.KeyDown += (_, e) =>
+ {
+ if (e.Key is not (Key.Enter or Key.Escape)) return;
+ if (e.Key == Key.Escape) box.Text = shown();
+ e.Handled = true;
+ TopLevel.GetTopLevel(box)?.FocusManager?.Focus(null);
+ };
+ }
+
+ // ---- footer --------------------------------------------------------------------------------
+
+ private void UpdateButtons()
+ {
+ bool open = _work is not null;
+ _duplicate.IsEnabled = open;
+ _delete.IsEnabled = open && !OnlyInProject && _lib is not null;
+ ToolTip.SetTip(_delete, OnlyInProject ? Loc.T("articulations.manager.delete_project_tip") : Loc.T("articulations.manager.delete_tip"));
+ _artAdd.IsEnabled = open;
+ bool sel = Selected is not null;
+ int k = sel ? _work!.Articulations.IndexOf(Selected!) : -1;
+ _artCopy.IsEnabled = _artRemove.IsEnabled = sel;
+ _artUp.IsEnabled = sel && k > 0;
+ _artDown.IsEnabled = sel && k < _work!.Articulations.Count - 1;
+ }
+
+ // The status line (what stops a save, unsaved changes, or how many tracks use the map) and
+ // the buttons that depend on it.
+ private void UpdateFooter()
+ {
+ UpdateButtons();
+ RefreshEffective();
+ bool open = _work is not null, dirty = Dirty;
+ var problems = open ? ArticulationMapEdits.Check(_work!) : new();
+ _status.Foreground = problems.Count > 0 ? NotaPalette.Warning : NotaPalette.TextTertiary;
+ _status.Text = !open ? ""
+ : problems.Count > 0 ? ProblemText(problems[0])
+ : _flash ?? (dirty ? Loc.T("articulations.manager.unsaved")
+ : Loc.Plural("articulations.manager.used_on", ArticulationMapUsage.TracksUsing(_engine, _work!.Id).Count));
+ _export.IsEnabled = open && problems.Count == 0;
+ _save.IsEnabled = open && problems.Count == 0 && (dirty || OnlyInProject || DiffersFromLibrary) && _lib is not null;
+ _revert.IsEnabled = open && dirty;
+ int track = InstrumentTrack();
+ _assign.IsEnabled = open && !dirty && problems.Count == 0 && track > 0;
+ ToolTip.SetTip(_assign, dirty ? Loc.T("articulations.manager.assign_dirty_tip")
+ : track <= 0 ? Loc.T("articulations.manager.assign_no_track_tip") : Loc.T("articulations.manager.assign_tip"));
+ }
+
+ // Under Note offset: when the selected articulation's notes play — the track offset plus its
+ // own, as the inspector says it (FR-018). Follows typing, Save, and the track offset changing.
+ private void RefreshEffective()
+ {
+ if (_effective is null || _work is null || Selected is not { } a) return;
+ if (!a.Enabled) { _effective.Text = Loc.T("articulations.manager.effective_disabled"); return; }
+ _effective.Text = ArticulationMapUsage.TrackOffsetFor(_engine, _work.Id, _selectedTrack()) is double trackMs
+ ? Loc.F("articulations.manager.effective", Ms(trackMs + a.NoteOffsetMs), Ms(trackMs), Ms(a.NoteOffsetMs))
+ : Loc.T("articulations.manager.effective_each");
+ }
+
+ private static string ProblemText((ArticulationMapEdits.Problem Problem, string Subject) p) => p.Problem switch
+ {
+ ArticulationMapEdits.Problem.NoName => Loc.T("articulations.manager.problem_no_name"),
+ ArticulationMapEdits.Problem.ArticulationWithoutName => Loc.F("articulations.manager.problem_articulation_name", p.Subject),
+ ArticulationMapEdits.Problem.DuplicateId => Loc.F("articulations.manager.problem_duplicate_id", p.Subject),
+ ArticulationMapEdits.Problem.InvalidAction => Loc.F("articulations.manager.problem_invalid_action", p.Subject),
+ _ => Loc.T("articulations.manager.problem_default_missing"),
+ };
+
+ // The selected track when it is an instrument track, else 0.
+ private int InstrumentTrack()
+ {
+ int t = _selectedTrack();
+ if (t <= 0) return 0;
+ for (int i = 0; i < _engine.TrackCount; i++)
+ if (_engine.TryGetTrackInfo(i, out var ti) && ti.Id == t) return ti.IsInstrument ? t : 0;
+ return 0;
+ }
+
+ private async void Save()
+ {
+ if (_work is null || ArticulationMapEdits.Check(_work).Count > 0) return;
+ if (!await Keep(_work)) return;
+ int n = ArticulationMapUsage.ApplyEverywhere(_engine, _work); // one undo step (FR-010)
+ string id = _work.Id;
+ Reload(id);
+ _flash = Loc.Plural("articulations.manager.saved", n);
+ UpdateFooter();
+ }
+
+ private void Revert()
+ {
+ if (_work is null) return;
+ Load(_mapIndex);
+ }
+
+ private void Assign()
+ {
+ int t = InstrumentTrack();
+ if (_work is null || t <= 0 || Dirty) return;
+ _flash = ArticulationMapAssignment.Assign(_engine, t, _work)
+ ? Loc.T("articulations.manager.assigned") : Loc.T("articulations.inspector.assign_failed");
+ UpdateFooter();
+ }
+
+ private async System.Threading.Tasks.Task Export()
+ {
+ if (_work is null) return;
+ var file = await this.PickSaveFileAsync(new FilePickerSaveOptions
+ {
+ Title = Loc.T("articulations.manager.export_title"),
+ DefaultExtension = ArticulationMapFile.Extension.TrimStart('.'),
+ SuggestedFileName = MapLabel(_work) + ArticulationMapFile.Extension,
+ FileTypeChoices = new[]
+ {
+ new FilePickerFileType(Loc.T("articulations.manager.file_type")) { Patterns = new[] { "*" + ArticulationMapFile.Extension } },
+ },
+ });
+ var path = file?.TryGetLocalPath();
+ if (path is null) return;
+ if (!path.EndsWith(ArticulationMapFile.Extension, StringComparison.OrdinalIgnoreCase)) path += ArticulationMapFile.Extension;
+ try
+ {
+ System.IO.File.WriteAllText(path, ArticulationMapFile.Write(_work));
+ _flash = Loc.F("articulations.manager.exported", System.IO.Path.GetFileName(path));
+ UpdateFooter();
+ }
+ catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException)
+ {
+ await Notice(Loc.F("articulations.manager.export_failed", ex.Message));
+ }
+ }
+
+ // ---- building blocks -----------------------------------------------------------------------
+
+ // A titled column: an optional head above, the body filling, tools and a hint below.
+ private static Border Column(string title, Control body, Control? tools, Control? hint, Control? head = null)
+ {
+ var top = new StackPanel { Spacing = 10, Margin = new Thickness(0, 0, 0, 10), Children = { SessionView.SectionHead(title) } };
+ if (head is not null) top.Children.Insert(0, head);
+ var bottom = new StackPanel { Spacing = 8, Margin = new Thickness(0, 10, 0, 0) };
+ if (tools is not null) bottom.Children.Add(tools);
+ if (hint is not null) bottom.Children.Add(hint);
+ var dock = new DockPanel();
+ DockPanel.SetDock(top, Dock.Top);
+ DockPanel.SetDock(bottom, Dock.Bottom);
+ dock.Children.Add(top);
+ dock.Children.Add(bottom);
+ dock.Children.Add(body);
+ return new Border { Padding = new Thickness(16, 14, 12, 0), Child = dock };
+ }
+
+ private static Control Labelled(string label, Control field) => new StackPanel
+ {
+ Spacing = 4,
+ Children = { new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextTertiary }, field },
+ };
+
+ private static TextBox Field(string text = "") => new()
+ {
+ Text = text, FontSize = 11, Height = NotaSize.Shell, MinHeight = 0, VerticalContentAlignment = VerticalAlignment.Center,
+ };
+
+ private static TextBlock Hint(string text) => new()
+ {
+ Text = text, FontSize = 11, LineHeight = 16, Foreground = NotaPalette.TextTertiary, TextWrapping = TextWrapping.Wrap,
+ };
+
+ private static Button TextButton(string text, string tip, Action click)
+ {
+ var b = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(0, 0, 6, 6), Content = text };
+ ToolTip.SetTip(b, tip);
+ b.Click += (_, _) => click();
+ return b;
+ }
+
+ private static Button IconButton(GlyphKind kind, string tip, Action click)
+ {
+ var b = new Button
+ {
+ Width = NotaSize.Shell, Height = NotaSize.Shell, Padding = new Thickness(0), Content = new Glyph(kind, 12),
+ HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center,
+ };
+ ToolTip.SetTip(b, tip);
+ b.Click += (_, _) => click();
+ return b;
+ }
+}
diff --git a/src/managed/Nota.App/ClipEditorView.cs b/src/managed/Nota.App/ClipEditorView.cs
index 3b465051..cabaeb2c 100644
--- a/src/managed/Nota.App/ClipEditorView.cs
+++ b/src/managed/Nota.App/ClipEditorView.cs
@@ -66,7 +66,7 @@ public sealed class ClipEditorView : UserControl
var right = new StackPanel
{
Orientation = Orientation.Horizontal, Spacing = 12,
- Children = { AuditionControl(), FitControl(roll), SnapControl(roll), HeaderDivider(), ScaleControls(), HeaderDivider(), _toolsToggle },
+ Children = { AuditionControl(), NoteColourControl(), FitControl(roll), SnapControl(roll), HeaderDivider(), ScaleControls(), HeaderDivider(), _toolsToggle },
};
var header = Header(roll.TrackBrush, HeaderName(clipName), "MIDI", tabs, null, right, out _nameText, out _colorBar, _props, _props.Flow);
DockPanel.SetDock(header, Dock.Top);
@@ -130,6 +130,23 @@ public sealed class ClipEditorView : UserControl
return b;
}
+ // Note colour by articulation (specs/085, FR-015): the palette chip. App-wide like the speaker,
+ // so every open editor's chip follows a flip made in another.
+ private static Control NoteColourControl()
+ {
+ var b = new ToggleButton
+ {
+ Content = new Glyph(GlyphKind.Palette, 14), Padding = new Thickness(8, 0), Classes = { "chip" },
+ IsChecked = PianoRollView.NoteColorByArticulation,
+ };
+ ToolTip.SetTip(b, Loc.T("articulations.colour.chip_tip"));
+ b.Click += (_, _) => PianoRollView.SetNoteColorByArticulation(b.IsChecked == true);
+ void Sync() => b.IsChecked = PianoRollView.NoteColorByArticulation;
+ b.AttachedToVisualTree += (_, _) => { Sync(); PianoRollView.NoteColorModeChanged += Sync; };
+ b.DetachedFromVisualTree += (_, _) => PianoRollView.NoteColorModeChanged -= Sync;
+ return b;
+ }
+
// Fit to notes (⇧F): rows zoom so every note of the clip is in view.
private static Control FitControl(PianoRollView roll)
{
diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.cs
index 9881b422..d4015913 100644
--- a/src/managed/Nota.App/MainWindow.Commands.cs
+++ b/src/managed/Nota.App/MainWindow.Commands.cs
@@ -76,6 +76,7 @@ public partial class MainWindow
B("view.mixer", ToggleMixer);
B("view.mixerFloat", () => SetMixerFloating(!MixerFloating));
B("view.connectPhone", ShowConnectPhone);
+ B("view.articulationMaps", ShowArticulationMaps);
B("view.toggleBrowser", () => OnMenuToggleBrowser(this, e));
B("view.toggleDetail", () => OnMenuToggleClip(this, e));
B("view.maximizeDetail", ToggleDetailMaximized,
diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.cs
index cbad4ad4..2d850786 100644
--- a/src/managed/Nota.App/MainWindow.Detail.cs
+++ b/src/managed/Nota.App/MainWindow.Detail.cs
@@ -715,6 +715,7 @@ public partial class MainWindow
PollHeldNotes = buf => Engine.LiveHeldNotes(buf),
ExpressionOf = id => Engine.GetNoteExpression(id),
CreateExpression = pts => Engine.CreateNoteExpression(pts),
+ ArticulationMapOf = t => Nota.Application.Articulations.ArticulationMapAssignment.Read(Engine, t), // specs/085
// The controller lane edits the active clip (specs/063); a clip gone since is left alone.
ControllersInClip = () => Engine.GetMidiClipControllers(roll.ActiveClip.TrackId, roll.ActiveClip.ClipIndex),
GetController = ctl => Engine.GetMidiClipController(roll.ActiveClip.TrackId, roll.ActiveClip.ClipIndex, ctl),
@@ -1412,6 +1413,8 @@ public partial class MainWindow
PollHeldNotes = buf => Engine.LiveHeldNotes(buf),
ExpressionOf = id => Engine.GetNoteExpression(id),
CreateExpression = pts => Engine.CreateNoteExpression(pts),
+ // A Session slot keeps its notes' articulations; they play in the slot from T042 on (specs/085).
+ ArticulationMapOf = _ => Nota.Application.Articulations.ArticulationMapAssignment.Read(Engine, trackId),
ControllersInClip = () => Engine.GetSessionControllers(trackId, scene),
GetController = ctl => Engine.GetSessionController(trackId, scene, ctl),
SetController = (ctl, pts) =>
diff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.cs
index 073e6034..c158c16a 100644
--- a/src/managed/Nota.App/MainWindow.Menu.cs
+++ b/src/managed/Nota.App/MainWindow.Menu.cs
@@ -31,6 +31,13 @@ public partial class MainWindow
// Help ▸ Documentation: the user manual in the browser.
private void OnDocumentation(object? sender, EventArgs e) => NotaDocs.Open(this);
+ /// <summary>The articulation map manager (specs/085, T065), on the selected track's map.</summary>
+ public void ShowArticulationMaps()
+ {
+ if (_vm is null) return;
+ ArticulationMapManager.Open(this, Engine, () => Timeline.SelectedTrackId);
+ }
+
private void OnPreferences(object? sender, EventArgs e) => ShowPreferences();
public void ShowPreferences()
{
diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axaml
index 4080705b..3209e4d1 100644
--- a/src/managed/Nota.App/MainWindow.axaml
+++ b/src/managed/Nota.App/MainWindow.axaml
@@ -80,6 +80,7 @@
<NativeMenuItem Header="{app:T 'common.mixer'}" app:Commands.Id="view.mixer"/>
<NativeMenuItem Header="{app:T 'main.mixer_in_its_own_window'}" app:Commands.Id="view.mixerFloat" ToggleType="CheckBox"/>
<NativeMenuItem Header="{app:T 'main.connect_phone'}" app:Commands.Id="view.connectPhone"/>
+ <NativeMenuItem Header="{app:T 'main.articulation_maps'}" app:Commands.Id="view.articulationMaps"/>
<NativeMenuItemSeparator/>
<NativeMenuItem Header="{app:T 'main.toggle_browser'}" app:Commands.Id="view.toggleBrowser"/>
<NativeMenuItem Header="{app:T 'main.toggle_detail_panel'}" app:Commands.Id="view.toggleDetail"/>
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 8e9b763d..c32a080c 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -397,6 +397,10 @@ public partial class MainWindow : Window
PianoRollView.AuditionEnabled = vm.Settings.Current.PianoRollAudition;
PianoRollView.AuditionToggled -= OnAuditionToggled;
PianoRollView.AuditionToggled += OnAuditionToggled;
+ // …and whether notes take their articulation's colour (specs/085, FR-015).
+ PianoRollView.NoteColorByArticulation = vm.Settings.Current.PianoRollNoteColorByArticulation;
+ PianoRollView.NoteColorModeChanged -= OnNoteColorModeChanged;
+ PianoRollView.NoteColorModeChanged += OnNoteColorModeChanged;
PianoRollView.VelocityWheelReversed = vm.Settings.Current.PianoRollVelocityWheelReversed;
PianoRollView.VelocityWheelMultiplier = Nota.Application.Editing.VelocityWheel.ClampMultiplier(vm.Settings.Current.PianoRollVelocityWheelMultiplier);
// The piano roll's key labels (every note, not just C) persist the same way.
@@ -896,6 +900,13 @@ public partial class MainWindow : Window
private NativeMenuItem? _followMenuItem;
+ private void OnNoteColorModeChanged()
+ {
+ if (_vm is null) return;
+ _vm.Settings.Current.PianoRollNoteColorByArticulation = PianoRollView.NoteColorByArticulation;
+ _vm.Settings.Save();
+ }
+
private void OnAuditionToggled()
{
if (_vm is null) return;
diff --git a/src/managed/Nota.App/PianoRollView.Articulations.cs b/src/managed/Nota.App/PianoRollView.Articulations.cs
new file mode 100644
index 00000000..435946dc
--- /dev/null
+++ b/src/managed/Nota.App/PianoRollView.Articulations.cs
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Per-note articulations in the piano roll (specs/085, US2): right-click a note → Articulation →
+// one of the track's map. The choice goes on every selected note of that track (a chord, a
+// phrase, overlapping notes — each keeps its own id) as one undo step. Notes of reference clips
+// and of other tracks in a multi-track editor are left alone. Clear sets the note back to none,
+// which plays as the map's default.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Avalonia.Controls;
+using Nota.Application.Articulations;
+using Nota.Application.Localization;
+
+namespace Nota.App;
+
+public sealed partial class PianoRollView
+{
+ /// <summary>The articulation map of a track, or null when it has none. Set by the host.</summary>
+ public Func<int, ArticulationMap?>? ArticulationMapOf { get; set; }
+
+ // ---- note colour by articulation (US4, FR-015) ------------------------------------------
+
+ /// <summary>Notes take their articulation's colour instead of the track's. App-wide, like
+ /// <see cref="AuditionEnabled"/>: seeded from and saved to Settings by the host; off by default.</summary>
+ public static bool NoteColorByArticulation { get; set; }
+ /// <summary>Fired when a clip editor's colour chip flips <see cref="NoteColorByArticulation"/>.</summary>
+ public static event Action? NoteColorModeChanged;
+ public static void SetNoteColorByArticulation(bool on)
+ {
+ if (NoteColorByArticulation == on) return;
+ NoteColorByArticulation = on;
+ NoteColorModeChanged?.Invoke();
+ }
+
+ // Follow the switch while on screen only: a roll is rebuilt for every clip, so a lasting
+ // subscription would leak (as the keys column does with the label mode).
+ protected override void OnAttachedToVisualTree(Avalonia.VisualTreeAttachmentEventArgs e)
+ {
+ base.OnAttachedToVisualTree(e);
+ NoteColorModeChanged += Invalidate;
+ }
+
+ protected override void OnDetachedFromVisualTree(Avalonia.VisualTreeAttachmentEventArgs e)
+ {
+ NoteColorModeChanged -= Invalidate;
+ base.OnDetachedFromVisualTree(e);
+ }
+
+ /// <summary>Note i's articulation colour (its own, or the default it plays as), or null for the
+ /// track colour — no map, or an id the map doesn't hold (enabled) any more.</summary>
+ private Avalonia.Media.Color? ArticulationColourOf(int i)
+ {
+ if (i < 0 || i >= _notes.Count) return null;
+ var shown = ArticulationColours.Shown(CachedArticulationMap(TrackOfSlot(_owner[i])), _notes[i].ArticulationId);
+ return shown is null ? null : ArticulationImportPreview.ColourOf(shown);
+ }
+
+ // Drawing reads the map on every frame; reading and parsing it each time would cost a frame's
+ // worth of work. A track's map is fetched at most twice a second, and again at once after this
+ // roll changes it. An undo or another view changing it shows within that half second.
+ private readonly Dictionary<int, (long At, ArticulationMap? Map)> _artMaps = new();
+ private const long ArtMapRefreshMs = 500;
+
+ internal ArticulationMap? CachedArticulationMap(int track)
+ {
+ if (ArticulationMapOf is null || track <= 0) return null;
+ long now = Environment.TickCount64;
+ if (_artMaps.TryGetValue(track, out var c) && now - c.At < ArtMapRefreshMs) return c.Map;
+ var map = ArticulationMapOf(track);
+ _artMaps[track] = (now, map);
+ return map;
+ }
+
+ /// <summary>FR-014: a note whose articulation the track's map doesn't hold (deleted, or
+ /// disabled). It plays as the map's default; the roll marks it.</summary>
+ internal bool HasMissingArticulation(int i)
+ {
+ if (i < 0 || i >= _notes.Count || _notes[i].ArticulationId <= 0) return false;
+ var map = CachedArticulationMap(TrackOfSlot(_owner[i]));
+ return map is not null && map.Find(_notes[i].ArticulationId) is not { Enabled: true };
+ }
+
+ /// <summary>The notes a menu opened on <paramref name="hit"/> would change: the selection's
+ /// notes on the same track as the hit, in editable clips.</summary>
+ internal List<int> ArticulationTargets(int hit)
+ {
+ int track = TrackOfSlot(_owner[hit]);
+ var picked = _selection.Contains(hit) ? _selection.ToList() : new List<int> { hit };
+ return picked.Where(i => i >= 0 && i < _notes.Count && !IsLocked(i) && TrackOfSlot(_owner[i]) == track).OrderBy(i => i).ToList();
+ }
+
+ /// <summary>Sets the articulation of <paramref name="targets"/> to <paramref name="id"/> (0 = none)
+ /// as one undo step. False when nothing changed.</summary>
+ internal bool SetArticulation(IReadOnlyList<int> targets, int id)
+ {
+ bool changed = false;
+ foreach (int i in targets)
+ {
+ if (_notes[i].ArticulationId == id) continue;
+ var n = _notes[i]; // copy the note: its expression and everything else travel with it
+ n.ArticulationId = Math.Max(0, id);
+ _notes[i] = n;
+ changed = true;
+ }
+ if (!changed) return false;
+ Invalidate();
+ CommitNotes();
+ Changed?.Invoke();
+ return true;
+ }
+
+ internal void ShowArticulationMenu(Control anchor, int hit)
+ {
+ if (hit < 0 || hit >= _notes.Count) return;
+ var targets = ArticulationTargets(hit);
+ _artMaps.Remove(TrackOfSlot(_owner[hit])); // the menu shows the map as it is now
+ var map = CachedArticulationMap(TrackOfSlot(_owner[hit]));
+ var flyout = new MenuFlyout();
+ if (map is null || targets.Count == 0)
+ {
+ flyout.Items.Add(MenuKit.Item(map is null ? Loc.T("articulations.menu.no_map") : Loc.T("articulations.menu.locked"), enabled: false));
+ flyout.ShowAt(anchor, showAtPointer: true);
+ return;
+ }
+
+ var ids = targets.Select(i => _notes[i].ArticulationId).Distinct().ToList();
+ string current = ids.Count > 1 ? Loc.T("articulations.menu.mixed") : Label(map, ids[0]);
+ var sub = MenuKit.ValueItem(Loc.T("articulations.menu.articulation"), null, current);
+ foreach (var a in map.Articulations.Where(a => a.Enabled))
+ {
+ int id = a.Id;
+ var mi = MenuKit.Item(a.Name, click: () => SetArticulation(targets, id));
+ mi.ToggleType = MenuItemToggleType.Radio;
+ mi.IsChecked = ids.Count == 1 && ids[0] == id;
+ MenuKit.SetTrailing(mi, MenuKit.Swatch(ArticulationImportPreview.Swatch(a)));
+ sub.Items.Add(mi);
+ }
+ sub.Items.Add(new Separator());
+ // Notes whose id is gone from the map (or disabled) play the default: say so (FR-014).
+ bool missing = ids.Any(i => i > 0 && map.Find(i) is not { Enabled: true });
+ sub.Items.Add(MenuKit.Item(missing ? Loc.T("articulations.menu.clear_missing") : Loc.T("articulations.menu.clear"),
+ click: () => SetArticulation(targets, 0), enabled: ids.Any(i => i != 0)));
+ flyout.Items.Add(sub);
+ flyout.ShowAt(anchor, showAtPointer: true);
+ }
+
+ /// <summary>How a note's articulation reads: its name; none → the default's ("Default · Long");
+ /// an id the map doesn't hold (any more) → "Missing".</summary>
+ internal static string Label(ArticulationMap map, int id)
+ {
+ if (id > 0) return map.Find(id) is { Enabled: true } a ? a.Name : Loc.T("articulations.menu.missing");
+ return map.DefaultArticulationId is int d && map.Find(d) is { Enabled: true } def
+ ? Loc.F("articulations.menu.default_named", def.Name)
+ : Loc.T("articulations.menu.default");
+ }
+}
diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.cs
index ff82d6bf..4fd10eae 100644
--- a/src/managed/Nota.App/PianoRollView.cs
+++ b/src/managed/Nota.App/PianoRollView.cs
@@ -677,9 +677,12 @@ public sealed partial class PianoRollView : UserControl
/// <summary>Length of the active clip (the inspector's LENGTH / LOOP).</summary>
public double ActiveLengthBeats => _set.ActiveClip.LengthBeats;
- /// <summary>Track colour of note i's clip; the active colour for a one-clip set.</summary>
+ /// <summary>Note i's colour: its articulation's when notes are coloured by articulation and it
+ /// has one to show (specs/085, FR-015), else the track colour of its clip (the active colour for
+ /// a one-clip set). Selected, ghost and locked notes are drawn by their own branches.</summary>
private Color ColorOf(int i)
{
+ if (NoteColorByArticulation && ArticulationColourOf(i) is Color art) return art;
int s = i >= 0 && i < _owner.Count ? _owner[i] : 0;
return s < _slotBrushes.Count && _set.IsMulti ? _slotBrushes[s].Color : _trackColor;
}
@@ -1187,9 +1190,8 @@ public sealed partial class PianoRollView : UserControl
if (a.Count != b.Length) return false;
for (int i = 0; i < b.Length; i++)
{
- var x = a[i]; var y = b[i];
- if (x.Pitch != y.Pitch || x.StartBeat != y.StartBeat || x.LengthBeats != y.LengthBeats
- || x.Velocity != y.Velocity || x.ExprId != y.ExprId) return false;
+ // Every field, the articulation included (specs/085): an edit to any of them must reach the engine.
+ if (!NotaNote.Same(a[i], b[i])) return false;
}
return true;
}
@@ -2259,6 +2261,9 @@ public sealed partial class PianoRollView : UserControl
}
}
if (n.ExprId > 0 || _o._expr.Editing(i)) DrawExpression(ctx, i, n, r, sel, ppb);
+ // FR-014: an articulation the map no longer holds — a warning notch at the note's start.
+ if (n.ArticulationId > 0 && _o.HasMissingArticulation(i))
+ ctx.FillRectangle(NotaPalette.Warning, new Rect(r.X, r.Y, Math.Min(3, r.Width), r.Height), 1);
// Resize-edge affordance: a bright bar on the edge a drag would trim.
bool edgeHi = ((_drag == Mode.Resize || _drag == Mode.ResizeLeft || (_drag == Mode.Place && _placeKind == PlaceDragKind.Length)) && sel)
|| (_drag == Mode.None && _hoverNote == i && !_o.IsLocked(i));
@@ -2385,6 +2390,20 @@ public sealed partial class PianoRollView : UserControl
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
Focus();
+ // Right-click a note: its articulation (specs/085). The selection stays when the note is
+ // in it (a chord, a phrase), else the note alone is selected first.
+ if (e.GetCurrentPoint(this).Properties.IsRightButtonPressed && _drag == Mode.None)
+ {
+ int rhit = HitTest(e.GetPosition(this), out _);
+ if (rhit < 0) return;
+ // A pending paste / drawn note lands first (settling can cut or remove notes): hit again.
+ if (!_o._selection.Contains(rhit) && _o.SettlePlacement()) rhit = HitTest(e.GetPosition(this), out _);
+ if (rhit < 0) return;
+ if (!_o._selection.Contains(rhit)) { _o._selection.Clear(); _o._selection.Add(rhit); _o.Invalidate(); _o.Changed?.Invoke(); }
+ _o.ShowArticulationMenu(this, rhit);
+ e.Handled = true;
+ return;
+ }
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
_o.EndVelocityWheel(); // a press starts a new edit: close the wheel's burst first
var p = e.GetPosition(this);
@@ -2673,7 +2692,11 @@ public sealed partial class PianoRollView : UserControl
int hn = kind == 1 ? hit : -1; // the bright trim-edge affordance shows only on the edge
bool left = edge < 0;
if (hn != _hoverNote || left != _hoverLeft) { _hoverNote = hn; _hoverLeft = left; _o.Invalidate(); }
+ // FR-014: say why a note carries the warning notch.
+ object? tip = hit >= 0 && _o.HasMissingArticulation(hit) ? MissingArticulationTip : null;
+ if (!Equals(ToolTip.GetTip(this), tip)) ToolTip.SetTip(this, tip);
}
+ private static readonly string MissingArticulationTip = Loc.T("articulations.menu.missing_tip");
// Whatever ends the press (release, a window losing the pointer) ends its note.
protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
diff --git a/src/managed/Nota.App/TrackInspectorView.cs b/src/managed/Nota.App/TrackInspectorView.cs
index b5b0024e..5c59c7a1 100644
--- a/src/managed/Nota.App/TrackInspectorView.cs
+++ b/src/managed/Nota.App/TrackInspectorView.cs
@@ -20,8 +20,10 @@ using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
+using Avalonia.Platform.Storage;
using Avalonia.Threading;
using Nota.Application;
+using Nota.Application.Articulations;
using Nota.Application.Localization;
namespace Nota.App;
@@ -41,6 +43,7 @@ internal sealed class TrackInspectorView : UserControl
private int _trackId = -1;
private string _shown = "";
private TextBox? _nameBox;
+ private TextBox? _offsetBox; // the MIDI offset being typed (specs/085) must survive the poll too
public TrackInspectorView(IAudioEngine engine, ArrangementView timeline, Func<int, IReadOnlyList<FreezeEntry>> freezeEntries,
Func<bool> engineSuspended)
@@ -82,7 +85,7 @@ internal sealed class TrackInspectorView : UserControl
if (_engineSuspended()) return;
// A folded browser keeps the tab attached but hidden; a name being typed must not be
// swept away by a rebuild.
- if (!IsEffectivelyVisible || _nameBox?.IsFocused == true) return;
+ if (!IsEffectivelyVisible || _nameBox?.IsFocused == true || _offsetBox?.IsFocused == true) return;
if (Snapshot() != _shown) Rebuild();
}
@@ -125,6 +128,10 @@ internal sealed class TrackInspectorView : UserControl
if (src > 0) sb.Append(TrackNames.Of(_engine, src));
foreach (var c in _timeline.MidiSourceChoices(id))
sb.Append('|').Append(c.Id).Append('=').Append(c.Name);
+ // The articulation map (specs/085): an undo, the MCP or another view can change it.
+ var map = _engine.GetTrackArticulationMapJson(id);
+ sb.Append("|art:").Append(map?.Length ?? -1).Append(':').Append(map?.GetHashCode() ?? 0)
+ .Append("|off:").Append(_engine.GetTrackMidiOffsetMs(id));
}
foreach (var f in _freezeEntries(id)) sb.Append('|').Append(f.Label).Append(f.Switch);
return sb.ToString();
@@ -135,6 +142,7 @@ internal sealed class TrackInspectorView : UserControl
if (_engineSuspended()) return;
_shown = Snapshot();
_nameBox = null;
+ _offsetBox = null;
var s = new StackPanel { Spacing = 18, Margin = new Thickness(12, 12, 12, 16) };
if (IsMaster) BuildMaster(s);
else if (_trackId > 0 && TryInfo(out var ti)) BuildTrack(s, ti);
@@ -183,6 +191,7 @@ internal sealed class TrackInspectorView : UserControl
if (audio) s.Children.Add(Section(Loc.T("common.input"), InputRows(id)));
if (ti.IsInstrument) s.Children.Add(Section(Loc.T("common.input"), MidiFromRow(id)));
+ if (ti.IsInstrument) s.Children.Add(Section(Loc.T("articulations.inspector.head"), ArticulationsBody(id)));
s.Children.Add(Section(Loc.T("track_inspector.color"), Swatches(id)));
@@ -263,6 +272,169 @@ internal sealed class TrackInspectorView : UserControl
return SessionView.Row(Loc.T("track_inspector.midi_from"), chip);
}
+ // ---- articulations (specs/085, US1) -------------------------------------------------------
+
+ private static IArticulationLibrary? Library => App.Services?.GetService(typeof(IArticulationLibrary)) as IArticulationLibrary;
+
+ // The track's map (name and size, a pick from the library), Import… and Remove. Files dropped
+ // from Explorer onto the section import like the picker does: decided by content, previewed first.
+ private Control ArticulationsBody(int id)
+ {
+ var map = ArticulationMapAssignment.Read(_engine, id);
+ var rows = new StackPanel { Spacing = 8 };
+
+ var lib = Library;
+ var saved = lib?.List() ?? (IReadOnlyList<ArticulationMap>)Array.Empty<ArticulationMap>();
+ var choices = new List<(string Id, string Name)> { ("", Loc.T("common.none")) };
+ choices.AddRange(saved.Select(m => (m.Id, m.Name)));
+ if (map is not null && saved.All(m => m.Id != map.Id)) choices.Insert(1, (map.Id, map.Name)); // the project's own copy
+ var chip = SessionView.Chip(map?.Name ?? Loc.T("common.none"), false, a =>
+ SessionView.Pick(a, choices, v => v == (map?.Id ?? ""), v =>
+ {
+ if (v.Length == 0) { if (map is not null) _engine.ClearTrackArticulationMap(id); }
+ else if (v != map?.Id && lib?.Get(v) is { } chosen) ArticulationMapAssignment.Assign(_engine, id, chosen);
+ Edited();
+ }));
+ ToolTip.SetTip(chip, Loc.T("articulations.inspector.map_tip"));
+ rows.Children.Add(SessionView.Row(Loc.T("articulations.inspector.map"), chip));
+ if (map is not null) rows.Children.Add(Note(ArticulationText.Count(map)));
+ rows.Children.Add(SessionView.Row(Loc.T("articulations.inspector.midi_offset"), MidiOffsetBox(id)));
+ // FR-018: what each articulation with an offset of its own adds up to on this track.
+ if (map is not null)
+ {
+ double trackMs = _engine.GetTrackMidiOffsetMs(id);
+ foreach (var (name, total) in ArticulationText.EffectiveOffsets(map, trackMs))
+ rows.Children.Add(Note(Loc.F("articulations.inspector.effective", name, OffsetText(total), OffsetText(trackMs), OffsetText(total - trackMs))));
+ }
+
+ var import = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Content = Loc.T("articulations.inspector.import") };
+ ToolTip.SetTip(import, Loc.T("articulations.inspector.import_tip"));
+ import.Click += async (_, _) => await PickAndImport(id);
+ var buttons = new WrapPanel { Orientation = Orientation.Horizontal, Children = { import } };
+ var manage = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(6, 0, 0, 0), Content = Loc.T("articulations.inspector.edit_maps") };
+ ToolTip.SetTip(manage, Loc.T("articulations.inspector.edit_maps_tip"));
+ manage.Click += (_, _) =>
+ ((Avalonia.Application.Current?.ApplicationLifetime as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime)?.MainWindow as MainWindow)?.ShowArticulationMaps();
+ buttons.Children.Add(manage);
+ if (map is not null)
+ {
+ var remove = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(6, 0, 0, 0), Content = Loc.T("articulations.inspector.remove") };
+ ToolTip.SetTip(remove, Loc.T("articulations.inspector.remove_tip"));
+ remove.Click += (_, _) => { _engine.ClearTrackArticulationMap(id); Edited(); };
+ buttons.Children.Add(remove);
+ }
+ rows.Children.Add(buttons);
+ rows.Children.Add(Note(Loc.T("articulations.inspector.drop_hint")));
+
+ var host = new Border
+ {
+ Child = rows, Padding = new Thickness(6), Margin = new Thickness(-6), CornerRadius = NotaRadius.Control,
+ BorderThickness = new Thickness(1), BorderBrush = Brushes.Transparent, Background = Brushes.Transparent,
+ };
+ HookArticulationDrop(host, id);
+ return host;
+ }
+
+ // The track's MIDI playback offset (specs/085, T052): typed in milliseconds ("−80", "-80 ms",
+ // "−0.08 s"), shown in the display culture. Enter or leaving the box sets it (one undo step);
+ // Esc puts it back; text that isn't a time is ignored.
+ private const double OffsetRangeMs = 2000;
+ private static string OffsetText(double ms) => NotaNum.Unit(Math.Round(ms), "0", "ms");
+
+ private Control MidiOffsetBox(int id)
+ {
+ double cur = _engine.GetTrackMidiOffsetMs(id);
+ string shown = OffsetText(cur);
+ var box = new TextBox
+ {
+ Text = shown, FontSize = 11, Height = NotaSize.Shell, MinHeight = 0, Width = 96,
+ VerticalContentAlignment = VerticalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Right,
+ };
+ ToolTip.SetTip(box, Loc.T("articulations.inspector.midi_offset_tip"));
+ void Commit()
+ {
+ string text = (box.Text ?? "").Trim();
+ if (text == shown) return;
+ double? pos = ValueText.Solve(text, shown, p => OffsetText(-OffsetRangeMs + 2 * OffsetRangeMs * p));
+ if (pos is not double p) { box.Text = shown; return; }
+ double ms = Math.Round(-OffsetRangeMs + 2 * OffsetRangeMs * p);
+ Dispatcher.UIThread.Post(() => // after a rebuild that dropped the box has finished, like the name
+ {
+ if (ms != cur) _engine.SetTrackMidiOffsetMs(id, ms);
+ Edited();
+ });
+ }
+ box.KeyDown += (_, e) =>
+ {
+ if (e.Key is not (Key.Enter or Key.Escape)) return;
+ if (e.Key == Key.Escape) box.Text = shown;
+ e.Handled = true;
+ TopLevel.GetTopLevel(box)?.FocusManager?.Focus(null);
+ };
+ box.LostFocus += (_, _) => Commit();
+ _offsetBox = box;
+ return box;
+ }
+
+ private async System.Threading.Tasks.Task PickAndImport(int id)
+ {
+ if (TopLevel.GetTopLevel(this) is not { } top) return;
+ var files = await top.PickFilesAsync(new FilePickerOpenOptions
+ {
+ Title = Loc.T("articulations.preview.title"),
+ AllowMultiple = false,
+ FileTypeFilter = new[]
+ {
+ new FilePickerFileType(Loc.T("articulations.inspector.file_type")) { Patterns = ArticulationImport.PickerExtensions.Select(x => "*" + x).ToArray() },
+ new FilePickerFileType(Loc.T("articulations.inspector.all_files")) { Patterns = new[] { "*" } },
+ },
+ });
+ if (files.Count > 0 && files[0].TryGetLocalPath() is { Length: > 0 } path) await ImportFromFile(id, path);
+ }
+
+ // Import → preview → (accepted) keep in the library and give the track. The file is only read.
+ private async System.Threading.Tasks.Task ImportFromFile(int id, string path)
+ {
+ if (TopLevel.GetTopLevel(this) is not Window owner) return;
+ var result = ArticulationImport.ImportFile(path);
+ bool ok = await new ArticulationImportPreview(System.IO.Path.GetFileName(path), result).ShowDialog<bool>(owner);
+ if (!ok || result.Map is not { } map) return;
+ try { Library?.Save(map); }
+ catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ // Still assign it: the project keeps its own copy. Say the library didn't take it.
+ await new ConfirmWindow(Loc.T("articulations.preview.title"), Loc.F("articulations.inspector.library_failed", ex.Message), Loc.T("common.close"), null).ShowDialog<bool>(owner);
+ }
+ if (!ArticulationMapAssignment.Assign(_engine, id, map))
+ await new ConfirmWindow(Loc.T("articulations.preview.title"), Loc.T("articulations.inspector.assign_failed"), Loc.T("common.close"), null).ShowDialog<bool>(owner);
+ Edited();
+ }
+
+ // Explorer → section. A drag is accepted on sight (reading files at drag-over would stall the
+ // pointer); the drop takes the first file and decides by its content, like the picker.
+ private void HookArticulationDrop(Border target, int id)
+ {
+ DragDrop.SetAllowDrop(target, true);
+ void Glow(bool on) => target.BorderBrush = on ? NotaPalette.Accent : Brushes.Transparent;
+ DragDrop.AddDragOverHandler(target, (_, e) =>
+ {
+ if (BrowserView.CurrentDrag is not null || !BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.None; return; }
+ e.DragEffects = DragDropEffects.Copy;
+ e.Handled = true;
+ Glow(true);
+ });
+ DragDrop.AddDragLeaveHandler(target, (_, _) => Glow(false));
+ DragDrop.AddDropHandler(target, (_, e) =>
+ {
+ Glow(false);
+ if (BrowserView.CurrentDrag is not null) return;
+ var file = BrowserView.ExternalPaths(e).FirstOrDefault(System.IO.File.Exists);
+ if (file is null) return;
+ e.Handled = true;
+ Dispatcher.UIThread.Post(() => _ = ImportFromFile(id, file)); // after the drop returns: the dialog is modal
+ });
+ }
+
// The track palette — each base in its normal, light and dark shade — and Auto, the
// stored colour ringed, as in the track menu.
private Control Swatches(int id)
diff --git a/src/managed/Nota.Application/Articulations/ArticulationColours.cs b/src/managed/Nota.Application/Articulations/ArticulationColours.cs
new file mode 100644
index 00000000..3b9c10b1
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationColours.cs
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Which colour a note shows when the piano roll colours notes by articulation (specs/085, US4,
+// FR-015). Pure, so the smoke test checks it: a note shows the articulation it plays — its own, or
+// the map's default when it has none. A note whose articulation the map no longer holds (or holds
+// disabled) plays the default but keeps the track colour, so it doesn't pass for a default note;
+// the roll's missing mark says why (FR-014). The view turns the answer into a colour: the
+// articulation's own RGB, else Nota's palette slot for it — never a guess at Cubase's palette.
+
+namespace Nota.Application.Articulations;
+
+public static class ArticulationColours
+{
+ /// <summary>The articulation whose colour a note with <paramref name="articulationId"/> shows,
+ /// or null for the track colour (no map, a missing or disabled id, or no default to play).</summary>
+ public static Articulation? Shown(ArticulationMap? map, int articulationId)
+ {
+ if (map is null) return null;
+ if (articulationId > 0) return map.Find(articulationId) is { Enabled: true } a ? a : null;
+ return map.DefaultArticulationId is int d && map.Find(d) is { Enabled: true } def ? def : null;
+ }
+
+ /// <summary>The palette base (0 … <paramref name="bases"/> − 1) for an articulation without a
+ /// colour of its own: the source file's palette index when it gave one (Cubase), else its id —
+ /// stable, so a note keeps its colour when the map is reordered.</summary>
+ public static int PaletteSlot(Articulation a, int bases)
+ {
+ if (bases <= 0) return 0;
+ int k = a.SourceColorIndex ?? a.Id;
+ return (k % bases + bases) % bases;
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationImport.cs b/src/managed/Nota.Application/Articulations/ArticulationImport.cs
new file mode 100644
index 00000000..49d47bcc
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationImport.cs
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// One entry point for every articulation map file (specs/085, FR-006): the importer is chosen by
+// what the file contains, never by its extension, so a renamed file still imports and a file that
+// merely carries a map's extension is refused. Formats Nota has not verified against a real file
+// (Studio One .soundvariation) are refused with a message, not guessed.
+
+using Nota.Application.Localization;
+
+namespace Nota.Application.Articulations;
+
+public enum ArticulationFileKind { Unknown, NotaMap, CubaseExpressionMap, StudioOneKeySwitchList }
+
+public static class ArticulationImport
+{
+ /// <summary>Extensions offered in the file picker. Matching one decides nothing: content does.</summary>
+ public static readonly string[] PickerExtensions = { ".expressionmap", ".keyswitch", ArticulationMapFile.Extension };
+
+ /// <summary>What the file is, by its content.</summary>
+ public static ArticulationFileKind Detect(string path)
+ {
+ if (ArticulationMapFile.Sniff(path)) return ArticulationFileKind.NotaMap;
+ if (ExpressionMapImporter.Sniff(path)) return ArticulationFileKind.CubaseExpressionMap;
+ if (KeySwitchListImporter.Sniff(path)) return ArticulationFileKind.StudioOneKeySwitchList;
+ return ArticulationFileKind.Unknown;
+ }
+
+ /// <summary>Imports <paramref name="path"/> with the importer its content calls for. The source
+ /// file is only read. An unknown or unsupported file returns an error and no map.</summary>
+ public static ArticulationImportResult ImportFile(string path)
+ {
+ if (!File.Exists(path))
+ {
+ var missing = new ArticulationImportResult();
+ missing.Error(Loc.F("articulations.import.file_not_found", path));
+ return missing;
+ }
+ switch (Detect(path))
+ {
+ case ArticulationFileKind.NotaMap: return ArticulationMapFile.ReadFile(path);
+ case ArticulationFileKind.CubaseExpressionMap: return ExpressionMapImporter.ImportFile(path);
+ case ArticulationFileKind.StudioOneKeySwitchList: return KeySwitchListImporter.ImportFile(path);
+ }
+ var res = new ArticulationImportResult();
+ res.Error(Path.GetExtension(path).Equals(".soundvariation", StringComparison.OrdinalIgnoreCase)
+ ? Loc.T("articulations.import.soundvariation_unsupported")
+ : Loc.T("articulations.import.unknown_format"));
+ return res;
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationMap.cs b/src/managed/Nota.Application/Articulations/ArticulationMap.cs
new file mode 100644
index 00000000..cc45a519
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationMap.cs
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Articulation maps: the named playing techniques of a sample library (Long, Staccato, Legato…),
+// each with the MIDI the library wants to switch to it and the timing it needs. A pure model —
+// no engine, no UI — so importers, the manager, the scheduler's inputs and persistence all share it.
+
+namespace Nota.Application.Articulations;
+
+/// <summary>What one MIDI action sends. Bank Select is a controller change on CC 0 / CC 32 but is
+/// kept apart so ordering (MSB, LSB, then Program Change) is explicit.</summary>
+public enum MidiActionKind
+{
+ /// <summary>A keyswitch note: Data1 = pitch, Data2 = velocity.</summary>
+ Keyswitch,
+ /// <summary>A controller change: Data1 = CC number, Data2 = value.</summary>
+ ControlChange,
+ /// <summary>A program change: Data1 = program.</summary>
+ ProgramChange,
+ /// <summary>Bank Select MSB (CC 0): Data2 = value.</summary>
+ BankSelectMsb,
+ /// <summary>Bank Select LSB (CC 32): Data2 = value.</summary>
+ BankSelectLsb,
+}
+
+/// <summary>How an articulation's trigger behaves after it is sent.</summary>
+public enum TriggerMode
+{
+ /// <summary>The switch is sent once and stays in force until another articulation replaces it
+ /// (a keyswitch is released shortly after it is pressed).</summary>
+ Latching,
+ /// <summary>The switch is held for as long as the note sounds and released with it.</summary>
+ Momentary,
+}
+
+/// <summary>One thing sent to the instrument to select an articulation. Actions run in list order.</summary>
+public sealed class MidiAction
+{
+ public MidiActionKind Kind { get; set; }
+ /// <summary>1..16, or null to use the channel of the note the articulation is applied to.</summary>
+ public int? Channel { get; set; }
+ public int Data1 { get; set; }
+ public int Data2 { get; set; }
+
+ public MidiAction Clone() => (MidiAction)MemberwiseClone();
+
+ /// <summary>True when the values are legal MIDI for <see cref="Kind"/>.</summary>
+ public bool IsValid() =>
+ (Channel is null || Channel is >= 1 and <= 16)
+ && Kind switch
+ {
+ MidiActionKind.Keyswitch or MidiActionKind.ControlChange => Data1 is >= 0 and <= 127 && Data2 is >= 0 and <= 127,
+ MidiActionKind.ProgramChange => Data1 is >= 0 and <= 127,
+ MidiActionKind.BankSelectMsb or MidiActionKind.BankSelectLsb => Data2 is >= 0 and <= 127,
+ _ => false,
+ };
+}
+
+/// <summary>A named set of mutually exclusive articulations (e.g. "Attribute" vs "Direction").</summary>
+public sealed class ArticulationGroup
+{
+ /// <summary>Stable within the map; 0 is reserved for "no group".</summary>
+ public int Id { get; set; }
+ public string Name { get; set; } = "";
+}
+
+public sealed class Articulation
+{
+ /// <summary>Stable within the map and never reused; this is what notes store. Always &gt; 0.</summary>
+ public int Id { get; set; }
+ public string Name { get; set; } = "";
+ public string ShortName { get; set; } = "";
+ /// <summary>Colour as 0xAARRGGBB, or null for "use the default for this slot".</summary>
+ public uint? ColorArgb { get; set; }
+ /// <summary>The source file's palette index when it gave one instead of an RGB value (Cubase).
+ /// Kept so nothing is lost; the colour a user sees is <see cref="ColorArgb"/> or Nota's own
+ /// default for the index, never a guess at the source application's palette.</summary>
+ public int? SourceColorIndex { get; set; }
+ /// <summary>0 = ungrouped, otherwise an <see cref="ArticulationGroup.Id"/>.</summary>
+ public int GroupId { get; set; }
+ public TriggerMode Trigger { get; set; } = TriggerMode.Latching;
+ /// <summary>Ordered MIDI actions that select this articulation.</summary>
+ public List<MidiAction> Actions { get; set; } = new();
+ /// <summary>Added to the track's MIDI offset for notes with this articulation (ms, negative = earlier).</summary>
+ public double NoteOffsetMs { get; set; }
+ /// <summary>How long before the (offset) note the actions are sent (ms, ≥ 0). Moves only the
+ /// trigger, never the note.</summary>
+ public double TriggerLeadMs { get; set; }
+ public bool Enabled { get; set; } = true;
+ /// <summary>Source details with no model field of their own (descriptions, original ids,
+ /// unsupported constructs), preserved for the manager and for export.</summary>
+ public Dictionary<string, string> Metadata { get; set; } = new();
+
+ public Articulation Clone()
+ {
+ var c = (Articulation)MemberwiseClone();
+ c.Actions = Actions.Select(a => a.Clone()).ToList();
+ c.Metadata = new Dictionary<string, string>(Metadata);
+ return c;
+ }
+}
+
+public sealed class ArticulationMap
+{
+ /// <summary>Version of the serialized form of this model.</summary>
+ public const int CurrentVersion = 1;
+
+ /// <summary>Stable across rename, duplicate-as-new and export.</summary>
+ public string Id { get; set; } = Guid.NewGuid().ToString("N");
+ public string Name { get; set; } = "";
+ public string InstrumentName { get; set; } = "";
+ public string? Description { get; set; }
+ public int Version { get; set; } = CurrentVersion;
+ /// <summary>The articulation notes without one play as; null = the library's own state.</summary>
+ public int? DefaultArticulationId { get; set; }
+ public List<ArticulationGroup> Groups { get; set; } = new();
+ public List<Articulation> Articulations { get; set; } = new();
+ /// <summary>Where it came from ("expressionmap", "soundvariation", "nota") and the file name.</summary>
+ public Dictionary<string, string> Metadata { get; set; } = new();
+
+ public Articulation? Find(int id) => id > 0 ? Articulations.FirstOrDefault(a => a.Id == id) : null;
+
+ /// <summary>The next unused articulation id (never reuses one, even after a delete).</summary>
+ public int NextArticulationId() => Articulations.Count == 0 ? 1 : Articulations.Max(a => a.Id) + 1;
+
+ /// <summary>A deep copy with a new map id and, optionally, a new name — articulation ids are
+ /// kept, so notes written for the original still resolve.</summary>
+ public ArticulationMap DuplicateAs(string name)
+ {
+ return new ArticulationMap
+ {
+ Id = Guid.NewGuid().ToString("N"),
+ Name = name,
+ InstrumentName = InstrumentName,
+ Description = Description,
+ Version = Version,
+ DefaultArticulationId = DefaultArticulationId,
+ Groups = Groups.Select(g => new ArticulationGroup { Id = g.Id, Name = g.Name }).ToList(),
+ Articulations = Articulations.Select(a => a.Clone()).ToList(),
+ Metadata = new Dictionary<string, string>(Metadata),
+ };
+ }
+}
+
+public enum ImportSeverity { Info, Warning, Error }
+
+public sealed record ImportMessage(ImportSeverity Severity, string Text);
+
+/// <summary>What an importer did: the map when the file was usable, and everything it could not
+/// carry over — nothing is dropped without a message.</summary>
+public sealed class ArticulationImportResult
+{
+ public ArticulationMap? Map { get; set; }
+ public List<ImportMessage> Messages { get; } = new();
+ public bool Succeeded => Map is not null;
+ public IEnumerable<ImportMessage> Warnings => Messages.Where(m => m.Severity != ImportSeverity.Info);
+
+ public void Info(string text) => Messages.Add(new ImportMessage(ImportSeverity.Info, text));
+ public void Warn(string text) => Messages.Add(new ImportMessage(ImportSeverity.Warning, text));
+ public void Error(string text) => Messages.Add(new ImportMessage(ImportSeverity.Error, text));
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationMapCompiler.cs b/src/managed/Nota.Application/Articulations/ArticulationMapCompiler.cs
new file mode 100644
index 00000000..58d07669
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationMapCompiler.cs
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// An articulation map → the flat table the engine schedules from (specs/085, contracts/c-abi.md):
+// articulations sorted by id, each pointing at its ordered actions in one array. Disabled
+// articulations are left out, so a note that asks for one plays the default. The engine
+// validates the table again; this only shapes it.
+
+namespace Nota.Application.Articulations;
+
+public sealed record CompiledArticulationMap(int DefaultId, NotaArticulationEntry[] Entries, NotaArticulationAction[] Actions);
+
+public static class ArticulationMapCompiler
+{
+ public const double MaxOffsetMs = 2000, MaxLeadMs = 2000;
+
+ public static CompiledArticulationMap Compile(ArticulationMap map)
+ {
+ var entries = new List<NotaArticulationEntry>();
+ var actions = new List<NotaArticulationAction>();
+ var seen = new HashSet<int>();
+ foreach (var a in map.Articulations.Where(a => a.Enabled && a.Id > 0).OrderBy(a => a.Id))
+ {
+ if (!seen.Add(a.Id)) continue; // a repeated id: the first one wins (the file reader repairs these)
+ int start = actions.Count;
+ foreach (var act in a.Actions)
+ {
+ if (!act.IsValid()) continue;
+ actions.Add(new NotaArticulationAction
+ {
+ Kind = (int)act.Kind,
+ Channel = act.Channel ?? 0,
+ Data1 = act.Kind is MidiActionKind.BankSelectMsb ? 0 : act.Kind is MidiActionKind.BankSelectLsb ? 32 : act.Data1,
+ Data2 = act.Kind is MidiActionKind.ProgramChange ? 0 : act.Data2,
+ });
+ }
+ entries.Add(new NotaArticulationEntry
+ {
+ Id = a.Id,
+ TriggerMode = a.Trigger == TriggerMode.Momentary ? 1 : 0,
+ OffsetMs = Finite(a.NoteOffsetMs, -MaxOffsetMs, MaxOffsetMs),
+ LeadMs = Finite(a.TriggerLeadMs, 0, MaxLeadMs),
+ ActionStart = start,
+ ActionCount = actions.Count - start,
+ });
+ }
+ int def = map.DefaultArticulationId is int d && entries.Any(e => e.Id == d) ? d : 0;
+ return new CompiledArticulationMap(def, entries.ToArray(), actions.ToArray());
+ }
+
+ private static double Finite(double v, double lo, double hi) => double.IsFinite(v) ? Math.Clamp(v, lo, hi) : 0;
+}
+
+/// <summary>Putting a map on a track and reading it back: compile, serialise, hand both to the engine.</summary>
+public static class ArticulationMapAssignment
+{
+ /// <summary>One undo step. False when the engine refuses (no such instrument track).</summary>
+ public static bool Assign(IAudioEngine engine, int trackId, ArticulationMap map)
+ {
+ var c = ArticulationMapCompiler.Compile(map);
+ return engine.SetTrackArticulationMap(trackId, c.DefaultId, c.Entries, c.Actions, ArticulationMapFile.Write(map));
+ }
+
+ /// <summary>The track's map, or null when it has none (or what it holds can't be read).</summary>
+ public static ArticulationMap? Read(IAudioEngine engine, int trackId)
+ {
+ var json = engine.GetTrackArticulationMapJson(trackId);
+ return json is null ? null : ArticulationMapFile.Read(json, "").Map;
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationMapEdits.cs b/src/managed/Nota.Application/Articulations/ArticulationMapEdits.cs
new file mode 100644
index 00000000..fe40a7b0
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationMapEdits.cs
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Editing an articulation map (specs/085, US5) — the rules the manager window follows, kept here so
+// the smoke test checks them: ids are never reused (notes point at them), removing the default
+// clears it, actions keep their send order, and a map is checked before it is saved.
+
+using System.Globalization;
+
+namespace Nota.Application.Articulations;
+
+public static class ArticulationMapEdits
+{
+ /// <summary>A new articulation at the end, with the next unused id; its id.</summary>
+ public static int Add(ArticulationMap map, string name)
+ {
+ int id = NextId(map);
+ map.Articulations.Add(new Articulation { Id = id, Name = name, ShortName = ShortOf(name) });
+ return id;
+ }
+
+ /// <summary>A copy of articulation <paramref name="id"/> right after it, with a new id; its id, or 0.</summary>
+ public static int Copy(ArticulationMap map, int id, string name)
+ {
+ int k = map.Articulations.FindIndex(a => a.Id == id);
+ if (k < 0) return 0;
+ var c = map.Articulations[k].Clone();
+ c.Id = NextId(map);
+ c.Name = name;
+ c.ShortName = ShortOf(name);
+ map.Articulations.Insert(k + 1, c);
+ return c.Id;
+ }
+
+ /// <summary>Removes articulation <paramref name="id"/>. Notes that used it keep the id and play the
+ /// default; the id is remembered in the map's metadata so it is never given to another
+ /// articulation (see <see cref="NextId"/>). A removed default leaves the map without one.</summary>
+ public static bool Remove(ArticulationMap map, int id)
+ {
+ int n = map.Articulations.RemoveAll(a => a.Id == id);
+ if (n > 0 && map.DefaultArticulationId == id) map.DefaultArticulationId = null;
+ if (n > 0) map.Metadata["nota.retiredIds"] = RetiredWith(map, id);
+ return n > 0;
+ }
+
+ /// <summary>Moves articulation <paramref name="id"/> by <paramref name="delta"/> places (clamped).</summary>
+ public static bool Move(ArticulationMap map, int id, int delta)
+ {
+ int k = map.Articulations.FindIndex(a => a.Id == id);
+ if (k < 0) return false;
+ int to = Math.Clamp(k + delta, 0, map.Articulations.Count - 1);
+ if (to == k) return false;
+ var a = map.Articulations[k];
+ map.Articulations.RemoveAt(k);
+ map.Articulations.Insert(to, a);
+ return true;
+ }
+
+ public static bool MoveAction(Articulation art, int index, int delta)
+ {
+ if (index < 0 || index >= art.Actions.Count) return false;
+ int to = Math.Clamp(index + delta, 0, art.Actions.Count - 1);
+ if (to == index) return false;
+ var x = art.Actions[index];
+ art.Actions.RemoveAt(index);
+ art.Actions.Insert(to, x);
+ return true;
+ }
+
+ /// <summary>The next id for a new articulation: above every id the map has, and every id it has
+ /// ever removed (kept in metadata) — so a note pointing at a removed id never comes back to life
+ /// as a different articulation.</summary>
+ public static int NextId(ArticulationMap map) => Math.Max(map.NextArticulationId(), Retired(map).DefaultIfEmpty(0).Max() + 1);
+
+ private static IEnumerable<int> Retired(ArticulationMap map) =>
+ map.Metadata.TryGetValue("nota.retiredIds", out var s)
+ ? s.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => int.TryParse(x, NumberStyles.None, CultureInfo.InvariantCulture, out int v) ? v : 0).Where(v => v > 0)
+ : Enumerable.Empty<int>();
+
+ private static string RetiredWith(ArticulationMap map, int id) =>
+ string.Join(",", Retired(map).Append(id).Distinct().OrderBy(v => v).Select(v => v.ToString(CultureInfo.InvariantCulture)));
+
+ /// <summary>The name shortened for a lane label: the name itself up to 6 characters, else its first 6.</summary>
+ public static string ShortOf(string name) => name.Length <= 6 ? name : name[..6];
+
+ public enum Problem { NoName, ArticulationWithoutName, DuplicateId, InvalidAction, DefaultMissing }
+
+ /// <summary>What would stop a map from being saved as it is. Empty = fine.</summary>
+ public static List<(Problem Problem, string Subject)> Check(ArticulationMap map)
+ {
+ var p = new List<(Problem, string)>();
+ if (string.IsNullOrWhiteSpace(map.Name)) p.Add((Problem.NoName, ""));
+ var seen = new HashSet<int>();
+ foreach (var a in map.Articulations)
+ {
+ if (string.IsNullOrWhiteSpace(a.Name)) p.Add((Problem.ArticulationWithoutName, "#" + a.Id.ToString(CultureInfo.InvariantCulture)));
+ if (a.Id <= 0 || !seen.Add(a.Id)) p.Add((Problem.DuplicateId, a.Name));
+ if (a.Actions.Any(x => !x.IsValid())) p.Add((Problem.InvalidAction, a.Name));
+ }
+ if (map.DefaultArticulationId is int d && map.Find(d) is null) p.Add((Problem.DefaultMissing, ""));
+ return p;
+ }
+
+ /// <summary>A MIDI data value typed by the user: a number 0..127 or, for a keyswitch, a note name
+ /// in Nota's naming (60 = C4; "C#1", "Db1", "c1" all read). Null when it isn't one.</summary>
+ public static int? ParseMidiValue(string text, bool noteNames)
+ {
+ var t = text.Trim();
+ if (int.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) return n is >= 0 and <= 127 ? n : null;
+ if (!noteNames || t.Length < 2) return null;
+ int pc = char.ToUpperInvariant(t[0]) switch { 'C' => 0, 'D' => 2, 'E' => 4, 'F' => 5, 'G' => 7, 'A' => 9, 'B' => 11, _ => -1 };
+ if (pc < 0) return null;
+ int i = 1;
+ if (i < t.Length && (t[i] == '#' || t[i] == '♯')) { pc++; i++; }
+ else if (i < t.Length && (t[i] == 'b' || t[i] == '♭')) { pc--; i++; }
+ var oct = t[i..].Replace('\u2212', '-');
+ if (!int.TryParse(oct, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int octave)) return null;
+ int midi = (octave + 1) * 12 + pc;
+ return midi is >= 0 and <= 127 ? midi : null;
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationMapFile.cs b/src/managed/Nota.Application/Articulations/ArticulationMapFile.cs
new file mode 100644
index 00000000..e21f3561
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationMapFile.cs
@@ -0,0 +1,276 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota's own articulation map file (specs/085, contracts/nota-articulation-map-file.md): the same
+// JSON in the library folder (*.notamap), in an export, and embedded in a project's track. Writing
+// is plain; reading repairs what it can deterministically and says what it changed — a broken map
+// must never stop a project from loading, and must never reach the engine broken.
+
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Nota.Application.Localization;
+
+namespace Nota.Application.Articulations;
+
+public static class ArticulationMapFile
+{
+ public const string Format = "nota-articulation-map";
+ public const string Extension = ".notamap";
+ public const long MaxBytes = 16 * 1024 * 1024;
+
+ private static readonly JsonSerializerOptions WriteOpts = new() { WriteIndented = true };
+ private static readonly JsonDocumentOptions ReadOpts = new() { MaxDepth = 64, CommentHandling = JsonCommentHandling.Skip };
+
+ // ---- write ------------------------------------------------------------------------------
+
+ public static string Write(ArticulationMap map) => ToJson(map).ToJsonString(WriteOpts);
+
+ public static JsonObject ToJson(ArticulationMap map)
+ {
+ var o = new JsonObject
+ {
+ ["format"] = Format,
+ ["version"] = ArticulationMap.CurrentVersion,
+ ["id"] = map.Id,
+ ["name"] = map.Name,
+ ["instrumentName"] = map.InstrumentName,
+ ["description"] = map.Description,
+ ["defaultArticulationId"] = map.DefaultArticulationId,
+ ["groups"] = new JsonArray(map.Groups.Select(g => (JsonNode)new JsonObject { ["id"] = g.Id, ["name"] = g.Name }).ToArray()),
+ ["articulations"] = new JsonArray(map.Articulations.Select(a => (JsonNode)ToJson(a)).ToArray()),
+ ["metadata"] = Dict(map.Metadata),
+ };
+ return o;
+ }
+
+ private static JsonObject ToJson(Articulation a) => new()
+ {
+ ["id"] = a.Id,
+ ["name"] = a.Name,
+ ["shortName"] = a.ShortName,
+ ["colorArgb"] = a.ColorArgb,
+ ["sourceColorIndex"] = a.SourceColorIndex,
+ ["groupId"] = a.GroupId,
+ ["trigger"] = a.Trigger == TriggerMode.Momentary ? "momentary" : "latching",
+ ["actions"] = new JsonArray(a.Actions.Select(x => (JsonNode)new JsonObject
+ {
+ ["kind"] = KindName(x.Kind),
+ ["channel"] = x.Channel,
+ ["data1"] = x.Data1,
+ ["data2"] = x.Data2,
+ }).ToArray()),
+ ["noteOffsetMs"] = a.NoteOffsetMs,
+ ["triggerLeadMs"] = a.TriggerLeadMs,
+ ["enabled"] = a.Enabled,
+ ["metadata"] = Dict(a.Metadata),
+ };
+
+ private static JsonObject Dict(Dictionary<string, string> d)
+ {
+ var o = new JsonObject();
+ foreach (var (k, v) in d.OrderBy(p => p.Key, StringComparer.Ordinal)) o[k] = v;
+ return o;
+ }
+
+ private static string KindName(MidiActionKind k) => k switch
+ {
+ MidiActionKind.Keyswitch => "keyswitch",
+ MidiActionKind.ControlChange => "controlChange",
+ MidiActionKind.ProgramChange => "programChange",
+ MidiActionKind.BankSelectMsb => "bankSelectMsb",
+ _ => "bankSelectLsb",
+ };
+
+ private static MidiActionKind? KindOf(string? s) => s switch
+ {
+ "keyswitch" => MidiActionKind.Keyswitch,
+ "controlChange" => MidiActionKind.ControlChange,
+ "programChange" => MidiActionKind.ProgramChange,
+ "bankSelectMsb" => MidiActionKind.BankSelectMsb,
+ "bankSelectLsb" => MidiActionKind.BankSelectLsb,
+ _ => null,
+ };
+
+ // ---- read -------------------------------------------------------------------------------
+
+ /// <summary>True when <paramref name="path"/> is a Nota map by its content.</summary>
+ public static bool Sniff(string path)
+ {
+ try
+ {
+ var fi = new FileInfo(path);
+ if (!fi.Exists || fi.Length > MaxBytes) return false;
+ using var doc = JsonDocument.Parse(File.ReadAllBytes(path), ReadOpts);
+ return doc.RootElement.ValueKind == JsonValueKind.Object
+ && doc.RootElement.TryGetProperty("format", out var f) && f.ValueKind == JsonValueKind.String && f.GetString() == Format;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) { return false; }
+ }
+
+ public static ArticulationImportResult ReadFile(string path)
+ {
+ var res = new ArticulationImportResult();
+ try
+ {
+ var fi = new FileInfo(path);
+ if (!fi.Exists) { res.Error(Loc.F("articulations.import.file_not_found", path)); return res; }
+ if (fi.Length > MaxBytes) { res.Error(Loc.F("articulations.import.too_large", fi.Length)); return res; }
+ Read(Encoding.UTF8.GetString(File.ReadAllBytes(path)), Path.GetFileNameWithoutExtension(path), res);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ res.Map = null;
+ res.Error(Loc.F("articulations.import.could_not_read", ex.Message));
+ }
+ return res;
+ }
+
+ public static ArticulationImportResult Read(string json, string fallbackName)
+ {
+ var res = new ArticulationImportResult();
+ Read(json, fallbackName, res);
+ return res;
+ }
+
+ private static void Read(string json, string fallbackName, ArticulationImportResult res)
+ {
+ if (json.Length > MaxBytes) { res.Error(Loc.F("articulations.import.too_large", (long)json.Length)); return; }
+ JsonNode? root;
+ try { root = JsonNode.Parse(json, documentOptions: ReadOpts); }
+ catch (JsonException ex) { res.Error(Loc.F("articulations.file.not_json", ex.Message)); return; }
+ if (root is not JsonObject o || Str(o, "format") != Format)
+ {
+ res.Error(Loc.T("articulations.file.wrong_format"));
+ return;
+ }
+ int version = Int(o, "version") ?? 1;
+ if (version > ArticulationMap.CurrentVersion)
+ {
+ res.Error(Loc.F("articulations.file.newer_version", version, ArticulationMap.CurrentVersion));
+ return;
+ }
+
+ var map = new ArticulationMap
+ {
+ Id = Str(o, "id") is { Length: > 0 } mapId ? mapId : Guid.NewGuid().ToString("N"),
+ InstrumentName = Str(o, "instrumentName") ?? "",
+ Description = Str(o, "description"),
+ Metadata = Strings(o["metadata"]),
+ };
+ // Saved data stays language-neutral: a nameless map is named after its file, else its id.
+ map.Name = Str(o, "name") is { Length: > 0 } nm ? nm : fallbackName.Length > 0 ? fallbackName : "#" + map.Id;
+
+ // Groups: ids > 0 and unique; anything else is dropped (its articulations become ungrouped).
+ var groupIds = new HashSet<int>();
+ bool droppedGroup = false;
+ foreach (var g in Objects(o["groups"]))
+ {
+ if (Int(g, "id") is int gid && gid > 0 && groupIds.Add(gid)) map.Groups.Add(new ArticulationGroup { Id = gid, Name = Str(g, "name") ?? "" });
+ else droppedGroup = true;
+ }
+ if (droppedGroup) res.Warn(Loc.T("articulations.file.group_dropped"));
+
+ // Articulations: valid unique ids kept as written (notes point at them); a missing or
+ // repeated one gets the next free id, in file order, and the change is reported.
+ var src = Objects(o["articulations"]).ToList();
+ var taken = new HashSet<int>();
+ var wanted = src.Select(a => Int(a, "id") is int i && i > 0 && taken.Add(i) ? i : 0).ToList();
+ int next = taken.Count == 0 ? 1 : taken.Max() + 1;
+ for (int k = 0; k < src.Count; k++)
+ {
+ var a = src[k];
+ int id = wanted[k];
+ string name = Str(a, "name") ?? "";
+ if (id == 0)
+ {
+ id = next++;
+ res.Warn(Loc.F("articulations.file.repaired_id", name.Length > 0 ? name : "#" + id.ToString(CultureInfo.InvariantCulture), id));
+ }
+ if (name.Length == 0) name = "#" + id.ToString(CultureInfo.InvariantCulture);
+ var art = new Articulation
+ {
+ Id = id,
+ Name = name,
+ ShortName = Str(a, "shortName") is { Length: > 0 } sn ? sn : name.Length <= 6 ? name : name[..6],
+ ColorArgb = UInt(a, "colorArgb"),
+ SourceColorIndex = Int(a, "sourceColorIndex"),
+ GroupId = Int(a, "groupId") is int gi && groupIds.Contains(gi) ? gi : 0,
+ Enabled = Bool(a, "enabled") ?? true,
+ Metadata = Strings(a["metadata"]),
+ };
+ string trig = Str(a, "trigger") ?? "latching";
+ if (trig == "momentary") art.Trigger = TriggerMode.Momentary;
+ else if (trig != "latching") res.Warn(Loc.F("articulations.file.unknown_trigger", name, trig));
+
+ double off = Dbl(a, "noteOffsetMs") ?? 0, lead = Dbl(a, "triggerLeadMs") ?? 0;
+ double cOff = double.IsFinite(off) ? Math.Clamp(off, -ArticulationMapCompiler.MaxOffsetMs, ArticulationMapCompiler.MaxOffsetMs) : 0;
+ double cLead = double.IsFinite(lead) ? Math.Clamp(lead, 0, ArticulationMapCompiler.MaxLeadMs) : 0;
+ if (cOff != off || cLead != lead) res.Warn(Loc.F("articulations.file.clamped", name));
+ art.NoteOffsetMs = cOff;
+ art.TriggerLeadMs = cLead;
+
+ bool dropped = false;
+ foreach (var x in Objects(a["actions"]))
+ {
+ var kind = KindOf(Str(x, "kind"));
+ var act = kind is null ? null : new MidiAction
+ {
+ Kind = kind.Value,
+ Channel = x["channel"] is null ? null : Int(x, "channel") ?? -1,
+ Data1 = Int(x, "data1") ?? 0,
+ Data2 = Int(x, "data2") ?? 0,
+ };
+ if (act is null || !act.IsValid()) { dropped = true; continue; }
+ art.Actions.Add(act);
+ }
+ if (dropped) res.Warn(Loc.F("articulations.file.action_dropped", name));
+ map.Articulations.Add(art);
+ }
+
+ if (Int(o, "defaultArticulationId") is int def)
+ {
+ if (map.Find(def) is not null) map.DefaultArticulationId = def;
+ else res.Warn(Loc.T("articulations.file.default_missing"));
+ }
+ res.Map = map;
+ }
+
+ // ---- tolerant field readers: a wrong type reads as absent ---------------------------------
+
+ private static IEnumerable<JsonObject> Objects(JsonNode? n) =>
+ n is JsonArray arr ? arr.OfType<JsonObject>() : Enumerable.Empty<JsonObject>();
+
+ private static string? Str(JsonObject o, string k) =>
+ o[k] is JsonValue v && v.TryGetValue<string>(out var s) ? s : null;
+
+ private static int? Int(JsonObject o, string k)
+ {
+ if (o[k] is not JsonValue v) return null;
+ if (v.TryGetValue<int>(out var i)) return i;
+ return v.TryGetValue<double>(out var d) && double.IsFinite(d) && d == Math.Floor(d) && d is >= int.MinValue and <= int.MaxValue ? (int)d : null;
+ }
+
+ private static uint? UInt(JsonObject o, string k)
+ {
+ if (o[k] is not JsonValue v) return null;
+ if (v.TryGetValue<uint>(out var u)) return u;
+ return v.TryGetValue<long>(out var l) && l is >= 0 and <= uint.MaxValue ? (uint)l : null;
+ }
+
+ private static double? Dbl(JsonObject o, string k) =>
+ o[k] is JsonValue v && v.TryGetValue<double>(out var d) ? d : null;
+
+ private static bool? Bool(JsonObject o, string k) =>
+ o[k] is JsonValue v && v.TryGetValue<bool>(out var b) ? b : null;
+
+ private static Dictionary<string, string> Strings(JsonNode? n)
+ {
+ var d = new Dictionary<string, string>();
+ if (n is JsonObject o)
+ foreach (var (k, v) in o)
+ if (v is JsonValue jv && jv.TryGetValue<string>(out var s)) d[k] = s;
+ return d;
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationMapUsage.cs b/src/managed/Nota.Application/Articulations/ArticulationMapUsage.cs
new file mode 100644
index 00000000..cc5f5734
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationMapUsage.cs
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Which tracks use a map, and putting an edited map on all of them (specs/085, FR-010, T062). A map
+// is shared by id: editing it changes every track that holds that id, as one undo step; a duplicate
+// has its own id and is left alone. The maps the manager lists are the library's and any project
+// track's copy the library doesn't have (a project opened on another machine).
+
+namespace Nota.Application.Articulations;
+
+public static class ArticulationMapUsage
+{
+ /// <summary>Instrument tracks holding the map with id <paramref name="mapId"/>.</summary>
+ public static List<int> TracksUsing(IAudioEngine engine, string mapId)
+ {
+ var ids = new List<int>();
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.IsInstrument
+ && ArticulationMapAssignment.Read(engine, ti.Id) is { } m && m.Id == mapId)
+ ids.Add(ti.Id);
+ return ids;
+ }
+
+ /// <summary>The track MIDI offset an articulation of map <paramref name="mapId"/> adds to, for the
+ /// manager's readout (FR-018): the selected track's when it holds the map, else the one offset
+ /// every track holding it shares; null when no track holds it or their offsets differ.</summary>
+ public static double? TrackOffsetFor(IAudioEngine engine, string mapId, int selectedTrack)
+ {
+ var tracks = TracksUsing(engine, mapId);
+ if (tracks.Contains(selectedTrack)) return engine.GetTrackMidiOffsetMs(selectedTrack);
+ var offsets = tracks.Select(engine.GetTrackMidiOffsetMs).Distinct().ToList();
+ return offsets.Count == 1 ? offsets[0] : null;
+ }
+
+ /// <summary>Puts <paramref name="map"/> on every track that holds its id, as one undo step.
+ /// Returns how many tracks took it.</summary>
+ public static int ApplyEverywhere(IAudioEngine engine, ArticulationMap map)
+ {
+ var tracks = TracksUsing(engine, map.Id);
+ if (tracks.Count == 0) return 0;
+ int n = 0;
+ engine.BeginUndoGroup();
+ try
+ {
+ foreach (int t in tracks)
+ if (ArticulationMapAssignment.Assign(engine, t, map)) n++;
+ }
+ finally { engine.EndUndoGroup(); }
+ return n;
+ }
+
+ /// <summary>The maps the manager lists, by name: the library's, and every map a project track
+ /// holds. When the project's copy of a map differs from the library's (the library was saved
+ /// after an edit that was then undone, or on another machine), the project's copy is listed —
+ /// it is what the tracks play, and saving an edit of it must not overwrite them with the
+ /// library's version — flagged <c>DiffersFromLibrary</c>. A map no library holds is flagged
+ /// <c>OnlyInProject</c>. Several tracks with different copies of one map: the first track's.</summary>
+ public static List<(ArticulationMap Map, bool OnlyInProject, bool DiffersFromLibrary)> Catalog(IAudioEngine engine, IArticulationLibrary? library)
+ {
+ var lib = new Dictionary<string, ArticulationMap>(StringComparer.Ordinal);
+ // A copied file can repeat an ID under another filename. Keep the first readable copy,
+ // as with project tracks below, so a duplicate can't prevent the manager from opening.
+ foreach (var m in library?.List() ?? Array.Empty<ArticulationMap>()) lib.TryAdd(m.Id, m);
+ var list = new List<(ArticulationMap Map, bool OnlyInProject, bool DiffersFromLibrary)>();
+ var seen = new HashSet<string>(StringComparer.Ordinal);
+ for (int i = 0; i < engine.TrackCount; i++)
+ if (engine.TryGetTrackInfo(i, out var ti) && ti.IsInstrument
+ && ArticulationMapAssignment.Read(engine, ti.Id) is { } m && seen.Add(m.Id))
+ {
+ if (!lib.TryGetValue(m.Id, out var saved)) list.Add((m, true, false));
+ else if (ArticulationMapFile.Write(saved) != ArticulationMapFile.Write(m)) list.Add((m, false, true));
+ else list.Add((saved, false, false));
+ }
+ foreach (var m in lib.Values)
+ if (!seen.Contains(m.Id)) list.Add((m, false, false));
+ return list.OrderBy(x => x.Map.Name, StringComparer.CurrentCultureIgnoreCase).ThenBy(x => x.Map.Id, StringComparer.Ordinal).ToList();
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/ArticulationText.cs b/src/managed/Nota.Application/Articulations/ArticulationText.cs
new file mode 100644
index 00000000..11ab67ee
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ArticulationText.cs
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// How articulations read in the interface (specs/085): an action as "Keyswitch C1 · vel 1",
+// a map as "44 articulations". Pure, so the import preview and the inspector show the same
+// wording and the smoke test can check it without a window.
+
+using Nota.Application.Localization;
+
+namespace Nota.Application.Articulations;
+
+public static class ArticulationText
+{
+ public static string Action(MidiAction a)
+ {
+ string body = a.Kind switch
+ {
+ MidiActionKind.Keyswitch => Loc.F("articulations.action.keyswitch", SamplerModel.NoteName(a.Data1), a.Data2),
+ MidiActionKind.ControlChange => Loc.F("articulations.action.control_change", a.Data1, a.Data2),
+ MidiActionKind.ProgramChange => Loc.F("articulations.action.program_change", a.Data1),
+ MidiActionKind.BankSelectMsb => Loc.F("articulations.action.bank_msb", a.Data2),
+ _ => Loc.F("articulations.action.bank_lsb", a.Data2),
+ };
+ return a.Channel is int ch ? Loc.F("articulations.action.on_channel", body, ch) : body;
+ }
+
+ /// <summary>Every action of an articulation, in send order; a dash when it sends nothing.</summary>
+ public static string Actions(Articulation art) =>
+ art.Actions.Count == 0 ? Loc.T("articulations.action.none") : string.Join(" · ", art.Actions.Select(Action));
+
+ public static string Count(ArticulationMap map) => Loc.Plural("articulations.count", map.Articulations.Count);
+
+ /// <summary>A group's label: its name, else a numbered one (files often number groups without naming them).</summary>
+ public static string Group(ArticulationGroup g) => g.Name.Length > 0 ? g.Name : Loc.F("articulations.group_n", g.Id);
+
+ /// <summary>FR-018: when each articulation's notes play, relative to the grid — the track offset
+ /// plus the articulation's own, applied once. Only articulations with an offset of their own
+ /// (the rest play at the track offset), enabled ones, in map order. The view formats the numbers.</summary>
+ public static IReadOnlyList<(string Name, double TotalMs)> EffectiveOffsets(ArticulationMap map, double trackOffsetMs) =>
+ map.Articulations.Where(a => a.Enabled && a.NoteOffsetMs != 0)
+ .Select(a => (a.Name, trackOffsetMs + a.NoteOffsetMs)).ToList();
+}
diff --git a/src/managed/Nota.Application/Articulations/ExpressionMapImporter.cs b/src/managed/Nota.Application/Articulations/ExpressionMapImporter.cs
new file mode 100644
index 00000000..f6bacab3
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/ExpressionMapImporter.cs
@@ -0,0 +1,266 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Cubase .expressionmap → an ArticulationMap.
+//
+// The format handled here is the XML "InstrumentMap" document, verified against a real file
+// (Art Conductor / Babylonwaves "CSSS Violins 1 A"):
+// InstrumentMap
+// string name="name" the map's name
+// member "slotvisuals" a list of USlotVisuals (a copy of each slot's own)
+// member "slots" → list of PSoundSlot one articulation each:
+// obj PSlotThruTrigger "remote" status / data1 — the remote key (not an articulation output)
+// obj PSlotMidiAction "action"
+// member "midiMessages" → POutputEvent { status, data1, data2 } ordered output
+// channel (-1 = the note's own channel), key / key2 / controller1* (editor mirrors)
+// member "sv" → USlotVisuals { text (short name), description, group, articulationtype,
+// symbol, displaytype }
+// member "name" → string "s" the articulation's name
+// int "color" a Cubase palette INDEX, not an RGB value
+//
+// Not verifiable from that file, so reported rather than guessed: switch modes (the file carries
+// no latching / momentary flag), non-zero groups, program-change and bank-change events, the
+// slot-level channel when it is not -1, and the RGB behind a colour index.
+
+using System.Globalization;
+using System.Xml;
+using System.Xml.Linq;
+using Nota.Application.Localization;
+
+namespace Nota.Application.Articulations;
+
+public static class ExpressionMapImporter
+{
+ /// <summary>Largest file accepted (a real map is ~100 KB).</summary>
+ public const long MaxBytes = 16 * 1024 * 1024;
+
+ /// <summary>True when <paramref name="path"/> looks like a Cubase expression map by its content,
+ /// not its extension.</summary>
+ public static bool Sniff(string path)
+ {
+ try
+ {
+ using var fs = File.OpenRead(path);
+ return fs.Length <= MaxBytes && Sniff(fs);
+ }
+ catch { return false; }
+ }
+
+ public static bool Sniff(Stream s)
+ {
+ try
+ {
+ using var r = XmlReader.Create(s, ReaderSettings());
+ while (r.Read())
+ if (r.NodeType == XmlNodeType.Element) return r.Name == "InstrumentMap";
+ return false;
+ }
+ catch { return false; }
+ }
+
+ public static ArticulationImportResult ImportFile(string path)
+ {
+ var res = new ArticulationImportResult();
+ try
+ {
+ var fi = new FileInfo(path);
+ if (!fi.Exists) { res.Error(Loc.F("articulations.import.file_not_found", path)); return res; }
+ if (fi.Length > MaxBytes) { res.Error(Loc.F("articulations.import.too_large", fi.Length)); return res; }
+ using var fs = fi.OpenRead();
+ Import(fs, Path.GetFileNameWithoutExtension(path), res);
+ if (res.Map is not null) res.Map.Metadata["source.file"] = fi.Name;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ res.Map = null;
+ res.Error(Loc.F("articulations.import.could_not_read", ex.Message));
+ }
+ return res;
+ }
+
+ public static ArticulationImportResult Import(Stream stream, string fallbackName)
+ {
+ var res = new ArticulationImportResult();
+ Import(stream, fallbackName, res);
+ return res;
+ }
+
+ private static XmlReaderSettings ReaderSettings() => new()
+ {
+ DtdProcessing = DtdProcessing.Prohibit, // no entity expansion from a hostile file
+ XmlResolver = null,
+ MaxCharactersInDocument = MaxBytes,
+ IgnoreComments = false,
+ };
+
+ /// <summary>The name of a slot the file leaves unnamed: its 1-based position. Saved with the map,
+ /// so it is language-neutral, never interface text.</summary>
+ private static string UnnamedSlot(int index) => "#" + (index + 1).ToString(CultureInfo.InvariantCulture);
+
+ private static void Import(Stream stream, string fallbackName, ArticulationImportResult res)
+ {
+ XDocument doc;
+ try
+ {
+ using var r = XmlReader.Create(stream, ReaderSettings());
+ doc = XDocument.Load(r, LoadOptions.None);
+ }
+ catch (XmlException ex)
+ {
+ res.Error(Loc.F("articulations.import.xml_error", ex.LineNumber, ex.Message));
+ return;
+ }
+
+ var root = doc.Root;
+ if (root is null || root.Name.LocalName != "InstrumentMap")
+ {
+ res.Error(Loc.T("articulations.import.not_expression_map"));
+ return;
+ }
+
+ var map = new ArticulationMap { Name = NamedString(root, "name") ?? fallbackName };
+ if (string.IsNullOrWhiteSpace(map.Name)) map.Name = fallbackName;
+ map.Metadata["source.format"] = "expressionmap";
+
+ // Header comments (maker, content / engine version) are kept as provenance.
+ var comments = doc.Nodes().OfType<XComment>().Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList();
+ if (comments.Count > 0) map.Metadata["source.comments"] = string.Join("\n", comments);
+
+ var slotsMember = Member(root, "slots");
+ var slots = slotsMember?.Element("list")?.Elements("obj").Where(o => (string?)o.Attribute("class") == "PSoundSlot").ToList();
+ if (slots is null || slots.Count == 0)
+ {
+ res.Error(Loc.T("articulations.import.no_sound_slots"));
+ return;
+ }
+
+ int nextId = 1;
+ int skippedEmpty = 0;
+ var groupsSeen = new SortedSet<int>();
+ for (int i = 0; i < slots.Count; i++)
+ {
+ var slot = slots[i];
+ string slotName = NamedString(Member(slot, "name"), "s") ?? "";
+ var vis = Member(slot, "sv")?.Element("list")?.Elements("obj").FirstOrDefault(o => (string?)o.Attribute("class") == "USlotVisuals");
+ var action = slot.Elements("obj").FirstOrDefault(o => (string?)o.Attribute("class") == "PSlotMidiAction");
+ var events = Member(action, "midiMessages")?.Element("list")?.Elements("obj")
+ .Where(o => (string?)o.Attribute("class") == "POutputEvent").ToList() ?? new List<XElement>();
+
+ // Cubase's first slot is the empty "no articulation" state: no name, no output.
+ if (events.Count == 0 && (slotName is "" or "---"))
+ {
+ skippedEmpty++;
+ continue;
+ }
+
+ string label = slotName.Length > 0 ? slotName : UnnamedSlot(i);
+ var art = new Articulation
+ {
+ Id = nextId++,
+ Name = slotName.Length > 0 ? slotName : (NamedString(vis, "description") ?? label),
+ ShortName = NamedString(vis, "text") ?? "",
+ };
+ if (art.ShortName.Length == 0) art.ShortName = art.Name.Length <= 6 ? art.Name : art.Name[..6];
+ if (NamedString(vis, "description") is { Length: > 0 } desc && desc != art.Name) art.Metadata["description"] = desc;
+ if ((string?)slot.Attribute("ID") is { } sid) art.Metadata["source.id"] = sid;
+
+ if (NamedInt(slot, "color") is { } colorIdx) art.SourceColorIndex = colorIdx;
+
+ int group = NamedInt(vis, "group") ?? 0;
+ if (group > 0) { art.GroupId = group; groupsSeen.Add(group); }
+ if (NamedInt(vis, "articulationtype") is { } at && at != 0)
+ art.Metadata["source.articulationtype"] = at.ToString(CultureInfo.InvariantCulture);
+
+ // Slot-level channel: -1 = the note's own. Anything else is stored 0-based or 1-based
+ // depending on the writer, which one file cannot settle — keep it, say so, do not apply it.
+ int slotChannel = NamedInt(action, "channel") ?? -1;
+ if (slotChannel != -1)
+ {
+ art.Metadata["source.channel"] = slotChannel.ToString(CultureInfo.InvariantCulture);
+ res.Warn(Loc.F("articulations.import.slot_channel_kept", label, slotChannel));
+ }
+
+ foreach (var ev in events)
+ {
+ int? status = NamedInt(ev, "status"), d1 = NamedInt(ev, "data1"), d2 = NamedInt(ev, "data2");
+ if (status is null || d1 is null)
+ {
+ res.Warn(Loc.F("articulations.import.message_without_data", label));
+ continue;
+ }
+ var act = ToAction(status.Value, d1.Value, d2 ?? 0, out string? why);
+ if (act is null)
+ {
+ res.Warn(Loc.F("articulations.import.unsupported_message", label, status, d1, d2, why));
+ art.Metadata["unsupported.midi"] = (art.Metadata.GetValueOrDefault("unsupported.midi") ?? "") + $"{status}:{d1}:{d2};";
+ continue;
+ }
+ if (!act.IsValid())
+ {
+ res.Warn(Loc.F("articulations.import.message_out_of_range", label, status, d1, d2));
+ continue;
+ }
+ art.Actions.Add(act);
+ }
+ if (art.Actions.Count == 0) res.Warn(Loc.F("articulations.import.no_usable_action", label));
+ map.Articulations.Add(art);
+ }
+
+ // The file numbers groups but never names them: the name stays empty (saved data is
+ // language-neutral) and the interface shows a numbered label for it.
+ foreach (int g in groupsSeen)
+ map.Groups.Add(new ArticulationGroup { Id = g, Name = "" });
+ if (groupsSeen.Count > 0)
+ res.Warn(Loc.T("articulations.import.groups_unnamed"));
+
+ if (skippedEmpty > 0)
+ res.Info(Loc.Plural("articulations.import.skipped_empty", skippedEmpty));
+ res.Info(Loc.T("articulations.import.switch_mode_not_stored"));
+ if (map.Articulations.Any(a => a.SourceColorIndex is not null))
+ res.Info(Loc.T("articulations.import.colour_indices"));
+
+ if (map.Articulations.Count == 0)
+ {
+ res.Error(Loc.T("articulations.import.no_articulations"));
+ return;
+ }
+ res.Map = map;
+ }
+
+ /// <summary>Cubase POutputEvent → a model action. The status byte's low nibble is the channel
+ /// (0 = no explicit channel, which in this format means the note's own).</summary>
+ private static MidiAction? ToAction(int status, int d1, int d2, out string? why)
+ {
+ why = null;
+ if (status is < 128 or > 255) { why = Loc.T("articulations.import.reason_status_out_of_range"); return null; }
+ int kind = status & 0xF0, ch = status & 0x0F;
+ int? channel = ch == 0 ? null : ch + 1; // a non-zero nibble names the channel explicitly (1-based)
+ switch (kind)
+ {
+ case 0x90: return new MidiAction { Kind = MidiActionKind.Keyswitch, Channel = channel, Data1 = d1, Data2 = d2 };
+ case 0xB0:
+ return d1 switch
+ {
+ 0 => new MidiAction { Kind = MidiActionKind.BankSelectMsb, Channel = channel, Data1 = 0, Data2 = d2 },
+ 32 => new MidiAction { Kind = MidiActionKind.BankSelectLsb, Channel = channel, Data1 = 32, Data2 = d2 },
+ _ => new MidiAction { Kind = MidiActionKind.ControlChange, Channel = channel, Data1 = d1, Data2 = d2 },
+ };
+ case 0xC0: return new MidiAction { Kind = MidiActionKind.ProgramChange, Channel = channel, Data1 = d1 };
+ default: why = Loc.F("articulations.import.reason_message_type", kind.ToString("X2", CultureInfo.InvariantCulture)); return null;
+ }
+ }
+
+ // --- the format's "typed child with a name attribute" idiom ---------------------------------
+
+ private static XElement? Member(XElement? parent, string name) =>
+ parent?.Elements("member").FirstOrDefault(m => (string?)m.Attribute("name") == name);
+
+ private static string? NamedString(XElement? parent, string name) =>
+ parent?.Elements("string").FirstOrDefault(e => (string?)e.Attribute("name") == name)?.Attribute("value")?.Value;
+
+ private static int? NamedInt(XElement? parent, string name)
+ {
+ var v = parent?.Elements("int").FirstOrDefault(e => (string?)e.Attribute("name") == name)?.Attribute("value")?.Value;
+ return int.TryParse(v?.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) ? n : null;
+ }
+}
diff --git a/src/managed/Nota.Application/Articulations/IArticulationLibrary.cs b/src/managed/Nota.Application/Articulations/IArticulationLibrary.cs
new file mode 100644
index 00000000..78d985d0
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/IArticulationLibrary.cs
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The user's articulation maps outside any project (specs/085, FR-008): what the manager lists and
+// a track can be given. One map per file, addressed by its stable map id; projects embed their own
+// copy, so a project opens without the library.
+
+namespace Nota.Application.Articulations;
+
+public interface IArticulationLibrary
+{
+ /// <summary>Every readable map, by name. A file that can't be read is skipped (and listed in
+ /// <see cref="Unreadable"/>), never thrown.</summary>
+ IReadOnlyList<ArticulationMap> List();
+
+ /// <summary>Files the last <see cref="List"/> could not read.</summary>
+ IReadOnlyList<string> Unreadable { get; }
+
+ ArticulationMap? Get(string mapId);
+
+ /// <summary>Adds or replaces the map with this id. Written atomically: a failure leaves the
+ /// previous file as it was.</summary>
+ void Save(ArticulationMap map);
+
+ /// <summary>False when there was no such map.</summary>
+ bool Delete(string mapId);
+}
diff --git a/src/managed/Nota.Application/Articulations/KeySwitchListImporter.cs b/src/managed/Nota.Application/Articulations/KeySwitchListImporter.cs
new file mode 100644
index 00000000..f7d85002
--- /dev/null
+++ b/src/managed/Nota.Application/Articulations/KeySwitchListImporter.cs
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Studio One .keyswitch ("Music.KeySwitchList") → an ArticulationMap.
+//
+// Verified against a real file (Babylonwaves "CSSS Violins 1 Attribute.keyswitch") by comparing
+// every entry with the same patch's Cubase expression map:
+//
+// <Music.KeySwitchList name="…">
+// <Attributes name="Long" id="1" pitch="24" activation="note24.1|note35.1|unknown"/>
+//
+// name the articulation's name; id 0 / "---" is the empty default entry
+// id position in the list (matches the Cubase slot order)
+// pitch the entry's primary keyswitch, for display
+// activation "|"-separated tokens, in the order they are sent:
+// noteP.V keyswitch note P, velocity V (note24.1 = Cubase 144/24/1)
+// noteP keyswitch note P, velocity 127 (note35 = Cubase 144/35/127)
+// unknown an action this format cannot describe — in the Cubase twin of this file
+// it is the CC 58 that selects the articulation. It is NOT recoverable here.
+//
+// The format carries no colours, groups, channels or switch mode.
+// Studio One's separate .soundvariation format has not been seen yet and is NOT handled here.
+
+using System.Globalization;
+using System.Xml;
+using System.Xml.Linq;
+using Nota.Application.Localization;
+
+namespace Nota.Application.Articulations;
+
+public static class KeySwitchListImporter
+{
+ public const long MaxBytes = 16 * 1024 * 1024;
+ private const string RootName = "Music.KeySwitchList";
+
+ public static bool Sniff(string path)
+ {
+ try
+ {
+ using var fs = File.OpenRead(path);
+ return fs.Length <= MaxBytes && Sniff(fs);
+ }
+ catch { return false; }
+ }
+
+ public static bool Sniff(Stream s)
+ {
+ try
+ {
+ using var r = XmlReader.Create(s, ReaderSettings());
+ while (r.Read())
+ if (r.NodeType == XmlNodeType.Element) return r.Name == RootName;
+ return false;
+ }
+ catch { return false; }
+ }
+
+ public static ArticulationImportResult ImportFile(string path)
+ {
+ var res = new ArticulationImportResult();
+ try
+ {
+ var fi = new FileInfo(path);
+ if (!fi.Exists) { res.Error(Loc.F("articulations.import.file_not_found", path)); return res; }
+ if (fi.Length > MaxBytes) { res.Error(Loc.F("articulations.import.too_large", fi.Length)); return res; }
+ using var fs = fi.OpenRead();
+ Import(fs, Path.GetFileNameWithoutExtension(path), res);
+ if (res.Map is not null) res.Map.Metadata["source.file"] = fi.Name;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ res.Map = null;
+ res.Error(Loc.F("articulations.import.could_not_read", ex.Message));
+ }
+ return res;
+ }
+
+ public static ArticulationImportResult Import(Stream stream, string fallbackName)
+ {
+ var res = new ArticulationImportResult();
+ Import(stream, fallbackName, res);
+ return res;
+ }
+
+ private static XmlReaderSettings ReaderSettings() => new()
+ {
+ DtdProcessing = DtdProcessing.Prohibit,
+ XmlResolver = null,
+ MaxCharactersInDocument = MaxBytes,
+ };
+
+ private static void Import(Stream stream, string fallbackName, ArticulationImportResult res)
+ {
+ XDocument doc;
+ try
+ {
+ using var r = XmlReader.Create(stream, ReaderSettings());
+ doc = XDocument.Load(r);
+ }
+ catch (XmlException ex)
+ {
+ res.Error(Loc.F("articulations.import.xml_error", ex.LineNumber, ex.Message));
+ return;
+ }
+
+ var root = doc.Root;
+ if (root is null || root.Name.LocalName != RootName)
+ {
+ res.Error(Loc.T("articulations.import.not_keyswitch_list"));
+ return;
+ }
+
+ var map = new ArticulationMap { Name = (string?)root.Attribute("name") is { Length: > 0 } n ? n : fallbackName };
+ map.Metadata["source.format"] = "keyswitch";
+
+ var used = new HashSet<int>();
+ int nextFallback = 1;
+ int skippedEmpty = 0, withUnknown = 0;
+ foreach (var e in root.Elements().Where(x => x.Name.LocalName == "Attributes")) // one entry each
+ {
+ string name = (string?)e.Attribute("name") ?? "";
+ string activation = (string?)e.Attribute("activation") ?? "";
+ int.TryParse((string?)e.Attribute("id"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int fileId);
+
+ // The empty default entry: no name worth keeping and nothing to send.
+ if ((name is "" or "---") && activation.Length == 0) { skippedEmpty++; continue; }
+
+ // Saved with the map, so language-neutral: the file's own number, not interface text.
+ string label = name.Length > 0 ? name : "#" + fileId.ToString(CultureInfo.InvariantCulture);
+ // The file's own id keeps re-imports stable; a missing, zero or repeated id gets the next free one.
+ int id = fileId > 0 && used.Add(fileId) ? fileId : 0;
+ if (id == 0) { while (!used.Add(nextFallback)) nextFallback++; id = nextFallback; }
+
+ var art = new Articulation
+ {
+ Id = id,
+ Name = label,
+ ShortName = label.Length <= 6 ? label : label[..6],
+ };
+ if ((string?)e.Attribute("pitch") is { Length: > 0 } pitch) art.Metadata["source.pitch"] = pitch;
+ if (activation.Length > 0) art.Metadata["source.activation"] = activation;
+
+ bool sawUnknown = false;
+ foreach (var tokenRaw in activation.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ if (tokenRaw.Equals("unknown", StringComparison.OrdinalIgnoreCase)) { sawUnknown = true; continue; }
+ var act = ParseNoteToken(tokenRaw);
+ if (act is null)
+ {
+ res.Warn(Loc.F("articulations.import.unrecognised_activation", label, tokenRaw));
+ continue;
+ }
+ if (!act.IsValid())
+ {
+ res.Warn(Loc.F("articulations.import.activation_out_of_range", label, tokenRaw));
+ continue;
+ }
+ art.Actions.Add(act);
+ }
+ if (sawUnknown) withUnknown++;
+ if (art.Actions.Count == 0) res.Warn(Loc.F("articulations.import.no_usable_action", label));
+ map.Articulations.Add(art);
+ }
+
+ if (skippedEmpty > 0) res.Info(Loc.Plural("articulations.import.skipped_empty", skippedEmpty));
+ if (withUnknown > 0) res.Warn(Loc.Plural("articulations.import.unknown_actions", withUnknown));
+ res.Info(Loc.T("articulations.import.keyswitch_no_extras"));
+
+ if (map.Articulations.Count == 0)
+ {
+ res.Error(Loc.T("articulations.import.no_articulations"));
+ return;
+ }
+ res.Map = map;
+ }
+
+ /// <summary>"note24.1" → keyswitch 24 at velocity 1; "note35" → keyswitch 35 at velocity 127.</summary>
+ private static MidiAction? ParseNoteToken(string token)
+ {
+ if (!token.StartsWith("note", StringComparison.OrdinalIgnoreCase)) return null;
+ var rest = token[4..];
+ int vel = 127;
+ int dot = rest.IndexOf('.');
+ if (dot >= 0)
+ {
+ if (!int.TryParse(rest[(dot + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out vel)) return null;
+ rest = rest[..dot];
+ }
+ if (!int.TryParse(rest, NumberStyles.None, CultureInfo.InvariantCulture, out int pitch)) return null;
+ return new MidiAction { Kind = MidiActionKind.Keyswitch, Data1 = pitch, Data2 = vel };
+ }
+}
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index f791f643..52ccd486 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -36,6 +36,42 @@ public struct NotaNote(int pitch, double startBeat, double lengthBeats, float ve
/// <summary>The note's recorded MPE in the engine's expression store (0 = none). Copy the
/// note (don't rebuild it from its fields) and the expression travels with it.</summary>
public int ExprId;
+ /// <summary>The note's articulation: a stable id in its track's articulation map (0 = none /
+ /// the map's default). Copy the note (don't rebuild it from its fields) and it travels with it.</summary>
+ public int ArticulationId;
+
+ /// <summary>Every field equal. Use this to tell whether an edit changed a note: a comparison
+ /// that lists fields by hand misses the next one added (an articulation-only edit was once
+ /// never sent to the engine for that reason). The smoke test checks it covers every field.</summary>
+ public static bool Same(in NotaNote a, in NotaNote b) =>
+ a.Pitch == b.Pitch && a.StartBeat == b.StartBeat && a.LengthBeats == b.LengthBeats
+ && a.Velocity == b.Velocity && a.ExprId == b.ExprId && a.ArticulationId == b.ArticulationId;
+}
+
+/// <summary>One articulation of a compiled articulation map (specs/085). Matches native
+/// NotaArticulationEntry: ids &gt; 0 and strictly ascending; actions are [ActionStart, ActionStart + ActionCount).</summary>
+[StructLayout(LayoutKind.Sequential)]
+public struct NotaArticulationEntry
+{
+ public int Id;
+ /// <summary>0 latching, 1 momentary.</summary>
+ public int TriggerMode;
+ public double OffsetMs;
+ public double LeadMs;
+ public int ActionStart;
+ public int ActionCount;
+}
+
+/// <summary>One MIDI action of a compiled articulation map. Matches native NotaArticulationAction.</summary>
+[StructLayout(LayoutKind.Sequential)]
+public struct NotaArticulationAction
+{
+ /// <summary>0 keyswitch, 1 control change, 2 program change, 3 bank select MSB, 4 bank select LSB.</summary>
+ public int Kind;
+ /// <summary>0 = the note's own channel, 1..16 explicit.</summary>
+ public int Channel;
+ public int Data1;
+ public int Data2;
}
/// <summary>One breakpoint of a note's recorded expression (MPE). Matches native NotaExprPoint:
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 63709e98..d8aaa4c4 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -357,6 +357,18 @@ public interface IAudioEngine : IDisposable
/// MIDI output ("MIDI In"). sourceTrackId = -1 turns it off.</summary>
void SetTrackMidiSource(int trackId, int sourceTrackId);
int GetTrackMidiSource(int trackId);
+ /// <summary>Track-level MIDI playback offset in ms (negative = notes play earlier). Playback only:
+ /// the notes in the clips do not move. Clamped to ±2000 ms.</summary>
+ void SetTrackMidiOffsetMs(int trackId, double ms);
+ double GetTrackMidiOffsetMs(int trackId);
+ /// <summary>Gives an instrument track its articulation map (specs/085): the compiled table
+ /// (see ArticulationMapCompiler) plus the map as Nota's JSON, saved with the project. One undo
+ /// step. False, with nothing changed, when the engine rejects the table or the track.</summary>
+ bool SetTrackArticulationMap(int trackId, int defaultId, NotaArticulationEntry[] entries, NotaArticulationAction[] actions, string mapJson);
+ /// <summary>Removes the track's map; notes keep their articulation ids. One undo step.</summary>
+ bool ClearTrackArticulationMap(int trackId);
+ /// <summary>The map JSON the track holds, or null when it has none.</summary>
+ string? GetTrackArticulationMapJson(int trackId);
// --- freeze (M7): bounce a track's pre-fader audio to a buffer and play it back
// in place of the live instrument+device chain. Drive offline with the backend
diff --git a/src/managed/Nota.Application/Localization/en.json b/src/managed/Nota.Application/Localization/en.json
index 7b550503..1aef6953 100644
--- a/src/managed/Nota.Application/Localization/en.json
+++ b/src/managed/Nota.Application/Localization/en.json
@@ -144,6 +144,186 @@
"arrangement.ungroup": "Ungroup",
"arrangement.vol": "Vol",
"arrangement.zoom": "Zoom",
+ "articulations.action.bank_lsb": "Bank LSB {0}",
+ "articulations.action.bank_msb": "Bank MSB {0}",
+ "articulations.action.control_change": "CC {0} = {1}",
+ "articulations.action.keyswitch": "Keyswitch {0} · vel {1}",
+ "articulations.action.none": "Sends nothing",
+ "articulations.action.on_channel": "{0} (ch {1})",
+ "articulations.action.program_change": "Program {0}",
+ "articulations.colour.chip_tip": "Colour notes by their articulation instead of the track colour",
+ "articulations.count": { "one": "{0} articulation", "other": "{0} articulations" },
+ "articulations.file.action_dropped": "\"{0}\": an invalid MIDI action was dropped.",
+ "articulations.file.clamped": "\"{0}\": an offset or lead time out of range was brought into range.",
+ "articulations.file.default_missing": "The default articulation isn't in the map any more; the map has no default now.",
+ "articulations.file.group_dropped": "A group with a missing or repeated id was dropped; its articulations are ungrouped.",
+ "articulations.file.newer_version": "This articulation map was saved by a newer Nota (format {0}); this version reads format {1}.",
+ "articulations.file.not_json": "Not a Nota articulation map: {0}",
+ "articulations.file.repaired_id": "\"{0}\": its id was missing or repeated and is now {1}. Notes that used the old id play the default.",
+ "articulations.file.unknown_trigger": "\"{0}\": unknown trigger mode \"{1}\"; it plays as Latching.",
+ "articulations.file.wrong_format": "Not a Nota articulation map: the file doesn't say \"nota-articulation-map\".",
+ "articulations.group_n": "Group {0}",
+ "articulations.import.activation_out_of_range": "\"{0}\": activation \"{1}\" is out of MIDI range and was skipped.",
+ "articulations.import.colour_indices": "Colours: the file stores Cubase palette indices, not RGB. The index is kept; Nota shows its own colour for it until you set one.",
+ "articulations.import.could_not_read": "Couldn't read the file: {0}",
+ "articulations.import.file_not_found": "File not found: {0}",
+ "articulations.import.groups_unnamed": "Group numbers were kept, but the file doesn't name its groups.",
+ "articulations.import.keyswitch_no_extras": "This format carries no colours, groups, channels or switch mode; every articulation imports as Latching on the note's own channel.",
+ "articulations.import.message_out_of_range": "\"{0}\": a MIDI message out of range (status {1}, data {2}/{3}) was skipped.",
+ "articulations.import.message_without_data": "\"{0}\": a MIDI message with no status or data was skipped.",
+ "articulations.import.no_articulations": "The file has no articulations.",
+ "articulations.import.no_sound_slots": "The expression map contains no sound slots.",
+ "articulations.import.no_usable_action": "\"{0}\" has no usable MIDI action; it can be selected but sends nothing.",
+ "articulations.import.not_expression_map": "Not a Cubase expression map: the root element is not <InstrumentMap>.",
+ "articulations.import.not_keyswitch_list": "Not a Studio One keyswitch list: the root element is not <Music.KeySwitchList>.",
+ "articulations.import.reason_message_type": "message type 0x{0} is not a keyswitch, controller or program change",
+ "articulations.import.reason_status_out_of_range": "status byte out of range",
+ "articulations.import.skipped_empty": { "one": "Skipped {0} empty default slot (no name, no MIDI).", "other": "Skipped {0} empty default slots (no name, no MIDI)." },
+ "articulations.import.slot_channel_kept": "\"{0}\": slot channel {1} was kept as metadata but not applied (its numbering is unverified).",
+ "articulations.import.soundvariation_unsupported": "Studio One Sound Variation files (.soundvariation) aren't supported yet. Export the keyswitch list (.keyswitch) or use the Cubase expression map.",
+ "articulations.import.switch_mode_not_stored": "Switch mode is not stored in the file; every articulation imports as Latching. Set Momentary per articulation where the library needs it.",
+ "articulations.import.too_large": "The file is too large to be an articulation map ({0} bytes).",
+ "articulations.import.unknown_actions": { "one": "{0} articulation lists an action the keyswitch format can't describe (\"unknown\"). Only its keyswitch notes were imported. If the library also selects articulations with a controller (CC 58 in Cinematic Studio Strings, for example), import the Cubase expression map instead or add the controller by hand.", "other": "{0} articulations list an action the keyswitch format can't describe (\"unknown\"). Only their keyswitch notes were imported. If the library also selects articulations with a controller (CC 58 in Cinematic Studio Strings, for example), import the Cubase expression map instead or add the controller by hand." },
+ "articulations.import.unknown_format": "This file isn't an articulation map Nota can read (Cubase .expressionmap, Studio One .keyswitch or Nota .notamap).",
+ "articulations.import.unrecognised_activation": "\"{0}\": unrecognised activation \"{1}\" was kept as metadata but sends nothing.",
+ "articulations.import.unsupported_message": "\"{0}\": unsupported MIDI message (status {1}, data {2}/{3}): {4}.",
+ "articulations.import.xml_error": "Not a valid file (XML error at line {0}: {1}).",
+ "articulations.inspector.all_files": "All files",
+ "articulations.inspector.assign_failed": "The track couldn't take this articulation map.",
+ "articulations.inspector.drop_hint": "Or drop a Cubase .expressionmap, Studio One .keyswitch or Nota .notamap file here.",
+ "articulations.inspector.edit_maps": "Edit maps…",
+ "articulations.inspector.edit_maps_tip": "Open the articulation map manager to edit, duplicate or export maps",
+ "articulations.inspector.effective": "{0} plays at {1} ({2} track + {3} articulation)",
+ "articulations.inspector.file_type": "Articulation maps",
+ "articulations.inspector.head": "Articulations",
+ "articulations.inspector.import": "Import…",
+ "articulations.inspector.import_tip": "Import an articulation map from a file and give it to this track",
+ "articulations.inspector.library_failed": "The map was given to the track, but it couldn't be kept in your library: {0}",
+ "articulations.inspector.map": "Map",
+ "articulations.inspector.map_tip": "The articulation map this track's notes choose from",
+ "articulations.inspector.midi_offset": "MIDI offset",
+ "articulations.inspector.midi_offset_tip": "Plays this track's notes earlier (negative) or later, to make up for slow attacks. The notes don't move.",
+ "articulations.inspector.remove": "Remove",
+ "articulations.inspector.remove_tip": "Take the map off this track; the notes keep their articulations",
+ "articulations.manager.actions": "MIDI actions",
+ "articulations.manager.add_action": "Add action",
+ "articulations.manager.add_action_tip": "Add a MIDI message this articulation sends, after the others",
+ "articulations.manager.add_name": "Articulation {0}",
+ "articulations.manager.add_tip": "Add an articulation at the end",
+ "articulations.manager.add_to_library": "Add to library",
+ "articulations.manager.art_name_tip": "The name shown in the piano roll menu",
+ "articulations.manager.articulations": "Articulations",
+ "articulations.manager.assign": "Assign to track",
+ "articulations.manager.assign_dirty_tip": "Save or revert your changes first",
+ "articulations.manager.assign_no_track_tip": "Select an instrument track first",
+ "articulations.manager.assign_tip": "Give this map to the selected track",
+ "articulations.manager.assigned": "Assigned to the selected track",
+ "articulations.manager.cc_tip": "Controller number, 0–127",
+ "articulations.manager.channel_n": "Ch {0}",
+ "articulations.manager.channel_tip": "The MIDI channel this message goes out on",
+ "articulations.manager.colour": "Colour",
+ "articulations.manager.colour_auto_tip": "Use the colour Nota gives this articulation",
+ "articulations.manager.copy_name": "{0} copy",
+ "articulations.manager.copy_tip": "Copy the selected articulation",
+ "articulations.manager.default_badge": "Default",
+ "articulations.manager.default_tip": "Notes without an articulation play this one",
+ "articulations.manager.delete": "Delete",
+ "articulations.manager.delete_confirm": "Delete \"{0}\" from your library? Tracks that use it keep their own copy.",
+ "articulations.manager.delete_failed": "Couldn't delete the map from your library: {0}",
+ "articulations.manager.delete_project_tip": "This map is only in the project, not in your library. Save it to add it.",
+ "articulations.manager.delete_tip": "Remove this map from your library; tracks that use it keep their copy",
+ "articulations.manager.details": "Details",
+ "articulations.manager.discard": "Discard",
+ "articulations.manager.discard_confirm": "Discard your unsaved changes to \"{0}\"?",
+ "articulations.manager.down_tip": "Move down",
+ "articulations.manager.drop_hint": "Drop a Cubase .expressionmap, Studio One .keyswitch or Nota .notamap file here to import it.",
+ "articulations.manager.duplicate": "Duplicate",
+ "articulations.manager.duplicate_tip": "Copy this map as a new one; tracks on the original keep it",
+ "articulations.manager.effective": "Plays at {0} ({1} track + {2} articulation)",
+ "articulations.manager.effective_disabled": "Disabled: its notes play the default articulation",
+ "articulations.manager.effective_each": "Adds to the MIDI offset of each track that uses this map",
+ "articulations.manager.empty": "No maps yet. Import a map file or create a new one.",
+ "articulations.manager.enabled": "Enabled",
+ "articulations.manager.enabled_tip": "A disabled articulation is left out of the piano roll menu and plays the default",
+ "articulations.manager.export": "Export…",
+ "articulations.manager.export_failed": "Couldn't export the map: {0}",
+ "articulations.manager.export_tip": "Save this map as a Nota .notamap file",
+ "articulations.manager.export_title": "Export articulation map",
+ "articulations.manager.exported": "Exported to {0}",
+ "articulations.manager.file_type": "Nota articulation map",
+ "articulations.manager.group": "Group",
+ "articulations.manager.group_tip": "Articulations in the same group replace each other",
+ "articulations.manager.import": "Import…",
+ "articulations.manager.import_tip": "Import a map file into your library",
+ "articulations.manager.instrument": "Instrument",
+ "articulations.manager.instrument_tip": "The library or patch this map is for",
+ "articulations.manager.key_tip": "Keyswitch note: a name like C1 or F#0, or 0–127",
+ "articulations.manager.kind_bank_lsb": "Bank LSB",
+ "articulations.manager.kind_bank_msb": "Bank MSB",
+ "articulations.manager.kind_cc": "Controller",
+ "articulations.manager.kind_keyswitch": "Keyswitch",
+ "articulations.manager.kind_program": "Program change",
+ "articulations.manager.kind_tip": "What this message is",
+ "articulations.manager.latching": "Latching",
+ "articulations.manager.lead": "Trigger lead",
+ "articulations.manager.lead_tip": "Send the switch this long before the note; the note doesn't move",
+ "articulations.manager.make_default": "Default articulation",
+ "articulations.manager.maps": "Maps",
+ "articulations.manager.meta_differs": "{0} · this project's version (differs from your library)",
+ "articulations.manager.meta_project": "{0} · in this project only",
+ "articulations.manager.momentary": "Momentary",
+ "articulations.manager.name": "Name",
+ "articulations.manager.name_tip": "The map's name",
+ "articulations.manager.new": "New",
+ "articulations.manager.new_name": "New map",
+ "articulations.manager.new_tip": "Create an empty map in your library",
+ "articulations.manager.no_group": "No group",
+ "articulations.manager.no_selection": "Select an articulation to edit it.",
+ "articulations.manager.note_channel": "Note's channel",
+ "articulations.manager.note_offset": "Note offset",
+ "articulations.manager.note_offset_tip": "Play this articulation's notes earlier (negative) or later, on top of the track's MIDI offset",
+ "articulations.manager.problem_articulation_name": "Articulation {0} needs a name.",
+ "articulations.manager.problem_default_missing": "The default articulation isn't in the map.",
+ "articulations.manager.problem_duplicate_id": "\"{0}\" shares its id with another articulation.",
+ "articulations.manager.problem_invalid_action": "\"{0}\" has a MIDI action out of range.",
+ "articulations.manager.problem_no_name": "The map needs a name.",
+ "articulations.manager.program_tip": "Program number, 0–127",
+ "articulations.manager.remove_action_tip": "Remove this message",
+ "articulations.manager.remove_tip": "Remove the selected articulation; notes that use it play the default",
+ "articulations.manager.revert": "Revert",
+ "articulations.manager.revert_tip": "Throw away your changes to this map",
+ "articulations.manager.save": "Save",
+ "articulations.manager.save_failed": "Couldn't save the map to your library: {0}",
+ "articulations.manager.save_tip": "Save to your library and update every track that uses this map",
+ "articulations.manager.saved": { "one": "Saved · {0} track updated", "other": "Saved · {0} tracks updated" },
+ "articulations.manager.short_name": "Short name",
+ "articulations.manager.short_name_tip": "A short label for tight spaces",
+ "articulations.manager.title": "Articulation maps",
+ "articulations.manager.trigger": "Trigger",
+ "articulations.manager.trigger_tip": "Latching stays until another articulation; momentary is held with the note",
+ "articulations.manager.unsaved": "Unsaved changes",
+ "articulations.manager.untitled": "Untitled map",
+ "articulations.manager.up_tip": "Move up",
+ "articulations.manager.used_on": { "one": "Used on {0} track", "other": "Used on {0} tracks" },
+ "articulations.manager.value_tip": "Value, 0–127",
+ "articulations.manager.velocity_tip": "Velocity, 0–127",
+ "articulations.menu.articulation": "Articulation",
+ "articulations.menu.clear": "Clear (play the default)",
+ "articulations.menu.clear_missing": "Clear the missing articulation",
+ "articulations.menu.default": "Default",
+ "articulations.menu.default_named": "Default · {0}",
+ "articulations.menu.locked": "These notes can't be edited here",
+ "articulations.menu.missing": "Missing",
+ "articulations.menu.missing_tip": "This note's articulation isn't in the track's map any more; it plays the default. Right-click to choose another.",
+ "articulations.menu.mixed": "Mixed",
+ "articulations.menu.no_map": "No articulation map: give the track one in the Track inspector",
+ "articulations.preview.articulations": "Articulations",
+ "articulations.preview.assign": "Assign to track",
+ "articulations.preview.errors": "Couldn't import",
+ "articulations.preview.notes": "Notes",
+ "articulations.preview.subtitle": "{0} · {1}",
+ "articulations.preview.title": "Import articulation map",
+ "articulations.preview.warnings": "Warnings",
"audio_clip_editor.a_session_slot_plays_on": "A Session slot plays on its own loop clock — launch it to play from the start",
"audio_clip_editor.beats": "Beats",
"audio_clip_editor.click_point_drag_move_right": "Click — point · drag — move · right-click — delete",
@@ -310,6 +490,7 @@
"command_palette.showing_results_for": "Showing results for ",
"command_palette.typed_in_the_other_keyboard": " · typed in the other keyboard layout",
"commands.activate_deactivate_clip": "Activate / deactivate clip",
+ "commands.articulation_maps": "Articulation maps",
"commands.auto_arm_selected_track": "Auto-arm selected track",
"commands.clip_editor_fills_the_window": "Clip editor fills the window",
"commands.command_palette": "Command palette",
@@ -2043,6 +2224,7 @@
"main.added_to_slot": "Added {0} to slot",
"main.all_return_buses_are_in": "All return buses are in use.",
"main.arrangement": "Arrangement",
+ "main.articulation_maps": "Articulation maps…",
"main.asio_driver_couldnt_start_using": "ASIO driver ‘{0}’ couldn't start — using WASAPI. {1}",
"main.audio_asio_hz_frames": "Audio: ASIO · {0} · {1:0} Hz · {2} frames",
"main.audio_device_error": "Audio device error: {0}",
diff --git a/src/managed/Nota.Application/Midi/MidiGenerators.cs b/src/managed/Nota.Application/Midi/MidiGenerators.cs
index c4778bb0..d830bc60 100644
--- a/src/managed/Nota.Application/Midi/MidiGenerators.cs
+++ b/src/managed/Nota.Application/Midi/MidiGenerators.cs
@@ -238,7 +238,7 @@ public static class MidiGenerators
}
for (int i = 0; i < stack.Count; i++)
- outp.Add(U.Note(stack[i], root.StartBeat, root.LengthBeats, root.Velocity * (1 - falloff * i / Math.Max(1, stack.Count - 1.0))));
+ outp.Add(U.Note(stack[i], root.StartBeat, root.LengthBeats, root.Velocity * (1 - falloff * i / Math.Max(1, stack.Count - 1.0)), root.ArticulationId));
}
return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));
}
diff --git a/src/managed/Nota.Application/Midi/MidiToolUtil.cs b/src/managed/Nota.Application/Midi/MidiToolUtil.cs
index 2d621e12..029b9092 100644
--- a/src/managed/Nota.Application/Midi/MidiToolUtil.cs
+++ b/src/managed/Nota.Application/Midi/MidiToolUtil.cs
@@ -24,11 +24,13 @@ public static class MidiToolUtil
return list;
}
- public static NotaNote Note(int pitch, double start, double length, double velocity) => new(
+ /// <summary>A new note. A note made from another one (an arpeggio step, an ornament, a run)
+ /// passes that note's <paramref name="articulation"/> so it plays with the same technique.</summary>
+ public static NotaNote Note(int pitch, double start, double length, double velocity, int articulation = 0) => new(
Math.Clamp(pitch, 0, 127),
start,
Math.Max(MinLength, length),
- (float)Math.Clamp(velocity, 0.01, 1.0));
+ (float)Math.Clamp(velocity, 0.01, 1.0)) { ArticulationId = Math.Max(0, articulation) };
/// <summary>Drops notes that start past the clip, trims those that overrun it, and
/// clamps pitch and velocity. Every tool ends with this so nothing has to be careful.</summary>
@@ -41,7 +43,8 @@ public static class MidiToolUtil
if (start >= lengthBeats - 1e-9) continue;
double len = Math.Min(Math.Max(MinLength, n.LengthBeats), lengthBeats - start);
var m = Note(n.Pitch, start, len, n.Velocity);
- m.ExprId = n.ExprId; // a moved / trimmed note keeps its recorded MPE
+ m.ExprId = n.ExprId; // a moved / trimmed note keeps its recorded MPE
+ m.ArticulationId = n.ArticulationId; // … and its articulation (specs/085)
outp.Add(m);
}
return Sorted(outp);
diff --git a/src/managed/Nota.Application/Midi/MidiTransforms.cs b/src/managed/Nota.Application/Midi/MidiTransforms.cs
index 75c76054..a992814e 100644
--- a/src/managed/Nota.Application/Midi/MidiTransforms.cs
+++ b/src/managed/Nota.Application/Midi/MidiTransforms.cs
@@ -54,8 +54,13 @@ public static class MidiTransforms
// Extend the chord across the octave range before ordering it.
var pitches = new List<int>();
+ var artOf = new Dictionary<int, int>(); // each step plays the articulation of the chord note it came from
foreach (int o in Enumerable.Range(0, octaves))
- foreach (var n in chord) pitches.Add(n.Pitch + o * distance);
+ foreach (var n in chord)
+ {
+ pitches.Add(n.Pitch + o * distance);
+ artOf.TryAdd(n.Pitch + o * distance, n.ArticulationId);
+ }
var seq = OrderArp(pitches, style, rng);
if (seq.Count == 0) continue;
@@ -68,9 +73,13 @@ public static class MidiTransforms
if (style == 7) // Chord — every pitch of this step's cycle together
{
int cycle = U.Mod(step, Math.Max(1, octaves));
- foreach (var n in chord) outp.Add(U.Note(n.Pitch + cycle * distance, t, len, vel * fade));
+ foreach (var n in chord) outp.Add(U.Note(n.Pitch + cycle * distance, t, len, vel * fade, n.ArticulationId));
+ }
+ else
+ {
+ int p = seq[U.Mod(step, seq.Count)];
+ outp.Add(U.Note(p, t, len, vel * fade, artOf.GetValueOrDefault(p)));
}
- else outp.Add(U.Note(seq[U.Mod(step, seq.Count)], t, len, vel * fade));
}
}
return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));
@@ -190,7 +199,7 @@ public static class MidiTransforms
else pitch = (int)Math.Round(U.Lerp(a.Pitch, b.Pitch, f));
// A run that arrives on the target early gives the landing away; step past it.
if (pitch == b.Pitch) pitch += Math.Sign(a.Pitch - b.Pitch);
- runs.Add(U.Note(pitch, runStart + k * rate, rate * gate, a.Velocity * velScale));
+ runs.Add(U.Note(pitch, runStart + k * rate, rate * gate, a.Velocity * velScale, a.ArticulationId));
}
}
outp.AddRange(runs);
@@ -241,12 +250,13 @@ public static class MidiTransforms
double len = n.LengthBeats;
double step = Math.Min(rate, len / 2);
double vel = n.Velocity * velScale;
+ int art = n.ArticulationId; // every ornament note plays the ornamented note's articulation
switch (type)
{
case 0: // Grace — a flick into the note, stealing a sliver off the front
- outp.Add(U.Note(aux, n.StartBeat, step, vel));
- outp.Add(U.Note(n.Pitch, n.StartBeat + step, len - step, n.Velocity));
+ outp.Add(U.Note(aux, n.StartBeat, step, vel, art));
+ outp.Add(U.Note(n.Pitch, n.StartBeat + step, len - step, n.Velocity, art));
break;
case 1: // Trill — alternate for the note's whole length
@@ -255,14 +265,14 @@ public static class MidiTransforms
for (double t = n.StartBeat; t < n.StartBeat + len - 1e-6; t += step, k++)
outp.Add(U.Note(k % 2 == 0 ? n.Pitch : aux,
t, Math.Min(step, n.StartBeat + len - t),
- k % 2 == 0 ? n.Velocity : vel));
+ k % 2 == 0 ? n.Velocity : vel, art));
break;
}
case 2: // Mordent — main, aux, main
- outp.Add(U.Note(n.Pitch, n.StartBeat, step, n.Velocity));
- outp.Add(U.Note(aux, n.StartBeat + step, step, vel));
- outp.Add(U.Note(n.Pitch, n.StartBeat + step * 2, Math.Max(U.MinLength, len - step * 2), n.Velocity));
+ outp.Add(U.Note(n.Pitch, n.StartBeat, step, n.Velocity, art));
+ outp.Add(U.Note(aux, n.StartBeat + step, step, vel, art));
+ outp.Add(U.Note(n.Pitch, n.StartBeat + step * 2, Math.Max(U.MinLength, len - step * 2), n.Velocity, art));
break;
case 3: // Turn — upper, main, lower, main
@@ -270,22 +280,22 @@ public static class MidiTransforms
int upper = Aux(n.Pitch, Math.Abs(interval) == 0 ? 1 : Math.Abs(interval));
int lower = Aux(n.Pitch, -(Math.Abs(interval) == 0 ? 1 : Math.Abs(interval)));
double q = Math.Min(step, len / 4);
- outp.Add(U.Note(upper, n.StartBeat, q, vel));
- outp.Add(U.Note(n.Pitch, n.StartBeat + q, q, n.Velocity));
- outp.Add(U.Note(lower, n.StartBeat + q * 2, q, vel));
- outp.Add(U.Note(n.Pitch, n.StartBeat + q * 3, Math.Max(U.MinLength, len - q * 3), n.Velocity));
+ outp.Add(U.Note(upper, n.StartBeat, q, vel, art));
+ outp.Add(U.Note(n.Pitch, n.StartBeat + q, q, n.Velocity, art));
+ outp.Add(U.Note(lower, n.StartBeat + q * 2, q, vel, art));
+ outp.Add(U.Note(n.Pitch, n.StartBeat + q * 3, Math.Max(U.MinLength, len - q * 3), n.Velocity, art));
break;
}
case 4: // Flam — a ghost a hair ahead, the main note untouched
- outp.Add(U.Note(n.Pitch, Math.Max(0, n.StartBeat - step * 0.5), step * 0.5, vel * 0.6));
+ outp.Add(U.Note(n.Pitch, Math.Max(0, n.StartBeat - step * 0.5), step * 0.5, vel * 0.6, art));
outp.Add(n);
break;
default: // Roll — ratchet the same pitch across the note
for (double t = n.StartBeat; t < n.StartBeat + len - 1e-6; t += step)
outp.Add(U.Note(n.Pitch, t, Math.Min(step, n.StartBeat + len - t) * 0.9,
- U.Lerp(n.Velocity, vel, (t - n.StartBeat) / Math.Max(1e-6, len))));
+ U.Lerp(n.Velocity, vel, (t - n.StartBeat) / Math.Max(1e-6, len)), art));
break;
}
}
diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.cs
index 20fa5334..aa71e186 100644
--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs
+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs
@@ -57,6 +57,7 @@ public static class CommandCatalog
C("view.mixer", Loc.T("commands.show_mixer"), Loc.T("commands.view"), Shortcut.CmdShift('M'), "faders channels"),
C("view.mixerFloat", Loc.T("commands.mixer_in_its_own_window"), Loc.T("commands.view"), "", "dock undock float pop out mixer window"),
C("view.connectPhone", Loc.T("commands.connect_phone"), Loc.T("commands.view"), "", "remote mobile qr"),
+ C("view.articulationMaps", Loc.T("commands.articulation_maps"), Loc.T("commands.view"), "", "expression map keyswitch articulation manager library"),
C("view.toggleBrowser", Loc.T("commands.toggle_browser"), Loc.T("commands.view"), "", "library sidebar"),
C("view.toggleDetail", Loc.T("commands.toggle_detail_panel"), Loc.T("commands.view"), "", "devices clip"),
C("view.maximizeDetail", Loc.T("commands.clip_editor_fills_the_window"), Loc.T("commands.view"), Shortcut.CmdShift('F'), "maximize maximise full detail panel piano roll restore split"),
diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.cs
index 4e4d33a7..a5f47393 100644
--- a/src/managed/Nota.Application/Settings.cs
+++ b/src/managed/Nota.Application/Settings.cs
@@ -193,6 +193,9 @@ public sealed class Settings
/// <summary>Piano-roll note audition (#46): notes sound while they are placed, clicked or
/// dragged. The speaker chip in the clip editor's header; on by default.</summary>
public bool PianoRollAudition { get; set; } = true;
+ /// <summary>Piano-roll notes in their articulation's colour instead of the track's (specs/085,
+ /// FR-015). The palette chip in the clip editor's header; off by default.</summary>
+ public bool PianoRollNoteColorByArticulation { get; set; }
/// <summary>Logical lane heights keyed by velocity, MPE dimension or MIDI controller.</summary>
public Dictionary<string, double> PianoRollLaneHeights { get; set; } = new();
/// <summary>Shift + wheel over a note in the piano roll (specs/063): false — wheel up raises
diff --git a/src/managed/Nota.Infrastructure/Articulations/ArticulationLibraryStore.cs b/src/managed/Nota.Infrastructure/Articulations/ArticulationLibraryStore.cs
new file mode 100644
index 00000000..91c5e146
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Articulations/ArticulationLibraryStore.cs
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// IArticulationLibrary over a folder of Nota map files (specs/085): <data>/articulations/<id>.notamap.
+// The file name comes from the map id, never from its name, so a rename doesn't move the file and a
+// name can't escape the folder. Writes go to a temp file first, then replace the old one.
+
+using System.Text;
+using Nota.Application.Articulations;
+
+namespace Nota.Infrastructure.Articulations;
+
+public sealed class ArticulationLibraryStore : IArticulationLibrary
+{
+ private readonly string _dir;
+ private List<string> _unreadable = new();
+
+ /// <param name="dir">The folder; default <c>NotaPaths.SubDir("articulations")</c>.</param>
+ public ArticulationLibraryStore(string? dir = null) => _dir = dir ?? NotaPaths.SubDir("articulations");
+
+ public string Folder => _dir;
+ public IReadOnlyList<string> Unreadable => _unreadable;
+
+ public IReadOnlyList<ArticulationMap> List()
+ {
+ var maps = new List<ArticulationMap>();
+ var bad = new List<string>();
+ if (Directory.Exists(_dir))
+ foreach (var f in Directory.EnumerateFiles(_dir, "*" + ArticulationMapFile.Extension))
+ {
+ var r = ArticulationMapFile.ReadFile(f);
+ if (r.Map is { } m) maps.Add(m); else bad.Add(f);
+ }
+ _unreadable = bad;
+ return maps.OrderBy(m => m.Name, StringComparer.CurrentCultureIgnoreCase).ThenBy(m => m.Id, StringComparer.Ordinal).ToList();
+ }
+
+ public ArticulationMap? Get(string mapId)
+ {
+ if (PathOf(mapId) is not { } p || !File.Exists(p)) return null;
+ return ArticulationMapFile.ReadFile(p).Map;
+ }
+
+ public void Save(ArticulationMap map)
+ {
+ ArgumentNullException.ThrowIfNull(map);
+ var path = PathOf(map.Id) ?? throw new ArgumentException("Not a valid articulation map id.", nameof(map));
+ Directory.CreateDirectory(_dir);
+ string tmp = path + ".tmp";
+ File.WriteAllText(tmp, ArticulationMapFile.Write(map), new UTF8Encoding(false));
+ File.Move(tmp, path, overwrite: true); // never leave a half-written map behind
+ }
+
+ public bool Delete(string mapId)
+ {
+ if (PathOf(mapId) is not { } p || !File.Exists(p)) return false;
+ File.Delete(p);
+ return true;
+ }
+
+ // Ids are 32 hex digits from Guid "N"; anything else (a path, "..", a hostile id from a file) is refused.
+ private string? PathOf(string? mapId) =>
+ mapId is { Length: > 0 and <= 64 } && mapId.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')
+ ? Path.Combine(_dir, mapId + ArticulationMapFile.Extension)
+ : null;
+}
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 0abf5e60..1c82cb11 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -345,6 +345,24 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_track_get_midi_source")]
internal static partial int TrackGetMidiSource(IntPtr engine, int trackId);
+ [LibraryImport(Lib, EntryPoint = "nota_track_set_midi_offset_ms")]
+ internal static partial NotaResult TrackSetMidiOffsetMs(IntPtr engine, int trackId, double ms);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_get_midi_offset_ms")]
+ internal static partial double TrackGetMidiOffsetMs(IntPtr engine, int trackId);
+
+ // --- articulation maps (specs/085) ---
+ [LibraryImport(Lib, EntryPoint = "nota_track_set_articulation_map")]
+ internal static partial NotaResult TrackSetArticulationMap(IntPtr engine, int trackId, int defaultId,
+ NotaArticulationEntry[] entries, int entryCount, NotaArticulationAction[] actions, int actionCount,
+ byte[] mapJson, int mapJsonLen);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_clear_articulation_map")]
+ internal static partial NotaResult TrackClearArticulationMap(IntPtr engine, int trackId);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_get_articulation_map_json")]
+ internal static partial int TrackGetArticulationMapJson(IntPtr engine, int trackId, byte[]? output, int maxLen);
+
// --- freeze (M7) ---
[LibraryImport(Lib, EntryPoint = "nota_track_freeze_begin")]
internal static partial long TrackFreezeBegin(IntPtr engine, int trackId, double lengthBeats);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index f6d48955..13cd7562 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -319,6 +319,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_timed_events_selftest")]
internal static partial int TimedEventsSelfTest(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_articulation_selftest")]
+ internal static partial int ArticulationSelfTest(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_cpu_load")]
internal static partial float CpuLoad(IntPtr engine);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index 927b3e42..1ad38fb0 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -558,6 +558,40 @@ public sealed partial class NotaEngine
public void SetTrackMidiSource(int trackId, int sourceTrackId)
{ ThrowIfDisposed(); NativeMethods.TrackSetMidiSource(_handle, trackId, sourceTrackId); }
+ /// <summary>Sets the track's MIDI playback offset in ms (negative = earlier; playback only).</summary>
+ public void SetTrackMidiOffsetMs(int trackId, double ms)
+ { ThrowIfDisposed(); NativeMethods.TrackSetMidiOffsetMs(_handle, trackId, ms); }
+
+ /// <summary>The track's MIDI playback offset in ms (negative = earlier).</summary>
+ public double GetTrackMidiOffsetMs(int trackId)
+ { ThrowIfDisposed(); return NativeMethods.TrackGetMidiOffsetMs(_handle, trackId); }
+
+ /// <inheritdoc/>
+ public bool SetTrackArticulationMap(int trackId, int defaultId, NotaArticulationEntry[] entries, NotaArticulationAction[] actions, string mapJson)
+ {
+ ThrowIfDisposed();
+ ArgumentNullException.ThrowIfNull(entries);
+ ArgumentNullException.ThrowIfNull(actions);
+ var json = System.Text.Encoding.UTF8.GetBytes(mapJson ?? "");
+ return NativeMethods.TrackSetArticulationMap(_handle, trackId, defaultId, entries, entries.Length,
+ actions, actions.Length, json, json.Length) == NativeMethods.NotaResult.Ok;
+ }
+
+ /// <inheritdoc/>
+ public bool ClearTrackArticulationMap(int trackId)
+ { ThrowIfDisposed(); return NativeMethods.TrackClearArticulationMap(_handle, trackId) == NativeMethods.NotaResult.Ok; }
+
+ /// <inheritdoc/>
+ public string? GetTrackArticulationMapJson(int trackId)
+ {
+ ThrowIfDisposed();
+ int n = NativeMethods.TrackGetArticulationMapJson(_handle, trackId, null, 0);
+ if (n <= 0) return null;
+ var buf = new byte[n];
+ int got = NativeMethods.TrackGetArticulationMapJson(_handle, trackId, buf, n);
+ return got == n ? System.Text.Encoding.UTF8.GetString(buf) : null; // changed in between: ask again
+ }
+
/// <summary>Gets an instrument track's MIDI input source track id (-1 = off).</summary>
public int GetTrackMidiSource(int trackId)
{ ThrowIfDisposed(); return NativeMethods.TrackGetMidiSource(_handle, trackId); }
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index ce377701..9a3874a1 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -333,6 +333,11 @@ public sealed partial class NotaEngine : IAudioEngine
public bool TimedEventsSelfTest()
{ ThrowIfDisposed(); return NativeMethods.TimedEventsSelfTest(_handle) != 0; }
+ /// <summary>Device-free self-test (specs/085): articulation scheduling and delivery. 0 = pass,
+ /// else the number of the check that failed (see Engine::articulationSelfTest).</summary>
+ public int ArticulationSelfTest()
+ { ThrowIfDisposed(); return NativeMethods.ArticulationSelfTest(_handle); }
+
/// <summary>Smoothed real-time DSP load, 0..1 (render time / block budget).</summary>
public float CpuLoad
{ get { ThrowIfDisposed(); return NativeMethods.CpuLoad(_handle); } }
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index 87eacdca..6fcbe7a6 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -118,6 +118,10 @@ public static class ProjectMigrations
// v28 -> v29: audio tracks gain Takes and audio clips TakeId (take lanes, specs/067).
// Absent in v28 documents = no takes, every clip a plain clip — no-op.
new Migration(28, _ => { }),
+
+ // 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, _ => { }),
};
/// <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.cs
index 1b9e9356..cdd1ad26 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -13,6 +13,7 @@
using System.Collections.Generic;
using System.Text.Json;
+using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
namespace Nota.Infrastructure;
@@ -133,6 +134,11 @@ public sealed class TrackDto
public int? InputChannels { get; set; }
// MIDI routing source ("MIDI In") as a doc-list index (survives id reassignment), or -1 = off.
public int MidiFrom { get; set; } = -1;
+ // MIDI playback offset in ms (negative = earlier; playback only, notes don't move). Omitted = 0. v30.
+ public double? MidiOffsetMs { get; set; }
+ // The track's articulation map (specs/085), embedded as Nota's map JSON
+ // (contracts/nota-articulation-map-file.md). Omitted = none. v30.
+ public JsonObject? ArticulationMap { get; set; }
public float[] Sends { get; set; } = new float[4];
public InstrumentDto? Instrument { get; set; }
public List<MidiDeviceDto> MidiEffects { get; set; } = new(); // MIDI FX chain, before the instrument
@@ -575,9 +581,16 @@ public sealed class NoteDto
/// <summary>Recorded MPE, when the note has any (omitted otherwise).</summary>
public NoteMpeDto? Mpe { get; set; }
+ /// <summary>The note's articulation: an id in its track's articulation map (omitted = none). v30.</summary>
+ public int? Articulation { get; set; }
+
public NoteDto() { }
- public NoteDto(NotaNote n) { Pitch = n.Pitch; Start = n.StartBeat; Length = n.LengthBeats; Velocity = n.Velocity; }
- public NotaNote ToNote() => new(Pitch, Start, Length, Velocity);
+ public NoteDto(NotaNote n)
+ {
+ Pitch = n.Pitch; Start = n.StartBeat; Length = n.LengthBeats; Velocity = n.Velocity;
+ Articulation = n.ArticulationId > 0 ? n.ArticulationId : null;
+ }
+ public NotaNote ToNote() => new(Pitch, Start, Length, Velocity) { ArticulationId = Articulation is > 0 ? Articulation.Value : 0 };
}
/// <summary>A note's recorded expression: per dimension a flat [beat, value, beat, value…] list,
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 04376ae9..e430d219 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -38,7 +38,8 @@ public sealed class ProjectService
/// 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.
/// v29 (specs/067) adds Takes on audio tracks and TakeId on audio clips.
- public const int CurrentFormatVersion = 29;
+ /// v30 (specs/085) adds MidiOffsetMs and ArticulationMap on tracks and Articulation on notes.
+ public const int CurrentFormatVersion = 30;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -117,6 +118,8 @@ public sealed class ProjectService
InputChannels = (int)engine.GetTrackInputChannels(ti.Id),
MidiFrom = engine.GetTrackMidiSource(ti.Id) is var mfrom && mfrom > 0
&& idToIndex.TryGetValue(mfrom, out var mix) ? mix : -1, // source → doc index, else off
+ MidiOffsetMs = engine.GetTrackMidiOffsetMs(ti.Id) is var moff && moff != 0.0 ? moff : null, // v30; 0 = omitted
+ ArticulationMap = ti.IsInstrument ? CaptureArticulationMap(engine, ti.Id, warnings) : null, // v30
};
for (int b = 0; b < t.Sends.Length; b++) t.Sends[b] = engine.GetTrackSend(ti.Id, b);
@@ -751,6 +754,8 @@ public sealed class ProjectService
if (t.Monitor) monitorDeferred.Add((id, true)); // after record inputs resolve
engine.SetTrackInputChannels(id, (InputChannels)(t.InputChannels ?? 0)); // older files: the stereo pair
if (t.MidiFrom >= 0) midiFromDeferred.Add((id, t.MidiFrom)); // resolve after all tracks exist
+ if (t.MidiOffsetMs is { } offMs && double.IsFinite(offMs)) engine.SetTrackMidiOffsetMs(id, offMs); // v30; absent = 0, engine clamps
+ if (t.Type == 1 && t.ArticulationMap is { } artMap) ApplyArticulationMap(engine, id, artMap, warnings); // v30
for (int b = 0; b < t.Sends.Length && b < 4; b++) engine.SetTrackSend(id, b, t.Sends[b]);
var ccPaths = new List<(int mi, int chain, int slot)>(); // CC targets inside racks: after the devices
@@ -1228,6 +1233,25 @@ public sealed class ProjectService
// A note's recorded MPE goes inline with it (notes sharing one curve, like a duplicate,
// each carry a copy).
+ // --- articulation maps (specs/085) ------------------------------------------------------
+
+ private static JsonObject? CaptureArticulationMap(IAudioEngine engine, int trackId, List<string> warnings)
+ {
+ if (engine.GetTrackArticulationMapJson(trackId) is not { Length: > 0 } json) return null;
+ try { return JsonNode.Parse(json) as JsonObject; }
+ catch (JsonException) { warnings.Add("A track's articulation map couldn't be saved (it isn't valid JSON)."); return null; }
+ }
+
+ // A map that can't be read, or that the engine refuses, is a warning: the project still opens.
+ private static void ApplyArticulationMap(IAudioEngine engine, int trackId, JsonObject node, List<string> warnings)
+ {
+ var read = Nota.Application.Articulations.ArticulationMapFile.Read(node.ToJsonString(), "");
+ foreach (var m in read.Warnings) warnings.Add(m.Text);
+ if (read.Map is not { } map) return;
+ if (!Nota.Application.Articulations.ArticulationMapAssignment.Assign(engine, trackId, map))
+ warnings.Add($"Couldn't restore the articulation map \"{map.Name}\".");
+ }
+
private static NoteDto[] ToDtos(IAudioEngine engine, NotaNote[] notes)
{
var arr = new NoteDto[notes.Length];
diff --git a/src/managed/Nota.Mcp/Tools/MidiTools.cs b/src/managed/Nota.Mcp/Tools/MidiTools.cs
index 93ed3825..d1e7ccbf 100644
--- a/src/managed/Nota.Mcp/Tools/MidiTools.cs
+++ b/src/managed/Nota.Mcp/Tools/MidiTools.cs
@@ -18,10 +18,12 @@ public sealed class MidiTools(IAudioEngine engine, IEngineDispatch dispatch, IAr
[property: Description("MIDI note number, 60 = middle C")] int Pitch,
[property: Description("Start in beats, relative to the clip")] double Start,
[property: Description("Length in beats")] double Length,
- [property: Description("Velocity 0..1")] float Velocity);
+ [property: Description("Velocity 0..1")] float Velocity,
+ [property: Description("Articulation id in the track's articulation map, 0 = none. Keep the value get_clip_notes returned when you write a note back.")] int Articulation = 0);
- private static NotaNote ToEngine(Note n) => new(n.Pitch, n.Start, n.Length, Math.Clamp(n.Velocity, 0f, 1f));
- private static Note FromEngine(NotaNote n) => new(n.Pitch, n.StartBeat, n.LengthBeats, n.Velocity);
+ // The articulation travels both ways, so a get → edit → set round trip keeps it (specs/085).
+ private static NotaNote ToEngine(Note n) => new(n.Pitch, n.Start, n.Length, Math.Clamp(n.Velocity, 0f, 1f)) { ArticulationId = Math.Max(0, n.Articulation) };
+ private static Note FromEngine(NotaNote n) => new(n.Pitch, n.StartBeat, n.LengthBeats, n.Velocity, n.ArticulationId);
[McpServerTool(Name = "add_midi_clip"), Description("Add an empty MIDI clip to an instrument track at startBeat for lengthBeats. Returns the clip index.")]
public Task<int> AddMidiClip(int trackId, double startBeat, double lengthBeats)
diff --git a/src/managed/Nota.Mcp/Tools/SessionTools.cs b/src/managed/Nota.Mcp/Tools/SessionTools.cs
index c85470ef..74fc9b29 100644
--- a/src/managed/Nota.Mcp/Tools/SessionTools.cs
+++ b/src/managed/Nota.Mcp/Tools/SessionTools.cs
@@ -18,7 +18,8 @@ namespace Nota.Mcp.Tools;
public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh)
: EngineTools(engine, dispatch, refresh)
{
- public sealed record Note(int Pitch, double Start, double Length, float Velocity);
+ public sealed record Note(int Pitch, double Start, double Length, float Velocity,
+ [property: Description("Articulation id in the track's articulation map, 0 = none. Keep the value get_session_notes returned when you write a note back.")] int Articulation = 0);
public sealed record FollowAction(string Action, int Chance);
public sealed record Slot(int TrackId, int Scene, string State, double LengthBeats, string Name, int Color,
string LaunchMode, double? QuantBeats, bool Legato, bool Loop, float VelocityAmount,
@@ -33,8 +34,9 @@ public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch,
private static readonly string[] Actions = { "none", "stop", "again", "previous", "next", "first", "last", "any", "other", "jump" };
private static string StateName(int s) => s switch { 5 => "record pending", 4 => "recording", 3 => "playing", 2 => "queued", 1 => "filled", _ => "empty" };
- private static NotaNote ToEngine(Note n) => new(n.Pitch, n.Start, n.Length, Math.Clamp(n.Velocity, 0f, 1f));
- private static Note FromEngine(NotaNote n) => new(n.Pitch, n.StartBeat, n.LengthBeats, n.Velocity);
+ // The articulation travels both ways, so a get → edit → set round trip keeps it (specs/085).
+ private static NotaNote ToEngine(Note n) => new(n.Pitch, n.Start, n.Length, Math.Clamp(n.Velocity, 0f, 1f)) { ArticulationId = Math.Max(0, n.Articulation) };
+ private static Note FromEngine(NotaNote n) => new(n.Pitch, n.StartBeat, n.LengthBeats, n.Velocity, n.ArticulationId);
private static int Parse(string? value, string[] names, string what)
{
diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txt
index 99a44653..6dff4491 100644
--- a/src/native/nota.engine/CMakeLists.txt
+++ b/src/native/nota.engine/CMakeLists.txt
@@ -131,6 +131,8 @@ set(NOTA_ENGINE_SOURCES
src/devices/midi_fx/MidiNoteLength.cpp
src/devices/midi_fx/MidiVelocity.cpp
src/devices/midi_fx/MidiRandom.cpp
+ src/engine/ArticulationSchedule.cpp
+ src/engine/ArticulationTable.cpp
src/engine/Graph.cpp
src/engine/Track.cpp
src/engine/Transport.cpp
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 39b2712b..d1c6cb23 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -48,6 +48,8 @@ typedef struct NotaNoteData {
float velocity; /* 0..1 */
int32_t expr_id; /* recorded MPE (nota_note_expr_*), 0 = none. Keep it when you move,
* copy or resize the note — the expression travels with it. */
+ int32_t articulation_id; /* stable articulation id in the track's articulation map, 0 = none.
+ * Keep it when you move, copy or resize the note. */
} NotaNoteData;
/* One breakpoint of a note's recorded expression (MPE). dim: 0 bend (semitones), 1 pressure
@@ -376,6 +378,10 @@ NOTA_API int32_t nota_engine_drum_rack_selftest(NotaEngine* engine);
* events renders once per block with every event at its sample offset, while a built-in
* still renders in segments between events. */
NOTA_API int32_t nota_engine_timed_events_selftest(NotaEngine* engine);
+/* Device-free self-test (specs/085): articulation scheduling block by block (map order, latching
+ * dedupe, offsets and leads, momentary holds, chase on seek and loop wrap, seam releases, overflow)
+ * and delivery ahead of the note on its channel. 0 = pass, else the number of the failed check. */
+NOTA_API int32_t nota_engine_articulation_selftest(NotaEngine* engine);
/* Plugin-parameter automation (M9-B, target 3). Device-free structural self-test;
* the plugin-param introspection + lane-add C ABI arrives in B2. */
NOTA_API int32_t nota_engine_plugin_automation_selftest(NotaEngine* engine);
@@ -1571,6 +1577,43 @@ NOTA_API void nota_engine_push_monitor_frames(NotaEngine* engine, const fl
* (source_track_id = -1 turns it off). */
NOTA_API NotaResult nota_track_set_midi_source(NotaEngine* engine, int32_t track_id, int32_t source_track_id);
NOTA_API int32_t nota_track_get_midi_source(NotaEngine* engine, int32_t track_id);
+/* Track-level MIDI playback offset in ms (negative = earlier). Non-destructive; clamped to +-2000. */
+NOTA_API NotaResult nota_track_set_midi_offset_ms(NotaEngine* engine, int32_t track_id, double ms);
+NOTA_API double nota_track_get_midi_offset_ms(NotaEngine* engine, int32_t track_id);
+
+/* Articulation maps (specs/085). The UI compiles a map into a flat table: articulations sorted
+ * by id, each pointing at a range of an ordered action array. Disabled articulations are left
+ * out (a note asking for one plays the default). */
+typedef struct NotaArticulationEntry {
+ int32_t id; /* > 0, unique, strictly ascending in the array */
+ int32_t trigger_mode; /* 0 latching (sent on change, stays in force), 1 momentary (held with each note) */
+ double offset_ms; /* added to the track's MIDI offset; within +-2000 */
+ double lead_ms; /* the actions go out this long before the (offset) note; 0..2000 */
+ int32_t action_start; /* first action in the action array */
+ int32_t action_count;
+} NotaArticulationEntry;
+
+typedef struct NotaArticulationAction {
+ int32_t kind; /* 0 keyswitch, 1 control change, 2 program change, 3 bank select MSB, 4 bank select LSB */
+ int32_t channel; /* 0 = the note's own, 1..16 explicit */
+ int32_t data1; /* keyswitch pitch / CC number / program, 0..127 */
+ int32_t data2; /* keyswitch velocity / CC or bank value, 0..127 */
+} NotaArticulationAction;
+
+/* Gives an instrument track its articulation map: the compiled table plus the map file as opaque
+ * JSON (UTF-8, saved with the project and restored by undo). One undo step. default_id 0 = none.
+ * NOTA_ERR_INVALID_ARG, with nothing changed, for: no such instrument track, ids not > 0 and
+ * strictly ascending, an action range outside the array, a kind/channel/data value out of range,
+ * an offset or lead out of range or not finite, a default_id that is not 0 or an entry's id. */
+NOTA_API NotaResult nota_track_set_articulation_map(NotaEngine* engine, int32_t track_id, int32_t default_id,
+ const NotaArticulationEntry* entries, int32_t entry_count,
+ const NotaArticulationAction* actions, int32_t action_count,
+ const char* map_json, int32_t map_json_len);
+/* Removes the track's map; notes keep their articulation ids. One undo step (none when there was no map). */
+NOTA_API NotaResult nota_track_clear_articulation_map(NotaEngine* engine, int32_t track_id);
+/* Copies the stored map JSON into out (no terminator) and returns its length in bytes; out = NULL or
+ * max_len too small returns the length without copying. 0 = no map. */
+NOTA_API int32_t nota_track_get_articulation_map_json(const NotaEngine* engine, int32_t track_id, char* out, int32_t max_len);
/* ---- Freeze (M7) ---------------------------------------------------------- */
/* Bounce a track's post-device, pre-fader audio to a buffer and play it back in
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
index abd6a7f5..5e5caf4e 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
+++ b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
@@ -6,6 +6,7 @@
#include "PluginInstrument.h"
+#include "engine/ArticulationSchedule.h"
#include "engine/MidiController.h"
#include "dsp/math/SimdAudio.h"
@@ -15,8 +16,12 @@ namespace hosting {
PluginInstrument::PluginInstrument(std::unique_ptr<juce::AudioPluginInstance> p, double sr, int maxBlock)
: plugin_(std::move(p)), maxBlock_(juce::jmin(maxBlock, kPluginMaxBlock)) {
- pending_.ensureSize(8192);
- piece_.ensureSize(8192);
+ // Room reserved up front so the audio thread doesn't grow the buffers. On top of the notes' room,
+ // a block's articulation MIDI (specs/085): at most kMaxBlockArt messages, 9 bytes each in a
+ // MidiBuffer (sample position, size, 3 data bytes).
+ constexpr int kArtBytes = nota::kMaxBlockArt * 9;
+ pending_.ensureSize(8192 + kArtBytes);
+ piece_.ensureSize(8192 + kArtBytes);
if (plugin_) name_ = plugin_->getName().toStdString(); // cache for displayName()
// VST3 process calls may run on audio workers. All MIDI, channel storage and
// playhead state belong to this instance; the engine joins before the next
@@ -40,30 +45,39 @@ void PluginInstrument::setSampleRate(double sr) {
prepare(sr);
}
+// Every engine-driven event goes out on chan(): channel 1, or an articulation's explicit channel
+// (specs/085). The editor window's own keyboard notes (render) stay on channel 1.
void PluginInstrument::noteOn(int32_t pitch, float velocity) {
- pending_.addEvent(juce::MidiMessage::noteOn(1, pitch, (float)velocity), eventOffset);
+ pending_.addEvent(juce::MidiMessage::noteOn(chan(), pitch, (float)velocity), eventOffset);
}
void PluginInstrument::noteOff(int32_t pitch) {
- pending_.addEvent(juce::MidiMessage::noteOff(1, pitch), eventOffset);
+ pending_.addEvent(juce::MidiMessage::noteOff(chan(), pitch), eventOffset);
}
void PluginInstrument::allNotesOff() {
- pending_.addEvent(juce::MidiMessage::allNotesOff(1), eventOffset);
+ // A flush (stop, seek, a voice cut): channel 1 as always, plus any channel an articulation
+ // sent on, so a note held on it can't hang. A plug-in never driven off channel 1 sees one message.
+ for (int c = 1; c <= 16; ++c)
+ if ((usedChannels_ >> (c - 1)) & 1u) pending_.addEvent(juce::MidiMessage::allNotesOff(c), eventOffset);
}
void PluginInstrument::noteExpression(int32_t pitch, int32_t dim, float value) {
- if (pitch >= 0 && dim == 1) pending_.addEvent(juce::MidiMessage::aftertouchChange(1, pitch, u7(value)), eventOffset);
+ if (pitch >= 0 && dim == 1) pending_.addEvent(juce::MidiMessage::aftertouchChange(chan(), pitch, u7(value)), eventOffset);
+}
+
+void PluginInstrument::programChange(int32_t program) {
+ if (program >= 0 && program < 128) pending_.addEvent(juce::MidiMessage::programChange(chan(), program), eventOffset);
}
void PluginInstrument::controller(int32_t ctl, float value) {
if (ctl == nota::kCtlPitchWheel)
pending_.addEvent(
- juce::MidiMessage::pitchWheel(1, juce::jlimit(0, 16383, (int)std::lround((value + 1.0f) * 8191.5f))), eventOffset);
+ juce::MidiMessage::pitchWheel(chan(), juce::jlimit(0, 16383, (int)std::lround((value + 1.0f) * 8191.5f))), eventOffset);
else if (ctl == nota::kCtlChannelPressure)
- pending_.addEvent(juce::MidiMessage::channelPressureChange(1, u7(value)), eventOffset);
+ pending_.addEvent(juce::MidiMessage::channelPressureChange(chan(), u7(value)), eventOffset);
else if (ctl >= 0 && ctl < 128)
- pending_.addEvent(juce::MidiMessage::controllerEvent(1, ctl, u7(value)), eventOffset);
+ pending_.addEvent(juce::MidiMessage::controllerEvent(chan(), ctl, u7(value)), eventOffset);
}
void PluginInstrument::render(float* out, int32_t frames) {
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
index 060daefa..d337c42d 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
+++ b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
@@ -42,6 +42,8 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
void allNotesOff() override;
void noteExpression(int32_t pitch, int32_t dim, float value) override;
void controller(int32_t ctl, float value) override;
+ void programChange(int32_t program) override;
+ bool takesArticulations() const override { return true; } // Kontakt & co. switch on keyswitches (specs/085)
void render(float* out, int32_t frames) override;
void setTransportInfo(const nota::TransportInfo& ti) override { playHead_.info = ti; }
@@ -79,6 +81,13 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
std::shared_ptr<nota::Instrument> clone() const override;
static int u7(float v) { return juce::jlimit(0, 127, (int)std::lround(v * 127.0f)); }
+ // The MIDI channel (1..16) of the event being sent: the articulation's explicit one, else 1.
+ // Remembers it, so allNotesOff reaches every channel used and only those. Audio thread only.
+ int chan() {
+ const int c = eventChannel >= 1 && eventChannel <= 16 ? eventChannel : 1;
+ usedChannels_ |= 1u << (c - 1);
+ return c;
+ }
private:
void audioProcessorParameterChanged(juce::AudioProcessor*, int index, float) override;
@@ -91,6 +100,7 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
NotaPlayHead playHead_; // declared first: outlives plugin_ (which points at it)
std::unique_ptr<juce::AudioPluginInstance> plugin_;
+ uint32_t usedChannels_ = 1u; // bit c-1 = channel c has been sent on (chan()); audio thread only
juce::AudioBuffer<float> storage_;
std::vector<float> spare_; // the channels past storage_ (see pluginChannelPtrs)
int chanFloor_ = 0; // pluginChannelPtrs floor (see minProcessChannels)
diff --git a/src/native/nota.engine/src/abi/nota_engine_automation.cpp b/src/native/nota.engine/src/abi/nota_engine_automation.cpp
index 8aee0b8d..fd8c2758 100644
--- a/src/native/nota.engine/src/abi/nota_engine_automation.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_automation.cpp
@@ -29,6 +29,9 @@ int32_t nota_engine_rack_device_selftest(NotaEngine* e) {
int32_t nota_engine_timed_events_selftest(NotaEngine* e) {
return (e && ENG(e)->timedEventsSelfTest()) ? 1 : 0;
}
+int32_t nota_engine_articulation_selftest(NotaEngine* e) {
+ return e ? ENG(e)->articulationSelfTest() : -1;
+}
int32_t nota_engine_drum_rack_selftest(NotaEngine* e) {
return (e && ENG(e)->drumRackSelfTest()) ? 1 : 0;
}
diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cpp
index e82b68be..12cdabde 100644
--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp
@@ -755,6 +755,30 @@ NotaResult nota_track_set_midi_source(NotaEngine* e, int32_t track_id, int32_t s
ENG(e)->setTrackMidiSource(track_id, source_track_id);
return NOTA_OK;
}
+NotaResult nota_track_set_midi_offset_ms(NotaEngine* e, int32_t track_id, double ms) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setTrackMidiOffsetMs(track_id, ms);
+ return NOTA_OK;
+}
+double nota_track_get_midi_offset_ms(NotaEngine* e, int32_t track_id) {
+ return e ? CENG(e)->trackMidiOffsetMs(track_id) : 0.0;
+}
+NotaResult nota_track_set_articulation_map(NotaEngine* e, int32_t track_id, int32_t default_id,
+ const NotaArticulationEntry* entries, int32_t entry_count, const NotaArticulationAction* actions, int32_t action_count,
+ const char* map_json, int32_t map_json_len) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->setTrackArticulationMap(
+ track_id, default_id, entries, entry_count, actions, action_count, map_json, map_json_len)
+ ? NOTA_OK
+ : NOTA_ERR_INVALID_ARG;
+}
+NotaResult nota_track_clear_articulation_map(NotaEngine* e, int32_t track_id) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->clearTrackArticulationMap(track_id) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
+int32_t nota_track_get_articulation_map_json(const NotaEngine* e, int32_t track_id, char* out, int32_t max_len) {
+ return e ? CENG(e)->trackArticulationMapJson(track_id, out, max_len) : 0;
+}
int32_t nota_track_get_midi_source(NotaEngine* e, int32_t track_id) {
return e ? CENG(e)->trackMidiSource(track_id) : -1;
}
diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.h
index a6a2f97c..828a4acf 100644
--- a/src/native/nota.engine/src/devices/Instrument.h
+++ b/src/native/nota.engine/src/devices/Instrument.h
@@ -52,6 +52,17 @@ class Instrument {
// sample offset within the next render(). Outside that it stays 0. Audio thread only.
virtual bool takesTimedEvents() const { return false; }
int32_t eventOffset = 0;
+ // The MIDI channel of the next event, like eventOffset: 0 = the default (channel 1), 1..16 an
+ // articulation's explicit channel (specs/085). The engine sets it before an articulation action
+ // and puts it back to 0 after. Only a hosted plug-in reads it. Audio thread only.
+ int32_t eventChannel = 0;
+ // A MIDI program change (an articulation action, specs/085), 0..127, at eventOffset on
+ // eventChannel. Built-in instruments have no programs and ignore it.
+ virtual void programChange(int32_t /*program*/) {}
+ // Whether articulation MIDI (keyswitch notes, controllers, programs) is meant for this
+ // instrument (specs/085, FR-024). A built-in would play a keyswitch as a note, so it says no
+ // and the engine sends it nothing; a hosted plug-in, or a rack holding one, says yes.
+ virtual bool takesArticulations() const { return false; }
// Note events (applied at segment boundaries by the engine for sample accuracy, or at
// eventOffset — see takesTimedEvents).
diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp b/src/native/nota.engine/src/devices/racks/RackInstrument.cpp
index d513b896..bc1285a2 100644
--- a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp
+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.cpp
@@ -335,7 +335,30 @@ void RackInstrument::controller(int32_t ctl, float value) {
RackState* st = live();
if (!st) return;
for (auto& c : st->chains)
- if (c.instrument) c.instrument->controller(ctl, value);
+ if (c.instrument) {
+ c.instrument->eventChannel = eventChannel; // an articulation's channel reaches the chain (specs/085)
+ c.instrument->controller(ctl, value);
+ c.instrument->eventChannel = 0;
+ }
+}
+
+void RackInstrument::programChange(int32_t program) {
+ RackState* st = live();
+ if (!st) return;
+ for (auto& c : st->chains)
+ if (c.instrument) {
+ c.instrument->eventChannel = eventChannel;
+ c.instrument->programChange(program);
+ c.instrument->eventChannel = 0;
+ }
+}
+
+bool RackInstrument::takesArticulations() const {
+ RackState* st = live();
+ if (!st) return false;
+ for (auto& c : st->chains)
+ if (c.instrument && c.instrument->takesArticulations()) return true;
+ return false;
}
bool RackInstrument::supportsMpe() const {
diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.h b/src/native/nota.engine/src/devices/racks/RackInstrument.h
index 4d4428c7..302fb5a4 100644
--- a/src/native/nota.engine/src/devices/racks/RackInstrument.h
+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.h
@@ -55,6 +55,10 @@ class RackInstrument : public Instrument, public RackCore {
void noteExpression(int32_t pitch, int32_t dim, float value) override;
// Controllers too: every chain hears the pedal and the wheels, like live input.
void controller(int32_t ctl, float value) override;
+ // An articulation's program change (specs/085) reaches every chain, on its channel.
+ void programChange(int32_t program) override;
+ // True when a chain holds an instrument that takes articulation MIDI (a hosted plug-in).
+ bool takesArticulations() const override;
bool supportsMpe() const override;
// ---- render: sum every audible chain into `out` -------------------------
diff --git a/src/native/nota.engine/src/engine/ArticulationSchedule.cpp b/src/native/nota.engine/src/engine/ArticulationSchedule.cpp
new file mode 100644
index 00000000..c23f340c
--- /dev/null
+++ b/src/native/nota.engine/src/engine/ArticulationSchedule.cpp
@@ -0,0 +1,423 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The articulation scheduler (specs/085, see ArticulationSchedule.h). Times here are absolute
+// transport samples; a block covers [blockStart, blockStart + frames). The note rules are the ones
+// gatherInstrumentNotes uses for the notes themselves, so a switch and its note agree on whether
+// the note plays at all: a note at or past the clip end doesn't, one before the clip start sounds
+// from the clip start, and a note's end is cut at the clip end.
+//
+// A clip "placement" is a clip at its place on this clock: an arrangement clip at its position, or
+// one loop pass of a Session slot. The plug-in's selected articulation is one state for the whole
+// track, so whether a latching point sends its switch is decided across every placement: it sends
+// when the point that triggers just before it (by trigger time, then placement, then order in the
+// clip) selects something else. That makes overlapping clips, per-articulation offsets that
+// reorder the triggers, and a chase after a seek all agree with straight playback.
+
+#include "ArticulationSchedule.h"
+
+#include "MidiClip.h"
+
+#include <algorithm>
+#include <climits>
+#include <cmath>
+#include <limits>
+
+namespace nota {
+
+namespace {
+
+constexpr double kInf = std::numeric_limits<double>::infinity();
+
+struct Writer {
+ ArtEv* out;
+ int cap;
+ int n = 0;
+ int dropped = 0;
+ int seq = 0;
+ bool put(int32_t off, ArtEvKind kind, int32_t channel, int32_t d1, int32_t d2) {
+ if (n >= cap) {
+ ++dropped;
+ return false;
+ }
+ out[n++] = {off, seq++, kind, static_cast<uint8_t>(channel), static_cast<uint8_t>(d1), static_cast<uint8_t>(d2)};
+ return true;
+ }
+};
+
+// Advance only [from, count): old entries advance before new key-ons are scheduled, then newly
+// queued entries advance at block end. Due releases get buffer space before new actions. If a
+// release cannot fit, keep it due at offset 0 of the next block instead of losing the held key.
+void advanceReleases(Writer& w, ArticulationReleaseState& state, int32_t frames, int from = 0) {
+ int kept = from;
+ for (int i = from; i < state.count; ++i) {
+ auto key = state.pending[i];
+ if (key.remaining < frames) {
+ if (w.put(std::max(0, key.remaining), ArtEvKind::KeyOff, key.channel, key.pitch, 0)) continue;
+ key.remaining = 0;
+ } else key.remaining -= frames;
+ state.pending[kept++] = key;
+ }
+ state.count = kept;
+}
+
+int beginReleases(Writer& w, const ArticulationBlock& b) {
+ if (!b.releases) return 0;
+ advanceReleases(w, *b.releases, b.frames);
+ return b.releases->count;
+}
+
+struct Window {
+ double start, end; // [start, end)
+ bool contains(double s) const { return s >= start && s < end; }
+ int32_t offsetOf(double s) const { return static_cast<int32_t>(s - start); }
+};
+
+// An entry's actions, in map order, at `at` (absolute samples), if that falls in the block.
+void sendActions(Writer& w, const ArticulationTable& table, const ArticulationEntry& e, double at, const Window& win,
+ ArticulationReleaseState* releases = nullptr, double hold = 0.0) {
+ if (!win.contains(at)) return;
+ const int32_t off = win.offsetOf(at);
+ const ArticulationAction* a = table.actionsOf(e);
+ for (int32_t i = 0; i < e.actionCount; ++i) {
+ const ArticulationAction& x = a[i];
+ switch (x.kind) {
+ case ArticulationActionKind::Keyswitch:
+ if (releases && releases->count >= kMaxBlockArt) {
+ ++w.dropped; // don't press a key whose release cannot be retained
+ break;
+ }
+ if (w.put(off, ArtEvKind::KeyOn, x.channel, x.data1, x.data2) && releases)
+ releases->pending[releases->count++] = {off + static_cast<int32_t>(std::lround(hold)),
+ static_cast<uint8_t>(x.channel), static_cast<uint8_t>(x.data1)};
+ break;
+ case ArticulationActionKind::ControlChange: w.put(off, ArtEvKind::Control, x.channel, x.data1, x.data2); break;
+ case ArticulationActionKind::ProgramChange: w.put(off, ArtEvKind::Program, x.channel, x.data1, 0); break;
+ case ArticulationActionKind::BankSelectMsb: w.put(off, ArtEvKind::Control, x.channel, 0, x.data2); break;
+ case ArticulationActionKind::BankSelectLsb: w.put(off, ArtEvKind::Control, x.channel, 32, x.data2); break;
+ }
+ }
+}
+
+// Let go of the entry's keyswitch notes at `at`, if that falls in the block.
+void releaseKeys(Writer& w, const ArticulationTable& table, const ArticulationEntry& e, double at, const Window& win) {
+ if (!win.contains(at)) return;
+ const int32_t off = win.offsetOf(at);
+ const ArticulationAction* a = table.actionsOf(e);
+ for (int32_t i = 0; i < e.actionCount; ++i)
+ if (a[i].kind == ArticulationActionKind::Keyswitch) w.put(off, ArtEvKind::KeyOff, a[i].channel, a[i].data1, 0);
+}
+
+bool hasKey(const ArticulationTable& table, const ArticulationEntry& e, int32_t channel, int32_t pitch) {
+ const ArticulationAction* a = table.actionsOf(e);
+ // Playback notes currently use channel 1; channel 0 means that same note channel.
+ // A default-channel action and an explicit channel-1 action hold the same physical key.
+ for (int32_t i = 0; i < e.actionCount; ++i)
+ if (a[i].kind == ArticulationActionKind::Keyswitch && std::max(1, a[i].channel) == std::max(1, channel) &&
+ a[i].data1 == pitch) return true;
+ return false;
+}
+
+bool hasKeys(const ArticulationTable& table, const ArticulationEntry& e) {
+ const ArticulationAction* a = table.actionsOf(e);
+ for (int32_t i = 0; i < e.actionCount; ++i)
+ if (a[i].kind == ArticulationActionKind::Keyswitch) return true;
+ return false;
+}
+
+// A clip at its place on this block's clock.
+struct Placement {
+ const MidiClip* clip;
+ double start; // samples
+ double lengthBeats; // notes at or past it don't play
+ long order; // clip index or loop pass, for a total order of triggers
+ bool trimEnd = true; // arrangement trims tails; Session notes may outlast a loop pass
+};
+
+// Everything a block's decisions share.
+struct Ctx {
+ const ArticulationTable& table;
+ const ArticulationBlock& b;
+ double msToS, trackShift, hold;
+ double lo, hi; // the smallest and largest (offset − lead) over the table, in samples
+};
+
+Ctx makeCtx(const ArticulationTable& table, const ArticulationBlock& b) {
+ Ctx c{table, b, b.sampleRate / 1000.0, 0.0, 0.0, kInf, -kInf};
+ c.trackShift = b.trackOffsetMs * c.msToS;
+ c.hold = kKeyswitchHoldMs * c.msToS;
+ for (const ArticulationEntry& e : table.entries()) {
+ const double d = (e.offsetMs - e.leadMs) * c.msToS;
+ c.lo = std::min(c.lo, d);
+ c.hi = std::max(c.hi, d);
+ }
+ if (c.lo > c.hi) c.lo = c.hi = 0.0; // an empty table
+ return c;
+}
+
+// Where a note at clip-local `beat` sounds before its articulation's own offset.
+double noteTime(const Ctx& c, const Placement& p, double beat) { return p.start + std::max(0.0, beat) * c.b.spb + c.trackShift; }
+
+double trigOf(const Ctx& c, const Placement& p, const ArticulationChange& x, const ArticulationEntry& e) {
+ return noteTime(c, p, x.beat) + (e.offsetMs - e.leadMs) * c.msToS;
+}
+
+struct Key {
+ double trig;
+ long order;
+ int32_t idx;
+};
+
+bool before(const Key& a, const Key& k) {
+ if (a.trig != k.trig) return a.trig < k.trig;
+ if (a.order != k.order) return a.order < k.order;
+ return a.idx < k.idx;
+}
+
+// Index of the first timeline point whose note time can reach `t` (samples) in placement `p`.
+size_t firstFrom(const Ctx& c, const Placement& p, const std::vector<ArticulationChange>& ch, double t) {
+ const double beat = (t - p.start - c.trackShift) / c.b.spb;
+ if (beat <= 0.0) return 0; // notes before the clip start sound from it
+ return static_cast<size_t>(std::lower_bound(ch.begin(), ch.end(), beat,
+ [](const ArticulationChange& x, double v) { return x.beat < v; }) -
+ ch.begin());
+}
+
+// The latching articulation in force just before key `k`: the entry of the point that triggers
+// last before it, over every placement `all` gives; 0 when nothing has triggered yet.
+template <class All> int32_t inForceBefore(const Ctx& c, const All& all, const Key& k) {
+ Key best{-kInf, LONG_MIN, INT32_MIN};
+ int32_t id = 0;
+ bool found = false;
+ all([&](const Placement& p) {
+ const ArticulationTimeline* tl = p.clip->articulations.get();
+ if (!tl) return;
+ const auto& ch = tl->changes;
+ // A point triggers no later than its note time + hi and no earlier than + lo: only the
+ // ones whose note time is at most k − lo can be before k; scanning back, stop once even
+ // + hi can't beat the best found.
+ size_t i = firstFrom(c, p, ch, k.trig - c.lo + 1.0);
+ while (i < ch.size() && noteTime(c, p, ch[i].beat) + c.lo <= k.trig) ++i;
+ while (i-- > 0) {
+ const ArticulationChange& x = ch[i];
+ if (found && noteTime(c, p, x.beat) + c.hi < best.trig) break;
+ if (x.beat >= p.lengthBeats) continue;
+ const ArticulationEntry* e = c.table.find(x.entryId);
+ if (!e) continue;
+ const Key kx{trigOf(c, p, x, *e), p.order, static_cast<int32_t>(i)};
+ if (!before(kx, k)) continue;
+ if (!found || before(best, kx)) {
+ best = kx;
+ id = x.entryId;
+ found = true;
+ }
+ }
+ });
+ return id;
+}
+
+// True when a momentary note other than (`self` in `selfOrder`) holds keyswitch (channel, pitch)
+// down across `at`: pressed at or before it, released after it.
+template <class All>
+bool keyHeldAcross(const Ctx& c, const All& all, int32_t channel, int32_t pitch, double at, const Note* self, long selfOrder) {
+ bool held = false;
+ all([&](const Placement& p) {
+ if (held) return;
+ const double end = p.start + p.lengthBeats * c.b.spb;
+ for (const Note& note : p.clip->notes) {
+ if (&note == self && p.order == selfOrder) continue;
+ if (note.startBeat >= p.lengthBeats || note.startBeat + note.lengthBeats <= 0.0) continue;
+ const ArticulationEntry* e = c.table.resolve(note.articulation);
+ if (!e || e->trigger != ArticulationTrigger::Momentary || !hasKey(c.table, *e, channel, pitch)) continue;
+ const double shift = c.trackShift + e->offsetMs * c.msToS;
+ const double on = p.start + std::max(0.0, note.startBeat) * c.b.spb + shift - e->leadMs * c.msToS;
+ const double noteEnd = p.start + (note.startBeat + note.lengthBeats) * c.b.spb;
+ const double off = (p.trimEnd ? std::min(end, noteEnd) : noteEnd) + shift;
+ if (on <= at && off > at) {
+ held = true;
+ return;
+ }
+ }
+ });
+ return held;
+}
+
+// The block's events for the placements `emit` gives, deciding against every placement `all`
+// gives (a superset: for a slot, the pass before too). `chase` re-sends what is in force at the
+// block's start; `covered` says whether any placement is still playing there.
+template <class Emit, class All> void scheduleAll(Writer& w, const Ctx& c, const Window& win, const Emit& emit, const All& all) {
+ const ArticulationBlock& b = c.b;
+ bool landingSent = false; // a switch already lands on the block's first sample
+ bool covered = false;
+
+ // ---- latching: each point sends when it changes what is in force ----
+ emit([&](const Placement& p) {
+ const double end = p.start + p.lengthBeats * b.spb;
+ if (win.start < end) covered = true;
+ const ArticulationTimeline* tl = p.clip->articulations.get();
+ if (!tl) return;
+ const auto& ch = tl->changes;
+ // Points that can act in this block: triggered in it, or released (hold later) in it.
+ for (size_t i = firstFrom(c, p, ch, win.start - c.hold - c.hi); i < ch.size(); ++i) {
+ const ArticulationChange& x = ch[i];
+ if (x.beat >= p.lengthBeats) break; // sorted: the rest are past the clip end too
+ if (noteTime(c, p, x.beat) + c.lo >= win.end) break;
+ const ArticulationEntry* e = c.table.find(x.entryId);
+ if (!e) continue;
+ const double trig = trigOf(c, p, x, *e);
+ if (trig + c.hold < win.start || trig >= win.end) continue;
+ if (inForceBefore(c, all, Key{trig, p.order, static_cast<int32_t>(i)}) == x.entryId) continue; // already selected
+ if (win.contains(trig) && trig < win.start + 1.0) landingSent = true;
+ sendActions(w, c.table, *e, trig, win, b.releases, c.hold);
+ if (!b.releases) releaseKeys(w, c.table, *e, trig + c.hold, win);
+ }
+ // A loop seam just passed: a key pressed before it and due for release after it (its
+ // release would have come past the loop end) lets go now. Those points sit at the seam,
+ // not in this block.
+ if (b.seamOffs) {
+ for (size_t i = firstFrom(c, p, ch, b.seamEnd - c.hold - c.hi); i < ch.size(); ++i) {
+ const ArticulationChange& x = ch[i];
+ if (x.beat >= p.lengthBeats || noteTime(c, p, x.beat) + c.lo >= b.seamEnd) break;
+ const ArticulationEntry* e = c.table.find(x.entryId);
+ if (!e) continue;
+ const double trig = trigOf(c, p, x, *e);
+ if (trig >= b.seamEnd || trig + c.hold < b.seamEnd) continue;
+ if (inForceBefore(c, all, Key{trig, p.order, static_cast<int32_t>(i)}) == x.entryId) continue; // never sent
+ releaseKeys(w, c.table, *e, win.start, win);
+ }
+ }
+ });
+
+ // ---- chase: retain its origin so a 20 ms release can land in a later block ----
+ const double chaseStart = b.chase ? win.start : b.chaseStart;
+ if (chaseStart >= 0.0 && ((b.chase && covered && !landingSent) || (!b.releases && win.contains(chaseStart + c.hold)))) {
+ const int32_t id = inForceBefore(c, all, Key{chaseStart, LONG_MIN, INT32_MIN});
+ // A natural switch at the landing sample supplies its own release; the old articulation
+ // was never chased. Repeated points selecting the same ID are suppressed, so still chase.
+ const int32_t landed = inForceBefore(c, all, Key{chaseStart + 1.0, LONG_MIN, INT32_MIN});
+ if (id == landed)
+ if (const ArticulationEntry* e = c.table.find(id)) {
+ if (b.chase) sendActions(w, c.table, *e, chaseStart, win, b.releases, c.hold);
+ if (!b.releases) releaseKeys(w, c.table, *e, chaseStart + c.hold, win);
+ }
+ }
+
+ // ---- momentary: per note, held while the note sounds ----
+ emit([&](const Placement& p) {
+ const double end = p.start + p.lengthBeats * b.spb;
+ for (const Note& note : p.clip->notes) {
+ if (note.startBeat >= p.lengthBeats || note.startBeat + note.lengthBeats <= 0.0) continue;
+ const ArticulationEntry* e = c.table.resolve(note.articulation);
+ if (!e || e->trigger != ArticulationTrigger::Momentary) continue;
+ const double shift = c.trackShift + e->offsetMs * c.msToS;
+ const double onS = p.start + std::max(0.0, note.startBeat) * b.spb + shift;
+ const double noteEnd = p.start + (note.startBeat + note.lengthBeats) * b.spb;
+ const double offS = (p.trimEnd ? std::min(end, noteEnd) : noteEnd) + shift;
+ const double trig = onS - e->leadMs * c.msToS;
+ sendActions(w, c.table, *e, trig, win);
+ if (hasKeys(c.table, *e)) {
+ // Each key lets go with its note — unless another note still holds the same key.
+ if (win.contains(offS)) {
+ const ArticulationAction* a = c.table.actionsOf(*e);
+ for (int32_t k = 0; k < e->actionCount; ++k)
+ if (a[k].kind == ArticulationActionKind::Keyswitch &&
+ !keyHeldAcross(c, all, a[k].channel, a[k].data1, offS, &note, p.order))
+ w.put(win.offsetOf(offS), ArtEvKind::KeyOff, a[k].channel, a[k].data1, 0);
+ }
+ if (b.seamOffs && trig < b.seamEnd && offS >= b.seamEnd) releaseKeys(w, c.table, *e, win.start, win);
+ }
+ // A note already held where playback lands is chased by the note scheduler; its switch goes with it.
+ if (b.chase && trig < win.start && offS > win.start) sendActions(w, c.table, *e, win.start, win);
+ }
+ });
+}
+
+int finish(Writer& w, ArtEv* out, int* dropped, const ArticulationBlock* b = nullptr, int carried = 0) {
+ if (b && b->releases) advanceReleases(w, *b->releases, b->frames, carried);
+ std::sort(out, out + w.n, [](const ArtEv& a, const ArtEv& c) {
+ if (a.off != c.off) return a.off < c.off;
+ const bool ra = a.kind == ArtEvKind::KeyOff, rc = c.kind == ArtEvKind::KeyOff;
+ if (ra != rc) return ra; // releases before presses at the same sample
+ return a.seq < c.seq;
+ });
+ if (dropped) *dropped = w.dropped;
+ return w.n;
+}
+
+} // namespace
+
+double articulationOffsetMs(const ArticulationTable* table, int32_t noteArticulation) {
+ if (!table) return 0.0;
+ const ArticulationEntry* e = table->resolve(noteArticulation);
+ return e ? e->offsetMs : 0.0;
+}
+
+int scheduleArticulations(const std::vector<MidiClip>& clips, const ArticulationTable& table, const ArticulationBlock& b,
+ ArtEv* out, int cap, int* dropped) {
+ Writer w{out, cap};
+ if (b.frames <= 0 || b.spb <= 0.0 || b.sampleRate <= 0.0) {
+ if (dropped) *dropped = 0;
+ return 0;
+ }
+ const Window win{b.blockStart, b.blockStart + b.frames};
+ const Ctx c = makeCtx(table, b);
+ const int carried = beginReleases(w, b);
+ // Every active clip of the track, in its order.
+ auto active = [&](auto&& f) {
+ long i = 0;
+ for (const MidiClip& clip : clips) {
+ if (clip.active) f(Placement{&clip, clip.startBeat * b.spb, clip.lengthBeats, i});
+ ++i;
+ }
+ };
+ scheduleAll(w, c, win, active, active);
+ return finish(w, out, dropped, &b, carried);
+}
+
+int scheduleSlotArticulations(const MidiClip& slotClip, double loopBeats, bool loop, const ArticulationTable& table,
+ const ArticulationBlock& b, ArtEv* out, int cap, int* dropped) {
+ Writer w{out, cap};
+ if (b.frames <= 0 || b.spb <= 0.0 || b.sampleRate <= 0.0 || loopBeats <= 0.0) {
+ if (dropped) *dropped = 0;
+ return 0;
+ }
+ const Window win{b.blockStart, b.blockStart + b.frames};
+ const Ctx c = makeCtx(table, b);
+ const int carried = beginReleases(w, b);
+ // The passes whose events can fall in this block: a pass's events lie between its start plus
+ // the earliest trigger and its end plus the latest note shift and the hold — on a short loop
+ // with a large offset, several passes away. No neighboring-pass limit: even a very short
+ // loop must retain all passes whose events reach this block.
+ const double loopS = loopBeats * b.spb;
+ double maxShift = c.trackShift;
+ for (const ArticulationEntry& e : table.entries()) maxShift = std::max(maxShift, c.trackShift + e.offsetMs * c.msToS);
+ double tail = 0.0;
+ for (const Note& note : slotClip.notes)
+ if (note.startBeat >= 0.0 && note.startBeat < loopBeats)
+ tail = std::max(tail, (note.startBeat + note.lengthBeats - loopBeats) * b.spb);
+ const double late = std::max(0.0, maxShift) + std::max(c.hold, tail);
+ const double early = c.trackShift + c.lo; // the earliest trigger relative to its note's grid time
+ long lo = std::max(0L, static_cast<long>(std::floor((win.start - late) / loopS)) - 1);
+ long hi = static_cast<long>(std::floor((win.end - std::min(0.0, early)) / loopS));
+ if (!loop) hi = std::min(hi, 0L); // one-shot: a single pass
+ if (hi < lo) {
+ return finish(w, out, dropped, &b, carried);
+ }
+ auto passes = [&](long from) {
+ return [&slotClip, loopS, loopBeats, from, hi](auto&& f) {
+ for (long k = from; k <= hi; ++k) f(Placement{&slotClip, k * loopS, loopBeats, k, false});
+ };
+ };
+ // Decisions look one pass further back, so a pass's first point knows what the pass before left in force.
+ scheduleAll(w, c, win, passes(lo), passes(std::max(0L, lo - 1)));
+ return finish(w, out, dropped, &b, carried);
+}
+
+int scheduleArticulationReleases(ArticulationReleaseState& releases, int32_t frames, ArtEv* out, int cap) {
+ Writer w{out, cap};
+ if (frames <= 0) return 0;
+ advanceReleases(w, releases, frames);
+ return finish(w, out, nullptr);
+}
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/ArticulationSchedule.h b/src/native/nota.engine/src/engine/ArticulationSchedule.h
new file mode 100644
index 00000000..8cf6e9b9
--- /dev/null
+++ b/src/native/nota.engine/src/engine/ArticulationSchedule.h
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Articulation playback (specs/085): which articulation MIDI one block sends. A pure function of
+// the track's clips, its table and the block. Session latching releases also retain the actual
+// keys and their remaining rendered frames, so tempo changes cannot skip a pending release:
+//
+// effective note time = nominal + track offset + articulation offset (FR-018)
+// trigger time = effective − lead (FR-019)
+//
+// A latching articulation is sent where a note asks for one that isn't already in force — decided
+// across all of the track's clips, by trigger time — so a phrase sends its keyswitch once and an
+// overlapping clip's switch in between is honoured; a keyswitch note is released kKeyswitchHoldMs
+// later. Momentary ones are sent with each note and their keyswitch held until the last note
+// holding that key ends. On a chase (start, seek, loop wrap, a slot's launch) the latching
+// articulation in force at the block start is sent at offset 0 and released 20 ms later, and
+// a held momentary note's switch goes with it. Audio thread: reads published, immutable data only
+// and writes into the caller's fixed array — no allocation, no locks (AR-6).
+
+#pragma once
+
+#include "ArticulationTable.h"
+
+#include <cstdint>
+#include <type_traits>
+#include <vector>
+
+namespace nota {
+
+struct MidiClip;
+
+enum class ArtEvKind : uint8_t {
+ KeyOn = 0, // keyswitch note on: data1 pitch, data2 velocity
+ KeyOff = 1, // keyswitch note off: data1 pitch
+ Control = 2, // CC data1 = data2 (bank select is CC 0 / CC 32)
+ Program = 3, // program change data1
+};
+
+// One articulation event of a block. Sorted by off; at a shared offset, key releases first (a
+// switch let go before the next one is pressed), then the actions in their map order (seq).
+// Trivially constructible on purpose: the render keeps a kMaxBlockArt array of these on the stack
+// for every instrument track, every block, and default member initialisers would zero it each time.
+struct ArtEv {
+ int32_t off; // sample offset in the block
+ int32_t seq; // order among events at the same offset
+ ArtEvKind kind;
+ uint8_t channel; // 0 = the note's own channel, 1..16
+ uint8_t data1;
+ uint8_t data2;
+};
+static_assert(std::is_trivially_default_constructible_v<ArtEv>);
+
+inline constexpr double kKeyswitchHoldMs = 20.0; // how long a latching keyswitch note is held
+inline constexpr int kMaxBlockArt = 256; // a block's articulation events (stack array)
+
+// Audio-thread-owned, fixed-capacity release storage. Only emitted latching key-ons enter it.
+// Remaining frames count down with rendering, independent of a slot's beat position or tempo.
+// The pending array is deliberately uninitialized: entries beyond count are never read.
+struct ArticulationReleaseState {
+ struct Pending {
+ int32_t remaining;
+ uint8_t channel, pitch;
+ };
+ Pending pending[kMaxBlockArt];
+ int count = 0;
+};
+
+struct ArticulationBlock {
+ int32_t frames = 0;
+ double blockStart = 0.0; // samples, the transport position of the block's first frame
+ double spb = 0.0; // samples per beat
+ double sampleRate = 0.0;
+ double trackOffsetMs = 0.0;
+ bool chase = false; // start / seek / loop wrap: re-send what is in force
+ bool seamOffs = false; // a loop seam just passed: let go of keys held across it
+ double seamEnd = 0.0; // where the seam was (samples), when seamOffs
+ double chaseStart = -1.0; // last discontinuity on this clock, for a chased key's later release
+ ArticulationReleaseState* releases = nullptr; // Session: rendered-frame clock for all latching releases
+};
+
+// Fills `out` (capacity `cap`) with the block's events, sorted, and returns how many. Events that
+// don't fit are dropped and counted in *dropped (never allocated). Inactive clips send nothing.
+int scheduleArticulations(const std::vector<MidiClip>& clips, const ArticulationTable& table, const ArticulationBlock& b,
+ ArtEv* out, int cap, int* dropped = nullptr);
+
+// A Session slot (specs/085, T042): the slot's clip looped every `loopBeats` on the slot's own clock.
+// In `b`, blockStart is the slot's local position in samples (localBeats × spb); a pass k starts at
+// k × loopBeats. A one-shot slot plays pass 0 only. Set chase on the first block after a launch.
+// Every pass whose events can reach the block is read, however far the offsets move them.
+int scheduleSlotArticulations(const MidiClip& slotClip, double loopBeats, bool loop, const ArticulationTable& table,
+ const ArticulationBlock& b, ArtEv* out, int cap, int* dropped = nullptr);
+
+// Continue pending releases even after the track's map was cleared; no table or beat clock needed.
+int scheduleArticulationReleases(ArticulationReleaseState& releases, int32_t frames, ArtEv* out, int cap);
+
+// The offset (ms) an articulation adds to a note with this id: its entry's (or the default's), else 0.
+double articulationOffsetMs(const ArticulationTable* table, int32_t noteArticulation);
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/ArticulationTable.cpp b/src/native/nota.engine/src/engine/ArticulationTable.cpp
new file mode 100644
index 00000000..d9b08457
--- /dev/null
+++ b/src/native/nota.engine/src/engine/ArticulationTable.cpp
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Building and reading articulation tables and clip timelines (specs/085). build and
+// buildArticulationTimeline run on the message thread; resolve / find / inForceAt are the
+// audio thread's, and only search sorted arrays.
+
+#include "ArticulationTable.h"
+
+#include "MidiClip.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+namespace nota {
+
+namespace {
+
+bool validAction(const ArticulationAction& a) {
+ const int32_t k = static_cast<int32_t>(a.kind);
+ if (k < 0 || k > static_cast<int32_t>(ArticulationActionKind::BankSelectLsb)) return false;
+ if (a.channel < 0 || a.channel > 16) return false;
+ return a.data1 >= 0 && a.data1 <= 127 && a.data2 >= 0 && a.data2 <= 127;
+}
+
+} // namespace
+
+std::shared_ptr<const ArticulationTable> ArticulationTable::build(int32_t defaultId, const ArticulationEntry* entries,
+ int32_t entryCount, const ArticulationAction* actions, int32_t actionCount) {
+ if (entryCount < 0 || actionCount < 0 || entryCount > kArticulationMaxEntries || actionCount > kArticulationMaxActions)
+ return nullptr;
+ if ((entryCount > 0 && !entries) || (actionCount > 0 && !actions)) return nullptr;
+ int32_t prev = 0;
+ bool defaultFound = defaultId == 0;
+ for (int32_t i = 0; i < entryCount; ++i) {
+ const ArticulationEntry& e = entries[i];
+ if (e.id <= prev) return nullptr; // > 0 and strictly ascending
+ prev = e.id;
+ const int32_t t = static_cast<int32_t>(e.trigger);
+ if (t < 0 || t > static_cast<int32_t>(ArticulationTrigger::Momentary)) return nullptr;
+ if (!std::isfinite(e.offsetMs) || std::abs(e.offsetMs) > kArticulationMaxOffsetMs) return nullptr;
+ if (!std::isfinite(e.leadMs) || e.leadMs < 0.0 || e.leadMs > kArticulationMaxLeadMs) return nullptr;
+ if (e.actionStart < 0 || e.actionCount < 0 || e.actionStart > actionCount ||
+ e.actionCount > actionCount - e.actionStart)
+ return nullptr;
+ if (e.id == defaultId) defaultFound = true;
+ }
+ if (defaultId < 0 || !defaultFound) return nullptr;
+ for (int32_t i = 0; i < actionCount; ++i)
+ if (!validAction(actions[i])) return nullptr;
+
+ auto t = std::make_shared<ArticulationTable>();
+ t->defaultId_ = defaultId;
+ t->entries_.assign(entries, entries + entryCount);
+ t->actions_.assign(actions, actions + actionCount);
+ return t;
+}
+
+const ArticulationEntry* ArticulationTable::find(int32_t id) const {
+ if (id <= 0) return nullptr;
+ auto it = std::lower_bound(entries_.begin(), entries_.end(), id,
+ [](const ArticulationEntry& e, int32_t v) { return e.id < v; });
+ return it != entries_.end() && it->id == id ? &*it : nullptr;
+}
+
+const ArticulationEntry* ArticulationTable::resolve(int32_t id) const {
+ if (const ArticulationEntry* e = find(id)) return e;
+ return find(defaultId_);
+}
+
+const ArticulationChange* ArticulationTimeline::inForceAt(double beat) const {
+ auto it = std::upper_bound(changes.begin(), changes.end(), beat,
+ [](double b, const ArticulationChange& c) { return b < c.beat; });
+ return it == changes.begin() ? nullptr : &*(it - 1);
+}
+
+uint64_t articulationNotesKey(const MidiClip& clip) {
+ // FNV-1a over the fields the timeline reads, in vector order.
+ uint64_t h = 1469598103934665603ull;
+ auto mix = [&](uint64_t v) {
+ for (int i = 0; i < 8; ++i) {
+ h ^= (v >> (i * 8)) & 0xFFu;
+ h *= 1099511628211ull;
+ }
+ };
+ mix(clip.notes.size());
+ for (const Note& n : clip.notes) {
+ uint64_t bits = 0;
+ static_assert(sizeof(bits) == sizeof(n.startBeat));
+ std::memcpy(&bits, &n.startBeat, sizeof(bits));
+ mix(bits);
+ mix(static_cast<uint64_t>(static_cast<uint32_t>(n.pitch)) << 32 | static_cast<uint32_t>(n.articulation));
+ }
+ return h;
+}
+
+std::shared_ptr<const ArticulationTimeline> buildArticulationTimeline(
+ const MidiClip& clip, const std::shared_ptr<const ArticulationTable>& table) {
+ auto tl = std::make_shared<ArticulationTimeline>();
+ tl->builtFor = table;
+ tl->notesKey = articulationNotesKey(clip);
+ if (!table) return tl;
+
+ // The notes in start order; at a shared start, ascending pitch, so the order is fixed and
+ // the highest note of a chord sets the articulation that stays in force.
+ std::vector<const Note*> order;
+ order.reserve(clip.notes.size());
+ for (const Note& n : clip.notes) order.push_back(&n);
+ std::stable_sort(order.begin(), order.end(), [](const Note* a, const Note* b) {
+ return a->startBeat < b->startBeat || (a->startBeat == b->startBeat && a->pitch < b->pitch);
+ });
+
+ // Every latching note is a point; whether it sends is decided at playback across the whole
+ // track (another clip may change the articulation in between). Only a repeat at the same beat
+ // (a chord's notes) is folded here: nothing can come between them.
+ for (const Note* n : order) {
+ const ArticulationEntry* e = table->resolve(n->articulation);
+ if (!e || e->trigger != ArticulationTrigger::Latching) continue; // momentary: per note, latch untouched
+ if (!tl->changes.empty() && tl->changes.back().beat == n->startBeat && tl->changes.back().entryId == e->id) continue;
+ tl->changes.push_back({n->startBeat, e->id, n->pitch});
+ }
+ return tl;
+}
+
+bool articulationTimelineCurrent(const MidiClip& clip, const std::shared_ptr<const ArticulationTable>& table) {
+ if (!table) return clip.articulations == nullptr;
+ const ArticulationTimeline* tl = clip.articulations.get();
+ return tl && tl->builtFor == table && tl->notesKey == articulationNotesKey(clip);
+}
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/ArticulationTable.h b/src/native/nota.engine/src/engine/ArticulationTable.h
new file mode 100644
index 00000000..106c72ff
--- /dev/null
+++ b/src/native/nota.engine/src/engine/ArticulationTable.h
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Articulation maps in the engine (specs/085). A track's map arrives compiled from the UI as a
+// flat table — articulations sorted by id, each pointing at its ordered MIDI actions — and a
+// clip derives from its notes the points where the latching articulation changes. Both are
+// built on the message thread, immutable once published with the graph (AR-5), and only read on
+// the audio thread: lookups are binary searches over arrays, nothing allocates there (AR-6).
+// Disabled articulations are left out by the UI's compiler, so here they are simply missing.
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+namespace nota {
+
+struct MidiClip;
+
+enum class ArticulationActionKind : int32_t {
+ Keyswitch = 0, // note data1 at velocity data2
+ ControlChange = 1, // controller data1 = data2
+ ProgramChange = 2, // program data1
+ BankSelectMsb = 3, // CC 0 = data2
+ BankSelectLsb = 4, // CC 32 = data2
+};
+
+enum class ArticulationTrigger : int32_t {
+ Latching = 0, // sent when the articulation changes; stays in force
+ Momentary = 1, // sent with each note and released with it
+};
+
+struct ArticulationAction {
+ ArticulationActionKind kind = ArticulationActionKind::Keyswitch;
+ int32_t channel = 0; // 0 = the note's own channel, 1..16 explicit
+ int32_t data1 = 0;
+ int32_t data2 = 0;
+};
+
+struct ArticulationEntry {
+ int32_t id = 0; // > 0, unique, ascending in the table
+ ArticulationTrigger trigger = ArticulationTrigger::Latching;
+ double offsetMs = 0.0; // added to the track's MIDI offset for notes with this articulation
+ double leadMs = 0.0; // the actions go out this long before the (offset) note
+ int32_t actionStart = 0;
+ int32_t actionCount = 0;
+};
+
+// Limits shared with the C ABI's validation.
+inline constexpr double kArticulationMaxOffsetMs = 2000.0;
+inline constexpr double kArticulationMaxLeadMs = 2000.0;
+inline constexpr int32_t kArticulationMaxEntries = 4096;
+inline constexpr int32_t kArticulationMaxActions = 65536;
+
+class ArticulationTable {
+ public:
+ // A validated table, or null (and nothing built) when the input breaks a rule: ids must be
+ // > 0 and strictly ascending; each entry's action range lies inside `actions`; kinds,
+ // channels (0..16) and data (0..127) in range; offsets within ±kArticulationMaxOffsetMs and
+ // leads within 0..kArticulationMaxLeadMs, both finite; defaultId is 0 or an entry's id.
+ static std::shared_ptr<const ArticulationTable> build(int32_t defaultId, const ArticulationEntry* entries,
+ int32_t entryCount, const ArticulationAction* actions, int32_t actionCount);
+
+ // The articulation a note with `id` plays: its own entry, else the default's (id 0, an id
+ // the map no longer has, or a disabled one), else null — no articulation, nothing sent.
+ const ArticulationEntry* resolve(int32_t id) const;
+ const ArticulationEntry* find(int32_t id) const;
+
+ const ArticulationAction* actionsOf(const ArticulationEntry& e) const { return actions_.data() + e.actionStart; }
+ int32_t defaultId() const { return defaultId_; }
+ const std::vector<ArticulationEntry>& entries() const { return entries_; }
+
+ private:
+ int32_t defaultId_ = 0;
+ std::vector<ArticulationEntry> entries_;
+ std::vector<ArticulationAction> actions_;
+};
+
+// The latching articulation each note of a clip asks for, in clip-local beats, sorted by beat (at a
+// shared beat, by ascending pitch; a repeat at the same beat is folded). The scheduler sends a
+// point's switch only when it changes what is in force across the whole track — so a phrase sends
+// its keyswitch once, and an overlapping clip's switch in between is respected. Momentary
+// articulations are not here — they are sent per note — and do not change the latched state.
+struct ArticulationChange {
+ double beat = 0.0; // the start of the note that brings the change
+ int32_t entryId = 0; // the resolved articulation (an entry id in the table)
+ int32_t notePitch = 0; // that note, for ordering changes that share a beat
+};
+
+struct ArticulationTimeline {
+ std::vector<ArticulationChange> changes; // may be empty: built, nothing latching
+
+ // What it was built from, so a publish can tell a current timeline from a stale one: the
+ // table itself (held, so a new table at a reused address can never pass for it) and a
+ // fingerprint of the clip's notes.
+ std::shared_ptr<const ArticulationTable> builtFor;
+ uint64_t notesKey = 0;
+
+ // The change in force at clip-local `beat` (the last one at or before it), or null.
+ const ArticulationChange* inForceAt(double beat) const;
+};
+
+// The clip's timeline against `table` (never null; empty when nothing latches).
+std::shared_ptr<const ArticulationTimeline> buildArticulationTimeline(
+ const MidiClip& clip, const std::shared_ptr<const ArticulationTable>& table);
+
+// A fingerprint of what a timeline depends on in the notes: each one's start, pitch and articulation, in order.
+uint64_t articulationNotesKey(const MidiClip& clip);
+
+// True when the clip's timeline matches `table` and its notes as they are (no table: no timeline).
+bool articulationTimelineCurrent(const MidiClip& clip, const std::shared_ptr<const ArticulationTable>& table);
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index 870fcaed..ad04e2ef 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -662,7 +662,9 @@ std::shared_ptr<Track> Engine::findTrackAuthoring(int32_t id) const {
}
std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {
- auto nt = std::make_shared<Track>(t.id(), t.type());
+ // Reuse playback state at construction: allocating a fresh player here only to replace it
+ // later wastes its fixed release storage on every clip edit and undo.
+ auto nt = std::make_shared<Track>(t.id(), t.type(), t.sessionPlayer);
nt->setVolume(t.volume());
nt->setPan(t.pan());
nt->setMute(t.mute());
@@ -674,6 +676,9 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {
nt->setInputChannels(t.inputChannels()); // mono / stereo hardware input
nt->setMonitor(t.monitor()); // live input monitoring
nt->setMidiFromTrackId(t.midiFromTrackId()); // MIDI routing
+ nt->setMidiOffsetMs(t.midiOffsetMs()); // MIDI playback offset
+ nt->articulationTable = t.articulationTable; // articulation map (shared, immutable)
+ nt->articulationMapJson = t.articulationMapJson;
for (int b = 0; b < kMaxReturns; ++b) nt->setSend(b, t.send(b)); // M6-1: send levels
nt->clips = t.clips;
nt->takes = t.takes; // take lanes (specs/067) — buffers shared
@@ -688,7 +693,6 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {
nt->cvLinks = t.cvLinks; // CV modulation edges (Phase 3)
nt->ccRoutesDirty = true; // Arp CC routes (specs/044): rebuilt when published
nt->nextModId = t.nextModId;
- nt->sessionPlayer = t.sessionPlayer; // shared — playback state persists (M5-2)
nt->liveHeld = t.liveHeld; // shared — held live notes (#366) and effect tail (#449) persist
nt->setFrozen(t.frozen()); // M7: freeze state + buffer (shared by pointer)
nt->frozenBuf = t.frozenBuf;
@@ -700,6 +704,33 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {
return nt;
}
+// Whether every clip of `t` (arrangement and Session) has the articulation timeline its notes
+// and its track's table call for — O(1) per clip on a track without a map. Message thread.
+bool Engine::articulationsCurrent(const Track& t) {
+ if (!t.articulationTable) { // the common case, inline: no map means no timelines
+ for (const auto& c : t.midiClips)
+ if (c.articulations) return false;
+ for (const auto& s : t.sessionSlots)
+ if (s.midi.articulations) return false;
+ return true;
+ }
+ for (const auto& c : t.midiClips)
+ if (!articulationTimelineCurrent(c, t.articulationTable)) return false;
+ for (const auto& s : t.sessionSlots)
+ if (!articulationTimelineCurrent(s.midi, t.articulationTable)) return false;
+ return true;
+}
+
+// Rebuild the stale timelines of `t`, which no render can see yet (a fresh clone). Message thread.
+void Engine::settleArticulations(Track& t) {
+ auto settle = [&](MidiClip& c) {
+ if (articulationTimelineCurrent(c, t.articulationTable)) return;
+ c.articulations = t.articulationTable ? buildArticulationTimeline(c, t.articulationTable) : nullptr;
+ };
+ for (auto& c : t.midiClips) settle(c);
+ for (auto& s : t.sessionSlots) settle(s.midi);
+}
+
// Message thread: make sure the published render scratch holds `tracks` tracks. Never
// grows the live one (the audio thread may be inside a block using it): builds a new one
// with headroom and publishes it. Runs inside publishRaw (before the live-graph swap, so a
@@ -754,6 +785,23 @@ void Engine::publishRaw(std::shared_ptr<Graph> g, bool restored) {
// added tracks (already-sized tracks are a no-op), so no race with audio.
for (auto& t : g->tracks)
if (static_cast<int32_t>(t->sessionSlots.size()) < g->sceneCount) t->sessionSlots.resize(g->sceneCount);
+ // Articulation timelines (specs/085) follow each clip's notes and its track's table. The same
+ // rule as the take joins above: a track the playing graph shares is the audio thread's and
+ // already current; one an edit just cloned is settled in place; a restored one (undo, redo,
+ // take retry) may still be walked by a render, so it is cloned first if anything would change.
+ if (g) {
+ auto playing = [&](const std::shared_ptr<Track>& t) {
+ if (!authoring_) return false;
+ for (const auto& old : authoring_->tracks)
+ if (old == t) return true;
+ return false;
+ };
+ for (auto& t : g->tracks) {
+ if (!t || articulationsCurrent(*t) || playing(t)) continue; // cheap test first: `playing` scans the graph
+ if (restored) t = cloneTrack(*t);
+ settleArticulations(*t);
+ }
+ }
authoring_ = g;
if (g) ensureRenderScratch(g->tracks.size());
// Fresh track objects only: the audio thread never sees them change. Before any CC target
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index 40d8bd9e..a3bd961b 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -218,6 +218,7 @@ class Engine {
bool rackSelfTest(); // Instrument Rack: chains sum, macros map, blob round-trips
bool rackDeviceSelfTest(); // Audio Effect Rack: pass-through, parallel sum, blob round-trips
bool timedEventsSelfTest(); // #436: a hosted plug-in renders once per block, events at their offsets
+ int32_t articulationSelfTest(); // specs/085: articulation scheduling + delivery; 0 = pass, else the failed check
bool drumRackSelfTest(); // Drum Rack: notes route only to the matching pad chain
// Lane CRUD — structural (snapshot + undo). addAutomationLane returns the lane
// index, reusing an existing lane on the same target. get/set use the ABI point
@@ -1285,6 +1286,17 @@ class Engine {
// MIDI routing: forward an instrument track's MIDI to another instrument track (-1 = off).
void setTrackMidiSource(int32_t trackId, int32_t sourceTrackId);
int32_t trackMidiSource(int32_t trackId) const;
+ // Track-level MIDI playback offset (ms, negative = earlier). Not destructive: note positions
+ // are unchanged; the scheduler shifts them. Clamped to +-2000 ms.
+ void setTrackMidiOffsetMs(int32_t trackId, double ms);
+ double trackMidiOffsetMs(int32_t trackId) const;
+ // Articulation map (specs/085): validated, one undo step each; publishRaw rebuilds the clips'
+ // timelines. False (nothing changed) on any invalid input — see nota_track_set_articulation_map.
+ bool setTrackArticulationMap(int32_t trackId, int32_t defaultId, const NotaArticulationEntry* entries,
+ int32_t entryCount, const NotaArticulationAction* actions, int32_t actionCount, const char* json, int32_t jsonLen);
+ bool clearTrackArticulationMap(int32_t trackId);
+ int32_t trackArticulationMapJson(int32_t trackId, char* out, int32_t maxLen) const;
+ std::shared_ptr<const ArticulationTable> trackArticulationTable(int32_t trackId) const; // tests
// Live notes (computer keyboard, gamepad, MIDI). Producers on different threads
// serialize on liveMidiMx_; the audio thread only pops (AR-6).
void noteOn(int32_t pitch, float velocity);
@@ -1526,6 +1538,9 @@ class Engine {
void installRackPluginFactory(); // wire RackCore::pluginFactory to the plugin host bridge
std::shared_ptr<Track> findTrackAuthoring(int32_t id) const;
std::shared_ptr<Track> cloneTrack(const Track& t) const;
+ // Articulation timelines (specs/085), kept current by publishRaw.
+ static bool articulationsCurrent(const Track& t);
+ static void settleArticulations(Track& t);
std::shared_ptr<SampleBuffer> findSampleById(int64_t sampleId) const; // M7-6b
static std::shared_ptr<SampleBuffer> chainSampleById(const RackCore* rack, int64_t sampleId, int depth);
void publish(std::shared_ptr<Graph> g); // checkpoints (undo), then publishRaw
@@ -2090,6 +2105,7 @@ class Engine {
bool seekedThisBlock_ = false; // a Seek command was drained this block (audio thread)
bool seekedWhileRolling_ = false; // ...and it arrived while the transport was rolling
bool chaseNotes_ = false; // this segment starts at a discontinuity: re-trigger held clip notes
+ double articulationChaseStart_ = -1.0; // last chase on the arrangement sample clock
// This segment starts right after a loop wrap: clip notes still sounding at the loop end
// (seamEndSamples_, the pre-wrap playhead) get their note-off here — a release, not a cut (#29).
bool seamOffs_ = false;
diff --git a/src/native/nota.engine/src/engine/Engine_Recording.cpp b/src/native/nota.engine/src/engine/Engine_Recording.cpp
index 85ef291a..1b51beba 100644
--- a/src/native/nota.engine/src/engine/Engine_Recording.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Recording.cpp
@@ -212,6 +212,22 @@ void Engine::setTrackMidiSource(int32_t trackId, int32_t sourceTrackId) {
if (sourceTrackId == trackId) sourceTrackId = -1; // no self-routing
if (auto t = findTrackAuthoring(trackId)) t->setMidiFromTrackId(sourceTrackId);
}
+// One undo step (specs/085, T051), like every other edit of a track: a new track with the offset,
+// published with the graph. The audio thread reads the new track's atomic; nothing is written to
+// the track it may be rendering. An unchanged value is no step at all.
+void Engine::setTrackMidiOffsetMs(int32_t trackId, double ms) {
+ if (!std::isfinite(ms)) ms = 0.0;
+ ms = std::clamp(ms, -2000.0, 2000.0);
+ auto old = findTrackAuthoring(trackId);
+ if (!old || old->midiOffsetMs() == ms) return;
+ auto nt = cloneTrack(*old);
+ nt->setMidiOffsetMs(ms);
+ republishWithTrack(trackId, nt);
+}
+double Engine::trackMidiOffsetMs(int32_t trackId) const {
+ auto t = findTrackAuthoring(trackId);
+ return t ? t->midiOffsetMs() : 0.0;
+}
int32_t Engine::trackMidiSource(int32_t trackId) const {
auto t = findTrackAuthoring(trackId);
return t ? t->midiFromTrackId() : -1;
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index 76d8acb4..2efdf3fc 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -4,6 +4,7 @@
// Engine — realtime render core: poll, block render, offline bounce, command/live-MIDI drain, per-track raw renderers, mixer processBlock, metronome & test tone. RT-hot; do not add allocations.
#include "Engine.h"
+#include "ArticulationSchedule.h"
#include "dsp/core/ScopedNoDenormals.h"
#include "dsp/math/SimdAudio.h"
#include "devices/racks/DrumRack.h"
@@ -179,14 +180,27 @@ inline void deliverExpr(Instrument& inst, int32_t pitch, int32_t dim, float valu
// after that it isn't rendered at all (no CPU) until it is switched back on, so `dst` stays
// silent. The MIDI before it keeps running. `beat` / `spb` / `rolling` is the clock the track's
// MIDI effects ran on, for the MIDI effects inside the instrument.
+// One articulation event (specs/085) into the instrument, on its channel. Keyswitch notes bypass
+// the engine's sustain pedal (sendNoteOn/Off): a switch is not a note the player holds.
+inline void deliverArt(Instrument& inst, const ArtEv& e) {
+ inst.eventChannel = e.channel;
+ switch (e.kind) {
+ case ArtEvKind::KeyOn: inst.noteOn(e.data1, static_cast<float>(std::max<int>(1, e.data2)) / 127.0f); break;
+ case ArtEvKind::KeyOff: inst.noteOff(e.data1); break;
+ case ArtEvKind::Control: inst.controller(e.data1, static_cast<float>(e.data2) / 127.0f); break;
+ case ArtEvKind::Program: inst.programChange(e.data1); break;
+ }
+ inst.eventChannel = 0;
+}
+
template <class Live>
void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs, int n, const ExprEv* xev, int xn,
- double beat, double spb, bool rolling, Live&& live) {
+ const ArtEv* aev, int an, double beat, double spb, bool rolling, Live&& live) {
const bool off = inst.bypassed();
if (!off) inst.offSettled.store(false, std::memory_order_relaxed);
else if (inst.offSettled.load(std::memory_order_relaxed))
return;
- if (off) n = xn = 0; // nothing new starts on the way out
+ if (off) n = xn = an = 0; // nothing new starts on the way out
if (inst.takesBlockMidi()) inst.blockMidi(evs, n, frames, beat, spb, rolling); // a rack's chain MIDI effects (#329)
int32_t cursor = 0;
bool liveDone = false;
@@ -208,11 +222,12 @@ void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs,
live();
liveDone = true;
};
- int k = 0, x = 0;
- while (k < n || x < xn) {
+ int k = 0, x = 0, a = 0;
+ while (k < n || x < xn || a < an) {
const int32_t nOff = k < n ? std::clamp(evs[k].off, 0, frames) : INT32_MAX;
const int32_t xOff = x < xn ? std::clamp(xev[x].off, 0, frames) : INT32_MAX;
- const int32_t at = std::min(nOff, xOff);
+ const int32_t aOff = a < an ? std::clamp(aev[a].off, 0, frames) : INT32_MAX;
+ const int32_t at = std::min(std::min(nOff, xOff), aOff);
if (timed) {
if (at >= frames) break; // after the render, at the next block's start (as segmented)
if (at > 0) liveAt0(); // live input sits after the offset-0 notes
@@ -220,7 +235,10 @@ void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs,
} else {
renderTo(at);
}
- if (nOff <= xOff) {
+ if (aOff <= nOff && aOff <= xOff) { // an articulation goes ahead of the note it selects
+ deliverArt(inst, aev[a]);
+ ++a;
+ } else if (nOff <= xOff) {
if (evs[k].on) sendNoteOn(inst, evs[k].pitch, evs[k].vel);
else
sendNoteOff(inst, evs[k].pitch, evs[k].vel);
@@ -235,7 +253,8 @@ void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs,
inst.eventOffset = 0;
inst.render(dst, frames);
cursor = frames;
- for (; k < n; ++k) // end-of-block events: offset 0 of the next render
+ for (; a < an; ++a) deliverArt(inst, aev[a]); // end-of-block events: offset 0 of the next render
+ for (; k < n; ++k)
if (evs[k].on) sendNoteOn(inst, evs[k].pitch, evs[k].vel);
else
sendNoteOff(inst, evs[k].pitch);
@@ -1237,37 +1256,55 @@ int Engine::gatherInstrumentNotes(
const double clipStart = clip.startBeat * spb;
const double clipEnd = clipStart + clip.lengthBeats * spb;
const bool hasVel = !clip.velocityEnvelope.points.empty();
- for (const Note& note : clip.notes) {
- // Clip length gates note starts (M4-2): notes outside don't play. A note that
- // starts before the clip (a count-in pickup recorded into a take at 1.1, #56)
- // sounds from the clip start for the part that reaches into it.
- if (note.startBeat >= clip.lengthBeats || note.startBeat + note.lengthBeats <= 0.0) continue;
- const double onS = clipStart + std::max(0.0, note.startBeat) * spb;
- // A trimmed clip cuts the tail: a note that runs past the clip's (possibly
- // shortened) end stops at the boundary instead of sounding its full length.
- double offS = clipStart + (note.startBeat + note.lengthBeats) * spb;
- if (offS > clipEnd) offS = clipEnd;
- // Velocity envelope (M9 follow-up): scale by the curve at the note's
- // clip-local start beat.
- float vel = note.velocity;
- if (hasVel) vel *= std::clamp(clip.velocityEnvelope.valueAt(note.startBeat), 0.0f, 1.0f);
- if (clipActive && onS >= blockStart && onS < blockStart + frames && n < 1024)
- evs[n++] = {static_cast<int32_t>(onS - blockStart), true, note.pitch, vel,
- static_cast<float>((offS - onS) / spb)};
- // Loop seam: a note still sounding at the loop end releases here, ahead of any
- // chase re-trigger at the same offset (offs sort first).
- if (seamOffs_ && onS < seamEndSamples_ && offS >= seamEndSamples_ && n < 1024)
- evs[n++] = {0, false, note.pitch, 0.0f};
- // Chase: a note already held at the jump point starts sounding right here.
- if (chaseNotes_ && clipActive && onS < blockStart && offS > blockStart && n < 1024)
- evs[n++] = {0, true, note.pitch, vel};
- if (offS >= blockStart && offS < blockStart + frames && n < 1024)
- evs[n++] = {static_cast<int32_t>(offS - blockStart), false, note.pitch, 0.0f};
- // Recorded MPE: the note's curve while it sounds in this block.
- if (xev && note.expr && clipActive)
- noteExprEvents(note, clipStart + note.startBeat * spb - blockStart, offS - blockStart, frames, spb,
- xev, *xn, kMaxBlockExpr); // curve timed from the true start
- }
+ // Track MIDI offset (ms → samples at the device rate). Playback-only: the shift
+ // is applied to the scheduled times below, never to the stored notes.
+ // A track without a map and without an offset (most tracks) pays nothing per note here:
+ // the per-note articulation lookup is skipped and the shift stays a constant zero.
+ const double msToS = transport_.sampleRate() / 1000.0;
+ const double trackShiftS = t.midiOffsetMs() * msToS;
+ const ArticulationTable* artTable = t.articulationTable.get();
+ const auto gatherClip = [&]<bool shifted>() {
+ for (const Note& note : clip.notes) {
+ // FR-018: track offset + the note's articulation offset, applied once (specs/085).
+ double shiftS = 0.0;
+ if constexpr (shifted)
+ shiftS = artTable ? trackShiftS + articulationOffsetMs(artTable, note.articulation) * msToS : trackShiftS;
+ // Clip length gates note starts (M4-2): notes outside don't play. A note that
+ // starts before the clip (a count-in pickup recorded into a take at 1.1, #56)
+ // sounds from the clip start for the part that reaches into it.
+ if (note.startBeat >= clip.lengthBeats || note.startBeat + note.lengthBeats <= 0.0) continue;
+ const double nominalOn = clipStart + std::max(0.0, note.startBeat) * spb;
+ // A trimmed clip cuts the tail: a note that runs past the clip's (possibly
+ // shortened) end stops at the boundary instead of sounding its full length.
+ double nominalOff = clipStart + (note.startBeat + note.lengthBeats) * spb;
+ if (nominalOff > clipEnd) nominalOff = clipEnd;
+ const double onS = shifted ? nominalOn + shiftS : nominalOn;
+ const double offS = shifted ? nominalOff + shiftS : nominalOff;
+ // Velocity envelope (M9 follow-up): scale by the curve at the note's
+ // clip-local start beat.
+ float vel = note.velocity;
+ if (hasVel) vel *= std::clamp(clip.velocityEnvelope.valueAt(note.startBeat), 0.0f, 1.0f);
+ if (clipActive && onS >= blockStart && onS < blockStart + frames && n < 1024)
+ evs[n++] = {static_cast<int32_t>(onS - blockStart), true, note.pitch, vel,
+ static_cast<float>((offS - onS) / spb)};
+ // Loop seam: a note still sounding at the loop end releases here, ahead of any
+ // chase re-trigger at the same offset (offs sort first).
+ if (seamOffs_ && onS < seamEndSamples_ && offS >= seamEndSamples_ && n < 1024)
+ evs[n++] = {0, false, note.pitch, 0.0f};
+ // Chase: a note already held at the jump point starts sounding right here.
+ if (chaseNotes_ && clipActive && onS < blockStart && offS > blockStart && n < 1024)
+ evs[n++] = {0, true, note.pitch, vel};
+ if (offS >= blockStart && offS < blockStart + frames && n < 1024)
+ evs[n++] = {static_cast<int32_t>(offS - blockStart), false, note.pitch, 0.0f};
+ // Recorded MPE: the note's curve while it sounds in this block.
+ if (xev && note.expr && clipActive)
+ noteExprEvents(note, (shifted ? clipStart + note.startBeat * spb + shiftS : clipStart + note.startBeat * spb) - blockStart,
+ offS - blockStart, frames, spb,
+ xev, *xn, kMaxBlockExpr); // curve timed from the true start
+ }
+ };
+ if (!artTable && trackShiftS == 0.0) gatherClip.template operator()<false>();
+ else gatherClip.template operator()<true>();
// The clip's controllers (specs/020).
if (xev && clipActive)
clipCtlEvents(clip, clipStart, clipEnd, blockStart, frames, spb, chaseNotes_, xev, *xn, kMaxBlockExpr);
@@ -1500,7 +1537,26 @@ void Engine::renderInstrumentRaw(
std::sort(evs, evs + n, midiEvLess);
std::stable_sort(xev, xev + xn, [](const ExprEv& a, const ExprEv& b) { return a.off < b.off; });
- playEvents(*inst, dst, frames, evs, n, xev, xn, spb > 0.0 ? blockStart / spb : 0.0, spb, playing, [&] {
+
+ // Articulation MIDI (specs/085): the track's own arrangement clips, past its MIDI FX, only to an
+ // instrument that takes it. A stack array like the notes' (AR-6); overflow is dropped, never grown.
+ ArtEv aev[kMaxBlockArt];
+ int an = 0;
+ if (t.articulationTable && playing && spb > 0.0 && arrangementActive_.load(std::memory_order_relaxed) &&
+ inst->takesArticulations()) {
+ ArticulationBlock ab;
+ ab.frames = frames;
+ ab.blockStart = blockStart;
+ ab.spb = spb;
+ ab.sampleRate = transport_.sampleRate();
+ ab.trackOffsetMs = t.midiOffsetMs();
+ ab.chase = chaseNotes_;
+ ab.chaseStart = articulationChaseStart_;
+ ab.seamOffs = seamOffs_;
+ ab.seamEnd = seamEndSamples_;
+ an = scheduleArticulations(t.midiClips, *t.articulationTable, ab, aev, kMaxBlockArt);
+ }
+ playEvents(*inst, dst, frames, evs, n, xev, xn, aev, an, spb > 0.0 ? blockStart / spb : 0.0, spb, playing, [&] {
if (liveExprCount_ > 0) applyLiveExpression(g, t, *inst);
});
@@ -1539,32 +1595,44 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double s
MidiEv evs[1024];
int n = 0;
+ ExprEv xev[kMaxBlockExpr];
+ int xn = 0;
const long i0 = static_cast<long>(std::floor(p / L));
const float velGain = sp.gain;
- for (long it = i0; it <= i0 + 1; ++it) {
- if (!s.loop && it > 0) break; // one-shot: a single pass
- for (const Note& note : s.midi.notes) {
- if (note.startBeat < 0.0 || note.startBeat >= L) continue;
+ // The track's MIDI offset and each note's articulation offset (specs/085, T049), as in the
+ // arrangement: the notes stay where they are, they sound shifted. A later shift can bring a note
+ // of the previous pass into this block, so that pass is read too — only when something is late,
+ // so a slot with no offset plays exactly as before.
+ const double msToS = transport_.sampleRate() / 1000.0;
+ const ArticulationTable* artTable = t.articulationTable.get();
+ const double trackMs = t.midiOffsetMs();
+ for (const Note& note : s.midi.notes) {
+ if (note.startBeat < 0.0 || note.startBeat >= L) continue;
+ const double shiftS = artTable ? (trackMs + articulationOffsetMs(artTable, note.articulation)) * msToS : trackMs * msToS;
+ const double shiftBeats = shiftS / spb;
+ // This note's on, off, or expression can reach the block from any pass whose shifted
+ // lifetime overlaps it. Derive both bounds per note: offsets and long tails can span
+ // arbitrarily many short loops, and the block itself may cross several loops.
+ const long itLo = std::max(0L, static_cast<long>(std::floor((p - shiftBeats - note.startBeat - note.lengthBeats) / L)));
+ long itHi = static_cast<long>(std::floor((p + db - shiftBeats - note.startBeat) / L));
+ if (!s.loop) itHi = std::min(itHi, 0L);
+ for (long it = itLo; it <= itHi; ++it) {
const double onAbs = it * L + note.startBeat;
const double offAbs = onAbs + note.lengthBeats;
- if (onAbs >= p && onAbs < p + db && n < 1024)
- evs[n++] = {static_cast<int32_t>((onAbs - p) * spb), true, note.pitch, note.velocity * velGain,
+ // Unshifted: the block test in beats, as always — the next block starts at exactly p + db,
+ // so a note on the boundary falls in one block, never both or neither. Shifted: in samples.
+ const bool onIn = shiftS == 0.0 ? onAbs >= p && onAbs < p + db
+ : (onAbs - p) * spb + shiftS >= 0.0 && (onAbs - p) * spb + shiftS < frames;
+ const bool offIn = shiftS == 0.0 ? offAbs >= p && offAbs < p + db
+ : (offAbs - p) * spb + shiftS >= 0.0 && (offAbs - p) * spb + shiftS < frames;
+ if (onIn && n < 1024)
+ evs[n++] = {static_cast<int32_t>((onAbs - p) * spb + shiftS), true, note.pitch, note.velocity * velGain,
static_cast<float>(note.lengthBeats)};
- if (offAbs >= p && offAbs < p + db && n < 1024)
- evs[n++] = {static_cast<int32_t>((offAbs - p) * spb), false, note.pitch, 0.0f};
- }
- }
- // Recorded MPE of the slot's notes sounding in this block (a note may have started a pass
- // earlier, so look one iteration back).
- ExprEv xev[kMaxBlockExpr];
- int xn = 0;
- for (long it = std::max(0L, i0 - 1); it <= i0 + 1; ++it) {
- if (!s.loop && it > 0) break;
- for (const Note& note : s.midi.notes) {
- if (!note.expr || note.startBeat < 0.0 || note.startBeat >= L) continue;
- const double onAbs = it * L + note.startBeat;
- noteExprEvents(
- note, (onAbs - p) * spb, (onAbs + note.lengthBeats - p) * spb, frames, spb, xev, xn, kMaxBlockExpr);
+ if (offIn && n < 1024)
+ evs[n++] = {static_cast<int32_t>((offAbs - p) * spb + shiftS), false, note.pitch, 0.0f};
+ if (note.expr)
+ noteExprEvents(note, (onAbs - p) * spb + shiftS, (offAbs - p) * spb + shiftS, frames, spb, xev, xn,
+ kMaxBlockExpr);
}
}
// The slot clip's controllers, per loop iteration: a release at each iteration's end, then
@@ -1600,7 +1668,28 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double s
applyMidiCcRouting(t); // Arps grouped into the Instrument Rack's chains (specs/044)
// The monitored live expression, after the offset-0 notes (as in renderInstrumentRaw).
- playEvents(*inst, dst, frames, evs, n, xev, xn, p, spb, true, [&] { // the slot's own loop clock
+ // The slot's articulation MIDI (specs/085, T042), on the slot's own loop clock, past its MIDI FX.
+ ArtEv aev[kMaxBlockArt];
+ int an = 0;
+ if (artTable && spb > 0.0 && inst->takesArticulations()) {
+ ArticulationBlock ab;
+ ab.frames = frames;
+ ab.blockStart = p * spb;
+ ab.spb = spb;
+ ab.sampleRate = transport_.sampleRate();
+ ab.trackOffsetMs = t.midiOffsetMs();
+ // The first block after a launch (playedBeats resets at launch): what is in force where the
+ // slot starts — its start, or the outgoing position for a legato launch — goes out, so a
+ // switch whose lead falls before the launch isn't lost.
+ ab.chase = sp.playedBeats.load(std::memory_order_relaxed) == 0.0;
+ ab.releases = &sp.articulationReleases;
+ ab.seamOffs = false;
+ ab.seamEnd = 0.0;
+ an = scheduleSlotArticulations(s.midi, L, s.loop, *artTable, ab, aev, kMaxBlockArt);
+ } else if (sp.articulationReleases.count > 0 && inst->takesArticulations()) {
+ an = scheduleArticulationReleases(sp.articulationReleases, frames, aev, kMaxBlockArt);
+ }
+ playEvents(*inst, dst, frames, evs, n, xev, xn, aev, an, p, spb, true, [&] { // the slot's own loop clock
if (!monitoring) return;
for (int i = 0; i < liveExprCount_; ++i)
if (liveExpr_[i].trackId < 0 || liveExpr_[i].trackId == t.id())
@@ -1975,6 +2064,7 @@ void Engine::processBlock(float* out, int32_t numFrames) {
presentationFrames += seg;
}
chaseNotes_ = chase;
+ if (chase) articulationChaseStart_ = segStart;
if (g && sr > 0.0) mixGraph(g, out + done * 2, seg, segStart, playing, spb);
chaseNotes_ = chase = seamOffs_ = false;
bool countInDone = false;
@@ -2426,6 +2516,9 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// what it holds, or a note crossed while silent would sound on after unmute.
// Once, on going silent: a hosted plug-in queues each release until it renders.
if (t.instrument && !t.sessionSilentReleased) t.instrument->allNotesOff();
+ // Those voices were flushed; an old latching release must not survive the
+ // silent interval and cut a new momentary hold after mute/solo is lifted.
+ t.sessionPlayer->articulationReleases.count = 0;
t.sessionSilentReleased = true;
t.sessionPlayer->localBeats += frames / spb;
sessionPostRender(t, frames / spb);
@@ -3039,7 +3132,7 @@ bool Engine::timedEventsSelfTest() {
const ExprEv xev[] = {{20, -1, kCtlDimBase + 1, 0.5f}};
float dst[frames * 2] = {};
auto run = [&](Probe& p) {
- playEvents(p, dst, frames, evs, 4, xev, 1, 0.0, 0.0, false,
+ playEvents(p, dst, frames, evs, 4, xev, 1, nullptr, 0, 0.0, 0.0, false,
[&] { p.events.push_back({3, -1, p.eventOffset, (int32_t)p.renders.size()}); });
};
using E = std::array<int32_t, 4>;
@@ -3059,4 +3152,562 @@ bool Engine::timedEventsSelfTest() {
return seg.renders == std::vector<int32_t>{10, 10, 44} && seg.events == wantSeg;
}
+// specs/085: the articulation scheduler, block by block at exact samples, and delivery through
+// playEvents. Returns 0 on success, else the number of the first check that failed.
+int32_t Engine::articulationSelfTest() {
+ constexpr double sr = 48000.0, spb = 24000.0; // 120 BPM
+ constexpr int32_t B = 512;
+ using AK = ArticulationActionKind;
+ // 1 Long: latching, keyswitches 24/1 + 35/1 + CC58=81. 2 Legato: latching, CC58=76, lead 30 ms,
+ // offset -150 ms. 3 Pizz: momentary, keyswitch 30/127, channel 2. Default = 1.
+ const ArticulationAction actions[] = {
+ {AK::Keyswitch, 0, 24, 1}, {AK::Keyswitch, 0, 35, 1}, {AK::ControlChange, 0, 58, 81},
+ {AK::ControlChange, 0, 58, 76},
+ {AK::Keyswitch, 2, 30, 127},
+ };
+ const ArticulationEntry entries[] = {
+ {1, ArticulationTrigger::Latching, 0.0, 0.0, 0, 3},
+ {2, ArticulationTrigger::Latching, -150.0, 30.0, 3, 1},
+ {3, ArticulationTrigger::Momentary, 0.0, 0.0, 4, 1},
+ };
+ auto table = ArticulationTable::build(1, entries, 3, actions, 5);
+ if (!table) return 1;
+
+ auto makeClip = [&](std::vector<std::pair<double, int32_t>> notes, double len = 1.0) {
+ MidiClip c;
+ c.startBeat = 0.0;
+ c.lengthBeats = 8.0;
+ for (auto [beat, art] : notes) {
+ Note n;
+ n.pitch = 60;
+ n.startBeat = beat;
+ n.lengthBeats = len;
+ n.articulation = art;
+ c.notes.push_back(n);
+ }
+ c.articulations = buildArticulationTimeline(c, table);
+ return c;
+ };
+ // Beat 0 Long, beat 1 Long again (no new switch), beat 2 Legato, beat 3 Pizz (momentary),
+ // beat 4 a note with no articulation (the default: Long again, a change from Legato).
+ std::vector<MidiClip> clips{makeClip({{0.0, 1}, {1.0, 1}, {2.0, 2}, {3.0, 3}, {4.0, 0}})};
+
+ struct Abs {
+ double at;
+ ArtEvKind kind;
+ int d1, d2, ch;
+ };
+ // Play [from, to) in blocks; the first block is a chase when `chase`.
+ auto play = [&](double from, double to, double trackMs, bool chase, std::vector<Abs>& got, int* dropped = nullptr) {
+ ArtEv buf[kMaxBlockArt];
+ for (double s = from; s < to; s += B) {
+ ArticulationBlock b{B, s, spb, sr, trackMs, chase && s == from, false, 0.0};
+ b.chaseStart = chase ? from : -1.0;
+ int d = 0;
+ const int n = scheduleArticulations(clips, *table, b, buf, kMaxBlockArt, &d);
+ if (dropped) *dropped += d;
+ for (int i = 0; i < n; ++i) got.push_back({s + buf[i].off, buf[i].kind, buf[i].data1, buf[i].data2, buf[i].channel});
+ }
+ };
+ auto count = [](const std::vector<Abs>& v, ArtEvKind k, int d1) {
+ int c = 0;
+ for (auto& e : v) c += e.kind == k && e.d1 == d1;
+ return c;
+ };
+ auto at = [](const std::vector<Abs>& v, ArtEvKind k, int d1, int d2 = -1) {
+ for (auto& e : v)
+ if (e.kind == k && e.d1 == d1 && (d2 < 0 || e.d2 == d2)) return e.at;
+ return -1.0;
+ };
+
+ // ---- a straight run from the start ----
+ std::vector<Abs> run;
+ play(0.0, 6 * spb, 0.0, true, run);
+ // 2: Long at 0 in map order — key 24, key 35, CC58=81 — and its keys released 20 ms later.
+ if (run.size() < 3 || run[0].at != 0.0 || run[0].kind != ArtEvKind::KeyOn || run[0].d1 != 24 || run[1].d1 != 35 ||
+ run[2].kind != ArtEvKind::Control || run[2].d1 != 58 || run[2].d2 != 81)
+ return 2;
+ if (at(run, ArtEvKind::KeyOff, 24) != 960.0 || at(run, ArtEvKind::KeyOff, 35) != 960.0) return 3;
+ // 4: the second Long note sends nothing (still in force): Long's keys go out twice in all — at
+ // beat 0 and again at beat 4 where the default (Long) follows Legato.
+ if (count(run, ArtEvKind::KeyOn, 24) != 2) return 4;
+ // 5: Legato: offset -150 ms and lead 30 ms → 48000 − 7200 − 1440 = 39360.
+ if (at(run, ArtEvKind::Control, 58, 76) != 39360.0) return 5;
+ // 6: Pizz is momentary on channel 2: pressed with its note (beat 3), released at its end.
+ double pOn = -1, pOff = -1;
+ for (auto& e : run)
+ if (e.d1 == 30 && e.ch == 2) (e.kind == ArtEvKind::KeyOn ? pOn : pOff) = e.at;
+ if (pOn != 72000.0 || pOff != 96000.0) return 6;
+ // 7: the default after Legato: Long again at beat 4.
+ if (at(run, ArtEvKind::Control, 58, 81) != 0.0) return 7; // first one at 0 …
+ {
+ int n81 = 0;
+ for (auto& e : run) n81 += e.kind == ArtEvKind::Control && e.d1 == 58 && e.d2 == 81 && e.at == 96000.0;
+ if (n81 != 1) return 7; // … and one at beat 4
+ }
+ // 8: nothing else: 2 × Long (3 actions + 2 releases), Legato (1), Pizz (on + off).
+ if (run.size() != 2 * 5 + 1 + 2) return 8;
+
+ // ---- a track offset moves every switch with the notes ----
+ std::vector<Abs> shifted;
+ play(0.0, 6 * spb, -100.0, true, shifted);
+ if (at(shifted, ArtEvKind::Control, 58, 76) != 39360.0 - 4800.0) return 9;
+ double sOn = -1;
+ for (auto& e : shifted)
+ if (e.d1 == 30 && e.kind == ArtEvKind::KeyOn) sOn = e.at;
+ if (sOn != 72000.0 - 4800.0) return 10;
+
+ // ---- a seek into the Legato phrase: what is in force goes out once, at the landing ----
+ std::vector<Abs> seek;
+ const double land = 2.5 * spb; // 60000: past Legato's switch (39360), before Pizz
+ play(land, land + 4 * B, 0.0, true, seek);
+ if (seek.size() != 1 || seek[0].at != land || seek[0].kind != ArtEvKind::Control || seek[0].d2 != 76) return 11;
+ // 12: without a chase, nothing is re-sent mid-phrase.
+ std::vector<Abs> quiet;
+ play(land, land + 4 * B, 0.0, false, quiet);
+ if (!quiet.empty()) return 12;
+ // 13: landing inside a held momentary note chases its switch too.
+ std::vector<Abs> inPizz;
+ play(3.5 * spb, 3.5 * spb + B, 0.0, true, inPizz);
+ if (count(inPizz, ArtEvKind::KeyOn, 30) != 1 || at(inPizz, ArtEvKind::KeyOn, 30) != 3.5 * spb) return 13;
+
+ // ---- a loop wrap onto a change at the loop start: no stale chase ahead of it ----
+ {
+ std::vector<Abs> wrap;
+ ArtEv buf[kMaxBlockArt];
+ ArticulationBlock b{B, 4 * spb, spb, sr, 0.0, true, true, 6 * spb}; // looping 4..6, just wrapped
+ const int n = scheduleArticulations(clips, *table, b, buf, kMaxBlockArt);
+ for (int i = 0; i < n; ++i) wrap.push_back({b.blockStart + buf[i].off, buf[i].kind, buf[i].data1, buf[i].data2, buf[i].channel});
+ // 14: Long's change lands on the block's first sample; the chase (Legato, in force before) is skipped.
+ if (count(wrap, ArtEvKind::Control, 58) != 1 || at(wrap, ArtEvKind::Control, 58, 81) != 4 * spb) return 14;
+ }
+ // 15: a seam lets go of a key pressed just before it.
+ {
+ std::vector<MidiClip> one{makeClip({{0.0, 1}})};
+ ArtEv buf[kMaxBlockArt];
+ ArticulationBlock b{B, 0.0, spb, sr, 0.0, false, true, 100.0}; // the key went down at 0, the seam came at 100
+ const int n = scheduleArticulations(one, *table, b, buf, kMaxBlockArt);
+ int offsAt0 = 0;
+ for (int i = 0; i < n; ++i) offsAt0 += buf[i].kind == ArtEvKind::KeyOff && buf[i].off == 0;
+ if (offsAt0 != 2) return 15;
+ }
+ // 16: releases sort before presses at the same sample.
+ {
+ std::vector<MidiClip> tight{makeClip({{0.0, 1}, {0.04, 3}}, 0.01)}; // Pizz 20 ms in = Long's release
+ ArtEv buf[kMaxBlockArt];
+ ArticulationBlock b{2048, 0.0, spb, sr, 0.0, false, false, 0.0};
+ const int n = scheduleArticulations(tight, *table, b, buf, kMaxBlockArt);
+ int firstOn = -1, lastOff = -1;
+ for (int i = 0; i < n; ++i)
+ if (buf[i].off == 960) {
+ if (buf[i].kind == ArtEvKind::KeyOff) lastOff = i;
+ else if (firstOn < 0) firstOn = i;
+ }
+ if (firstOn < 0 || lastOff < 0 || lastOff > firstOn) return 16;
+ }
+ // 17: a full buffer drops and counts, never overruns.
+ {
+ ArtEv small[2];
+ int dropped = 0;
+ ArticulationBlock b{B, 0.0, spb, sr, 0.0, false, false, 0.0};
+ const int n = scheduleArticulations(clips, *table, b, small, 2, &dropped);
+ if (n != 2 || dropped != 1) return 17;
+ }
+ // 18: an inactive clip sends nothing.
+ {
+ std::vector<MidiClip> off = clips;
+ off[0].active = false;
+ ArtEv buf[kMaxBlockArt];
+ ArticulationBlock b{B, 0.0, spb, sr, 0.0, true, false, 0.0};
+ if (scheduleArticulations(off, *table, b, buf, kMaxBlockArt) != 0) return 18;
+ }
+
+ // ---- delivery: ahead of the note at the same offset, on its channel, channel reset after ----
+ struct Probe final : Instrument {
+ std::vector<std::array<int32_t, 5>> events; // kind (1 on, 0 off, 2 cc, 3 program), d1, d2, offset, channel
+ bool articulations = false;
+ bool takesTimedEvents() const override { return true; }
+ bool takesArticulations() const override { return articulations; }
+ void setSampleRate(double) override {}
+ void noteOn(int32_t p, float v) override { events.push_back({1, p, (int32_t)std::lround(v * 127.0f), eventOffset, eventChannel}); }
+ void noteOff(int32_t p) override { events.push_back({0, p, 0, eventOffset, eventChannel}); }
+ void allNotesOff() override {}
+ void controller(int32_t c, float v) override { events.push_back({2, c, (int32_t)std::lround(v * 127.0f), eventOffset, eventChannel}); }
+ void programChange(int32_t p) override { events.push_back({3, p, 0, eventOffset, eventChannel}); }
+ void noteExpression(int32_t p, int32_t, float v) override {
+ events.push_back({4, p, (int32_t)std::lround(v * 127.0f), eventOffset, eventChannel});
+ }
+ void render(float*, int32_t) override {}
+ };
+ Probe p;
+ if (p.takesArticulations()) return 19; // the default is no: a built-in never gets keyswitches
+ const MidiEv evs[] = {{100, true, 60, 0.5f}};
+ const ArtEv aev[] = {{100, 0, ArtEvKind::KeyOn, 0, 24, 1}, {100, 1, ArtEvKind::Control, 5, 58, 81}, {100, 2, ArtEvKind::Program, 0, 12, 0}};
+ float dst[B * 2] = {};
+ playEvents(p, dst, B, evs, 1, nullptr, 0, aev, 3, 0.0, spb, true, [] {});
+ using E5 = std::array<int32_t, 5>;
+ const std::vector<E5> want = {{1, 24, 1, 100, 0}, {2, 58, 81, 100, 5}, {3, 12, 0, 100, 0}, {1, 60, 64, 100, 0}};
+ if (p.events != want) return 20;
+ if (p.eventChannel != 0) return 21;
+
+ // 22: changing only a note's articulation makes the published timeline stale (publishRaw
+ // rebuilds it), and the rebuilt one switches there.
+ {
+ MidiClip c = makeClip({{0.0, 1}, {1.0, 1}});
+ MidiClip edited = c;
+ edited.notes[1].articulation = 2;
+ if (articulationNotesKey(c) == articulationNotesKey(edited)) return 22;
+ if (!articulationTimelineCurrent(c, table) || articulationTimelineCurrent(edited, table)) return 22;
+ auto rebuilt = buildArticulationTimeline(edited, table);
+ if (rebuilt->changes.size() != 2 || rebuilt->changes[1].entryId != 2) return 22;
+ }
+
+ // ---- Session slots (T042): the slot's clip looped every 2 beats on its own clock ----
+ {
+ MidiClip slot = makeClip({{0.0, 1}, {1.0, 2}}); // Long at 0, Legato at 1, each pass
+ constexpr double L = 2.0;
+ auto playSlot = [&](bool loop, double from, double to, std::vector<Abs>& got) {
+ ArtEv buf[kMaxBlockArt];
+ for (double s = from; s < to; s += B) {
+ ArticulationBlock b{B, s, spb, sr, 0.0, false, false, 0.0};
+ const int n = scheduleSlotArticulations(slot, L, loop, *table, b, buf, kMaxBlockArt);
+ for (int i = 0; i < n; ++i) // the last block runs past `to`: count only what falls before it
+ if (s + buf[i].off < to) got.push_back({s + buf[i].off, buf[i].kind, buf[i].data1, buf[i].data2, buf[i].channel});
+ }
+ };
+ std::vector<Abs> looped;
+ playSlot(true, 0.0, 3 * L * spb, looped);
+ // 23: each pass switches to Long at its start and to Legato (−150 ms, lead 30 ms) after —
+ // three passes, three of each, at their places (Legato: pass k at k·48000 + 24000 − 8640).
+ int longs = 0, legatos = 0;
+ bool placed = true;
+ for (auto& e : looped) {
+ if (e.kind == ArtEvKind::KeyOn && e.d1 == 24) { ++longs; placed &= std::fmod(e.at, L * spb) == 0.0; }
+ if (e.kind == ArtEvKind::Control && e.d2 == 76) { ++legatos; placed &= std::fmod(e.at, L * spb) == 24000.0 - 8640.0; }
+ }
+ if (longs != 3 || legatos != 3 || !placed) return 23;
+ // 24: a one-shot slot plays its single pass.
+ std::vector<Abs> once;
+ playSlot(false, 0.0, 3 * L * spb, once);
+ if (count(once, ArtEvKind::KeyOn, 24) != 1 || count(once, ArtEvKind::Control, 58) != 2) return 24;
+ // 25: a launch sends the switch whose lead falls before it, and an early switch reaches back
+ // across the loop end. Legato on beat 0 (−150 ms, lead 30 ms) and Long on beat 1 of each pass:
+ // the launch block's chase sends Legato at 0; after that, each pass's Legato goes out at the
+ // end of the pass before (k·48000 − 8640) and its Long at k·48000 + 24000.
+ MidiClip early = makeClip({{0.0, 2}, {1.0, 1}});
+ std::vector<Abs> back;
+ ArtEv buf[kMaxBlockArt];
+ for (double s = 0.0; s < 2 * L * spb; s += B) {
+ ArticulationBlock b{B, s, spb, sr, 0.0, s == 0.0, false, 0.0};
+ const int n = scheduleSlotArticulations(early, L, true, *table, b, buf, kMaxBlockArt);
+ for (int i = 0; i < n; ++i)
+ if (s + buf[i].off < 2 * L * spb) back.push_back({s + buf[i].off, buf[i].kind, buf[i].data1, buf[i].data2, buf[i].channel});
+ }
+ std::vector<double> legatoAt, longAt;
+ for (auto& e : back) {
+ if (e.kind == ArtEvKind::Control && e.d2 == 76) legatoAt.push_back(e.at);
+ if (e.kind == ArtEvKind::KeyOn && e.d1 == 24) longAt.push_back(e.at);
+ }
+ if (legatoAt != std::vector<double>{0.0, L * spb - 8640.0, 2 * L * spb - 8640.0} ||
+ longAt != std::vector<double>{24000.0, L * spb + 24000.0})
+ return 25;
+ }
+
+ // 26: a chase in a block shorter than 20 ms lets go exactly 20 ms later, in a subsequent block.
+ {
+ std::vector<Abs> got;
+ const double land = 0.5 * spb; // inside the first Long phrase
+ play(land, land + 3 * B, 0.0, true, got);
+ if (count(got, ArtEvKind::KeyOn, 24) != 1 || count(got, ArtEvKind::KeyOff, 24) != 1 ||
+ at(got, ArtEvKind::KeyOn, 24) != land || at(got, ArtEvKind::KeyOff, 24) != land + 960.0) return 26;
+ }
+
+ // 27: overlapping clips share the instrument's state. Clip A: Long at beats 0 and 2; clip B:
+ // Legato at beat 1. Beat 2's Long must be sent again — B changed the articulation in between.
+ {
+ std::vector<MidiClip> overlap{makeClip({{0.0, 1}, {2.0, 1}}), makeClip({{1.0, 2}})};
+ std::vector<Abs> got;
+ ArtEv buf[kMaxBlockArt];
+ for (double s = 0.0; s < 3 * spb; s += B) {
+ ArticulationBlock b{B, s, spb, sr, 0.0, s == 0.0, false, 0.0};
+ const int n = scheduleArticulations(overlap, *table, b, buf, kMaxBlockArt);
+ for (int i = 0; i < n; ++i) got.push_back({s + buf[i].off, buf[i].kind, buf[i].data1, buf[i].data2, buf[i].channel});
+ }
+ int longs = 0, legatos = 0;
+ for (auto& e : got) {
+ longs += e.kind == ArtEvKind::Control && e.d2 == 81;
+ legatos += e.kind == ArtEvKind::Control && e.d2 == 76;
+ }
+ if (longs != 2 || legatos != 1 || at(got, ArtEvKind::Control, 58, 81) != 0.0) return 27;
+ }
+
+ // 28: two overlapping momentary notes on the same key: the shorter one ending doesn't let go of
+ // the key the longer one still holds. Pizz (key 30, channel 2) 3.0–5.0 and 3.5–3.75 beats.
+ {
+ MidiClip c;
+ c.startBeat = 0.0;
+ c.lengthBeats = 8.0;
+ for (auto [start, len] : {std::pair{3.0, 2.0}, std::pair{3.5, 0.25}}) {
+ Note n;
+ n.pitch = 60;
+ n.startBeat = start;
+ n.lengthBeats = len;
+ n.articulation = 3;
+ c.notes.push_back(n);
+ }
+ c.articulations = buildArticulationTimeline(c, table);
+ std::vector<MidiClip> one{c};
+ std::vector<Abs> got;
+ ArtEv buf[kMaxBlockArt];
+ for (double s = 0.0; s < 6 * spb; s += B) {
+ ArticulationBlock b{B, s, spb, sr, 0.0, false, false, 0.0};
+ const int n = scheduleArticulations(one, *table, b, buf, kMaxBlockArt);
+ for (int i = 0; i < n; ++i) got.push_back({s + buf[i].off, buf[i].kind, buf[i].data1, buf[i].data2, buf[i].channel});
+ }
+ int earlyOff = 0, finalOff = 0;
+ for (auto& e : got)
+ if (e.kind == ArtEvKind::KeyOff && e.d1 == 30) {
+ earlyOff += e.at == 3.75 * spb;
+ finalOff += e.at == 5.0 * spb;
+ }
+ if (earlyOff != 0 || finalOff != 1) return 28;
+ }
+
+ // 29: a short slot with a large offset: a one-beat loop (24000 samples = 500 ms) with a +1500 ms
+ // momentary articulation — each pass's switch lands three passes later and must not be lost.
+ {
+ const ArticulationAction late[] = {{AK::Keyswitch, 0, 40, 100}};
+ const ArticulationEntry lateE[] = {{1, ArticulationTrigger::Momentary, 1500.0, 0.0, 0, 1}};
+ auto lateTable = ArticulationTable::build(0, lateE, 1, late, 1);
+ if (!lateTable) return 29;
+ MidiClip slot;
+ slot.lengthBeats = 1.0;
+ Note n;
+ n.pitch = 60;
+ n.startBeat = 0.0;
+ n.lengthBeats = 0.25;
+ n.articulation = 1;
+ slot.notes.push_back(n);
+ slot.articulations = buildArticulationTimeline(slot, lateTable);
+ std::vector<double> ons;
+ ArtEv buf[kMaxBlockArt];
+ for (double s = 0.0; s < 6 * spb; s += B) {
+ ArticulationBlock b{B, s, spb, sr, 0.0, false, false, 0.0};
+ const int cnt = scheduleSlotArticulations(slot, 1.0, true, *lateTable, b, buf, kMaxBlockArt);
+ for (int i = 0; i < cnt; ++i)
+ if (buf[i].kind == ArtEvKind::KeyOn && s + buf[i].off < 6 * spb) ons.push_back(s + buf[i].off);
+ }
+ // Passes 0, 1, 2 land at 72000, 96000, 120000; pass 3 would land at 144000, past the window.
+ if (ons != std::vector<double>{72000.0, 96000.0, 120000.0}) return 29;
+
+ // 30: a 31.25 ms loop requires looking 48 passes back for this same offset. Its release
+ // must also survive. Read just the block containing the first on, then the first off.
+ slot.lengthBeats = 0.0625;
+ slot.notes[0].lengthBeats = 0.03125;
+ slot.articulations = buildArticulationTimeline(slot, lateTable);
+ for (bool release : {false, true}) {
+ const double due = 72000.0 + (release ? 750.0 : 0.0);
+ ArticulationBlock b{B, due - 100, spb, sr, 0.0, false, false, 0.0};
+ const int cnt = scheduleSlotArticulations(slot, 0.0625, true, *lateTable, b, buf, kMaxBlockArt);
+ if (cnt != 1 || buf[0].off != 100 || buf[0].kind != (release ? ArtEvKind::KeyOff : ArtEvKind::KeyOn)) return 30;
+ }
+ }
+
+ // 31: different momentary articulations in separate clips can hold the same explicit key.
+ {
+ ArticulationAction keys[] = {{AK::Keyswitch, 2, 30, 100}, {AK::Keyswitch, 2, 30, 100}};
+ const ArticulationEntry entries[] = {{1, ArticulationTrigger::Momentary, 0, 0, 0, 1},
+ {2, ArticulationTrigger::Momentary, 0, 0, 1, 1}};
+ for (bool defaultChannel : {false, true}) {
+ keys[0].channel = defaultChannel ? 0 : 2;
+ keys[1].channel = defaultChannel ? 1 : 2;
+ auto shared = ArticulationTable::build(0, entries, 2, keys, 2);
+ auto a = makeClip({{0.0, 1}}, 2.0), b = makeClip({{0.5, 2}}, 0.5);
+ a.articulations = buildArticulationTimeline(a, shared);
+ b.articulations = buildArticulationTimeline(b, shared);
+ ArtEv buf[kMaxBlockArt];
+ ArticulationBlock block{B, spb - 100, spb, sr};
+ if (scheduleArticulations({a, b}, *shared, block, buf, kMaxBlockArt) != 0) return 31;
+ block.blockStart = 2 * spb - 100;
+ const int cnt = scheduleArticulations({a, b}, *shared, block, buf, kMaxBlockArt);
+ if (cnt != 1 || buf[0].off != 100 || buf[0].kind != ArtEvKind::KeyOff || buf[0].channel != keys[0].channel) return 31;
+ }
+ }
+
+ // Exercise Session rendering itself, capturing the events delivered to a timed instrument.
+ auto slotEngine = std::make_unique<Engine>();
+ slotEngine->transport_.setSampleRate(sr);
+ Track track(1, TrackType::Instrument);
+ auto probe = std::make_shared<Probe>();
+ track.instrument = probe;
+ track.sessionSlots.resize(1);
+ track.sessionPlayer->playing.store(0);
+ auto& slot = track.sessionSlots[0];
+ slot.hasClip = true;
+ slot.lengthBeats = 1.0;
+ Note note;
+ note.startBeat = 0.5;
+ note.lengthBeats = 0.25;
+ note.articulation = 1;
+ auto expr = std::make_shared<NoteExpr>();
+ expr->dim[ExprPressure] = {{0.0f, 0.25f}, {0.25f, 0.75f}};
+ note.expr = expr;
+ slot.midi.notes = {note};
+ // 32: both positive and negative track + articulation offsets move opening expression with
+ // its note. It starts at 0.25 pressure at the note-on, never partway through the curve.
+ for (double offset : {-100.0, 100.0}) {
+ const ArticulationEntry entry{1, ArticulationTrigger::Latching, offset, 0, 0, 0};
+ track.articulationTable = ArticulationTable::build(0, &entry, 1, nullptr, 0);
+ track.setMidiOffsetMs(offset);
+ track.sessionPlayer->localBeats = offset < 0 ? 0.09375 : 0.890625;
+ probe->events.clear();
+ slotEngine->renderSessionSlotRaw(track, dst, B, spb);
+ const int32_t at = offset < 0 ? 150 : 225;
+ const E5 on{1, 60, 102, at, 0}, pressure{4, 60, 32, at, 0};
+ if (std::find(probe->events.begin(), probe->events.end(), on) == probe->events.end() ||
+ std::find(probe->events.begin(), probe->events.end(), pressure) == probe->events.end()) return 32;
+ }
+ // 33: a note release more than one pass after its start must still reach the instrument.
+ track.articulationTable.reset();
+ track.setMidiOffsetMs(0);
+ slot.midi.notes[0].expr.reset();
+ slot.midi.notes[0].startBeat = 0;
+ slot.midi.notes[0].lengthBeats = 3;
+ track.sessionPlayer->localBeats = 3.0 - 0.015625;
+ probe->events.clear();
+ slotEngine->renderSessionSlotRaw(track, dst, B, spb);
+ if (std::find(probe->events.begin(), probe->events.end(), E5{0, 60, 0, 375, 0}) == probe->events.end()) return 33;
+
+ // 34: even one-frame render segments preserve the full chased-key hold.
+ {
+ ArtEv buf[kMaxBlockArt];
+ const double land = 0.5 * spb;
+ ArticulationBlock b{1, land, spb, sr, 0.0, true};
+ b.chaseStart = land;
+ if (scheduleArticulations(clips, *table, b, buf, kMaxBlockArt) != 3) return 34;
+ b.chase = false;
+ b.blockStart = land + 960;
+ const int cnt = scheduleArticulations(clips, *table, b, buf, kMaxBlockArt);
+ if (cnt != 2 || buf[0].kind != ArtEvKind::KeyOff || buf[0].off != 0 || buf[1].kind != ArtEvKind::KeyOff) return 34;
+ }
+ // 35: launch and legato launch restore a pre-launch switch through the real Session renderer,
+ // and its release reaches the next block rather than being shortened to this block.
+ {
+ const ArticulationAction key{AK::Keyswitch, 0, 24, 100};
+ const ArticulationEntry entry{1, ArticulationTrigger::Latching, 0, 30, 0, 1};
+ track.articulationTable = ArticulationTable::build(0, &entry, 1, &key, 1);
+ slot.midi.notes[0].lengthBeats = 1;
+ slot.midi.articulations = buildArticulationTimeline(slot.midi, track.articulationTable);
+ probe->articulations = true;
+ for (bool legato : {false, true}) {
+ track.sessionPlayer->localBeats = legato ? 0.5 : 0.0;
+ track.sessionPlayer->requestLaunch(0, 0, legato);
+ if (!track.sessionPlayer->maybeApply(0, B / spb, 0)) return 35;
+ probe->events.clear();
+ slotEngine->renderSessionSlotRaw(track, dst, B, spb);
+ if (std::find(probe->events.begin(), probe->events.end(), E5{1, 24, 100, 0, 0}) == probe->events.end()) return 35;
+ track.sessionPlayer->publish(B / spb);
+ probe->events.clear();
+ slotEngine->renderSessionSlotRaw(track, dst, B, spb);
+ if (std::find(probe->events.begin(), probe->events.end(), E5{0, 24, 0, 448, 0}) == probe->events.end()) return 35;
+ }
+ }
+ // 36: Session releases count rendered frames, even when tempo changes between the press and
+ // release at a nonzero legato position. Check both faster and slower tempo, natural switches,
+ // and clearing the map while the key is held. Every release still lands at frame 960.
+ {
+ const ArticulationAction keys[] = {{AK::Keyswitch, 0, 24, 100}, {AK::Keyswitch, 0, 25, 100}};
+ const ArticulationEntry entries[] = {{1, ArticulationTrigger::Latching, 0, 0, 0, 1},
+ {2, ArticulationTrigger::Latching, 0, 0, 1, 1}};
+ const auto mapped = ArticulationTable::build(0, entries, 2, keys, 2);
+ slot.midi.notes = makeClip({{0.0, 1}, {0.5, 2}}, 0.25).notes;
+ slot.midi.articulations = buildArticulationTimeline(slot.midi, mapped);
+ for (bool chase : {false, true})
+ for (double nextSpb : {spb / 2, spb * 2})
+ for (bool clearMap : {false, true}) {
+ track.articulationTable = mapped;
+ track.sessionPlayer->localBeats = chase ? 8.125 : 8.0;
+ track.sessionPlayer->requestLaunch(0, 0, true);
+ if (!track.sessionPlayer->maybeApply(0, B / spb, 0)) return 36;
+ if (!chase) track.sessionPlayer->playedBeats.store(1.0); // normal beat-8 switch, not a chase
+ probe->events.clear();
+ slotEngine->renderSessionSlotRaw(track, dst, B, spb);
+ if (std::count(probe->events.begin(), probe->events.end(), E5{1, 24, 100, 0, 0}) != 1 ||
+ track.sessionPlayer->articulationReleases.count != 1) return 36;
+ track.sessionPlayer->publish(B / spb);
+ if (clearMap) track.articulationTable.reset();
+ probe->events.clear();
+ slotEngine->renderSessionSlotRaw(track, dst, B, nextSpb);
+ if (std::count(probe->events.begin(), probe->events.end(), E5{0, 24, 0, 448, 0}) != 1 ||
+ track.sessionPlayer->articulationReleases.count != 0) return 36;
+ }
+ }
+ // 37: a bounded pending queue never presses a key whose release can't be retained. Due offs
+ // have priority, and an output buffer too small for them carries the rest to the next block.
+ {
+ std::vector<ArticulationAction> keys;
+ for (int i = 0; i <= kMaxBlockArt; ++i) keys.push_back({AK::Keyswitch, 1 + i / 128, i % 128, 100});
+ const ArticulationEntry entry{1, ArticulationTrigger::Latching, 0, 0, 0, static_cast<int32_t>(keys.size())};
+ auto many = ArticulationTable::build(0, &entry, 1, keys.data(), static_cast<int32_t>(keys.size()));
+ MidiClip clip = makeClip({{0.0, 1}});
+ clip.articulations = buildArticulationTimeline(clip, many);
+ ArticulationReleaseState pending;
+ ArticulationBlock b{1, 0, spb, sr};
+ b.releases = &pending;
+ ArtEv buf[kMaxBlockArt];
+ int dropped = 0;
+ if (scheduleSlotArticulations(clip, 8, true, *many, b, buf, kMaxBlockArt, &dropped) != kMaxBlockArt ||
+ dropped != 1 || pending.count != kMaxBlockArt) return 37;
+ if (scheduleArticulationReleases(pending, 960, buf, kMaxBlockArt) != kMaxBlockArt || pending.count != 0) return 37;
+ for (int i = 0; i < kMaxBlockArt; ++i)
+ if (buf[i].kind != ArtEvKind::KeyOff || buf[i].off != 959 || buf[i].channel != keys[i].channel ||
+ buf[i].data1 != keys[i].data1) return 37;
+ pending.pending[0] = {0, 2, 30};
+ pending.pending[1] = {0, 3, 31};
+ pending.count = 2;
+ if (scheduleArticulationReleases(pending, 1, buf, 1) != 1 || pending.count != 1 || buf[0].data1 != 30) return 37;
+ if (scheduleArticulationReleases(pending, 1, buf, 1) != 1 || pending.count != 0 || buf[0].data1 != 31) return 37;
+ track.sessionPlayer->articulationReleases.count = 1;
+ track.sessionPlayer->requestLaunch(0, 0, true);
+ if (!track.sessionPlayer->maybeApply(0, 1, 0) || track.sessionPlayer->articulationReleases.count != 0) return 37;
+ track.sessionPlayer->articulationReleases.count = 1;
+ track.sessionPlayer->requestStopNow();
+ if (!track.sessionPlayer->maybeApply(0, 1, 0) || track.sessionPlayer->articulationReleases.count != 0) return 37;
+ }
+ // 38: mute/solo gating flushes an old latching hold. Its obsolete release must never resume
+ // after unmuting and cut a new momentary hold of the same key.
+ for (bool soloGate : {false, true}) {
+ auto engine = std::make_unique<Engine>();
+ const int id = engine->addInstrumentTrack(), other = engine->addAudioTrack();
+ auto target = engine->cloneTrack(*engine->findTrackAuthoring(id));
+ auto capture = std::make_shared<Probe>();
+ capture->articulations = true;
+ target->instrument = capture;
+ const ArticulationAction key{AK::Keyswitch, 0, 24, 100};
+ const ArticulationEntry entries[] = {{1, ArticulationTrigger::Latching, 0, 0, 0, 1},
+ {2, ArticulationTrigger::Momentary, 0, 0, 0, 1}};
+ target->articulationTable = ArticulationTable::build(0, entries, 2, &key, 1);
+ target->sessionSlots.resize(1);
+ auto& clip = target->sessionSlots[0];
+ clip.hasClip = true;
+ clip.lengthBeats = 4;
+ clip.midi.notes = makeClip({{0.0, 1}, {0.046875, 2}}, 1.0).notes; // momentary starts at frame 1125
+ engine->republishWithTrack(id, target);
+ engine->setLaunchQuant(0);
+ engine->transportPlay();
+ engine->launchSlot(id, 0);
+ engine->renderOffline(dst, B, sr); // first 512 frames: latching key has 448 frames left
+ if (target->sessionPlayer->articulationReleases.count != 1) return 38;
+ if (soloGate) engine->setTrackSolo(other, true); else engine->setTrackMute(id, true);
+ engine->renderOffline(dst, 256, sr); // the mute flushes voices; the slot still advances
+ if (soloGate) engine->setTrackSolo(other, false); else engine->setTrackMute(id, false);
+ capture->events.clear();
+ engine->renderOffline(dst, B, sr); // momentary key at offset 357, obsolete off would be 448
+ if (target->sessionPlayer->articulationReleases.count != 0 ||
+ std::count(capture->events.begin(), capture->events.end(), E5{1, 24, 100, 357, 0}) != 1 ||
+ std::any_of(capture->events.begin(), capture->events.end(), [](const E5& e) { return e[0] == 0 && e[1] == 24; })) return 38;
+ }
+ return 0;
+}
+
} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
index 4156ed7c..e86dd3f4 100644
--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
@@ -3671,6 +3671,9 @@ std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId, b
nt->setInputChannels(src.inputChannels());
nt->setMonitor(src.monitor());
nt->setMidiFromTrackId(src.midiFromTrackId());
+ nt->setMidiOffsetMs(src.midiOffsetMs());
+ nt->articulationTable = src.articulationTable; // the map goes with the instrument, content or not
+ nt->articulationMapJson = src.articulationMapJson;
for (int b = 0; b < kMaxReturns; ++b) nt->setSend(b, src.send(b));
if (withContent) {
nt->clips = src.clips; // sample buffers are shared_ptr (immutable) — fine
@@ -4185,6 +4188,7 @@ Note Engine::noteFromData(const NotaNoteData& d) const {
n.startBeat = d.start_beat;
n.lengthBeats = d.length_beats;
n.velocity = d.velocity;
+ n.articulation = d.articulation_id > 0 ? d.articulation_id : 0;
if (d.expr_id > 0) {
std::lock_guard<std::mutex> lk(exprMx_);
auto it = exprStore_.find(d.expr_id);
@@ -4202,6 +4206,66 @@ void Engine::noteToData(const Note& n, NotaNoteData& d) {
d.length_beats = n.lengthBeats;
d.velocity = n.velocity;
d.expr_id = n.expr ? n.exprId : 0;
+ d.articulation_id = n.articulation;
+}
+
+// --- articulation maps (specs/085) ---------------------------------------------------------
+
+namespace {
+constexpr int32_t kMaxArticulationJson = 16 * 1024 * 1024; // the map file's own limit
+}
+
+bool Engine::setTrackArticulationMap(int32_t trackId, int32_t defaultId, const NotaArticulationEntry* entries,
+ int32_t entryCount, const NotaArticulationAction* actions, int32_t actionCount, const char* json, int32_t jsonLen) {
+ auto old = findTrackAuthoring(trackId);
+ if (!old || old->type() != TrackType::Instrument) return false;
+ if (jsonLen < 0 || jsonLen > kMaxArticulationJson || (jsonLen > 0 && !json)) return false;
+ // Sizes checked before anything is allocated for them; the rest is ArticulationTable::build's.
+ if (entryCount < 0 || actionCount < 0 || entryCount > kArticulationMaxEntries || actionCount > kArticulationMaxActions)
+ return false;
+ if ((entryCount > 0 && !entries) || (actionCount > 0 && !actions)) return false;
+ std::vector<ArticulationEntry> e(static_cast<size_t>(entryCount));
+ for (int32_t i = 0; i < entryCount; ++i) {
+ const NotaArticulationEntry& s = entries[i];
+ e[i] = {s.id, static_cast<ArticulationTrigger>(s.trigger_mode), s.offset_ms, s.lead_ms, s.action_start, s.action_count};
+ }
+ std::vector<ArticulationAction> a(static_cast<size_t>(actionCount));
+ for (int32_t i = 0; i < actionCount; ++i) {
+ const NotaArticulationAction& s = actions[i];
+ a[i] = {static_cast<ArticulationActionKind>(s.kind), s.channel, s.data1, s.data2};
+ }
+ auto table = ArticulationTable::build(defaultId, e.data(), entryCount, a.data(), actionCount);
+ if (!table) return false;
+ auto nt = cloneTrack(*old);
+ nt->articulationTable = std::move(table);
+ nt->articulationMapJson = std::make_shared<const std::string>(json ? json : "", static_cast<size_t>(jsonLen));
+ republishWithTrack(trackId, nt); // the clips' timelines are rebuilt as it publishes
+ return true;
+}
+
+bool Engine::clearTrackArticulationMap(int32_t trackId) {
+ auto old = findTrackAuthoring(trackId);
+ if (!old || old->type() != TrackType::Instrument) return false;
+ if (!old->articulationTable && !old->articulationMapJson) return true; // nothing to undo
+ auto nt = cloneTrack(*old);
+ nt->articulationTable = nullptr;
+ nt->articulationMapJson = nullptr;
+ republishWithTrack(trackId, nt);
+ return true;
+}
+
+int32_t Engine::trackArticulationMapJson(int32_t trackId, char* out, int32_t maxLen) const {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || !t->articulationMapJson) return 0;
+ const std::string& s = *t->articulationMapJson;
+ const auto n = static_cast<int32_t>(s.size());
+ if (out && maxLen >= n) std::memcpy(out, s.data(), s.size());
+ return n;
+}
+
+std::shared_ptr<const ArticulationTable> Engine::trackArticulationTable(int32_t trackId) const {
+ auto t = findTrackAuthoring(trackId);
+ return t ? t->articulationTable : nullptr;
}
int32_t Engine::clipNoteCount(int32_t trackId, int32_t clipIndex) const {
diff --git a/src/native/nota.engine/src/engine/MidiClip.h b/src/native/nota.engine/src/engine/MidiClip.h
index 2525d093..ddaee577 100644
--- a/src/native/nota.engine/src/engine/MidiClip.h
+++ b/src/native/nota.engine/src/engine/MidiClip.h
@@ -7,6 +7,7 @@
#pragma once
+#include "ArticulationTable.h"
#include "Automation.h"
#include "MidiController.h"
#include "NoteExpression.h"
@@ -50,6 +51,7 @@ struct Note {
double startBeat = 0.0; // relative to the clip start
double lengthBeats = 1.0;
float velocity = 0.8f; // 0..1
+ int32_t articulation = 0; // stable articulation id within the track's map (0 = none/default)
int32_t exprId = 0; // the engine's expression store id (0 = none)
std::shared_ptr<const NoteExpr> expr; // resolved from exprId; null = none
};
@@ -68,6 +70,11 @@ struct MidiClip {
// Instrument-wide controllers (specs/020): at most one curve per ctl, sorted by ctl.
// Shared, immutable curves — a clip copy shares them; an edit swaps in a new one.
std::vector<std::shared_ptr<const ControllerCurve>> controllers;
+ // Where the latching articulation changes (specs/085), derived from the notes and the
+ // track's articulation table when the graph is published (Engine::publishRaw) — never
+ // edited directly. Null when the track has no map. A copied clip carries its source's until
+ // the publish replaces it.
+ std::shared_ptr<const ArticulationTimeline> articulations;
const ControllerCurve* controller(int32_t ctl) const {
for (const auto& c : controllers)
diff --git a/src/native/nota.engine/src/engine/SessionPlayer.cpp b/src/native/nota.engine/src/engine/SessionPlayer.cpp
index c31daf89..dd3d9f6f 100644
--- a/src/native/nota.engine/src/engine/SessionPlayer.cpp
+++ b/src/native/nota.engine/src/engine/SessionPlayer.cpp
@@ -30,6 +30,9 @@ bool SessionPlayer::maybeApply(double blockStartBeats, double blockBeats, double
// A launch may have replaced the request between our two loads; only consume it if not.
int32_t expect = p;
if (!pending.compare_exchange_strong(expect, kNone, std::memory_order_relaxed)) return false;
+ // The caller flushes instrument voices when a launch/stop applies. Discard releases from
+ // the outgoing slot so they cannot cut a newly launched slot's switch on the same key.
+ articulationReleases.count = 0;
if (p == kStop || p == kStopNow) {
playing.store(-1, std::memory_order_relaxed);
} else {
diff --git a/src/native/nota.engine/src/engine/SessionPlayer.h b/src/native/nota.engine/src/engine/SessionPlayer.h
index d0a19eb7..9e0791c5 100644
--- a/src/native/nota.engine/src/engine/SessionPlayer.h
+++ b/src/native/nota.engine/src/engine/SessionPlayer.h
@@ -8,6 +8,8 @@
#pragma once
+#include "ArticulationSchedule.h"
+
#include <atomic>
#include <cmath>
#include <cstdint>
@@ -16,6 +18,10 @@ namespace nota {
class SessionPlayer {
public:
+ // Keep make_shared<SessionPlayer>() from zero-filling unused pending-release storage.
+ // Every live field has its own initializer; pending entries are read only below count.
+ SessionPlayer() noexcept {}
+
static constexpr int32_t kNone = -2; // no pending request
static constexpr int32_t kStop = -1; // pending stop (quantized)
static constexpr int32_t kStopNow = -3; // pending stop, applied at the next block (per-track "back to arrangement")
@@ -35,6 +41,7 @@ class SessionPlayer {
// Audio-thread-only.
double localBeats = 0.0; // absolute position within the loop clock
+ ArticulationReleaseState articulationReleases; // pending latching keys, timed by rendered frames
float gain = 1.0f; // launch-velocity gain of the playing slot
void requestLaunch(int32_t slot, double quant = -1.0, bool legato = false, float g = 1.0f);
diff --git a/src/native/nota.engine/src/engine/Track.h b/src/native/nota.engine/src/engine/Track.h
index d9ebd418..c3d9542a 100644
--- a/src/native/nota.engine/src/engine/Track.h
+++ b/src/native/nota.engine/src/engine/Track.h
@@ -199,7 +199,10 @@ inline constexpr int kMaxReturns = 4;
class Track {
public:
- explicit Track(int32_t id, TrackType type = TrackType::Audio) : id_(id), type_(type) {}
+ explicit Track(int32_t id, TrackType type = TrackType::Audio)
+ : Track(id, type, std::make_shared<SessionPlayer>()) {}
+ Track(int32_t id, TrackType type, const std::shared_ptr<SessionPlayer>& player)
+ : sessionPlayer(player), id_(id), type_(type) {}
int32_t id() const { return id_; }
TrackType type() const { return type_; }
@@ -322,6 +325,12 @@ class Track {
int32_t midiFromTrackId() const { return midiFromTrackId_.load(std::memory_order_relaxed); }
void setMidiFromTrackId(int32_t id) { midiFromTrackId_.store(id, std::memory_order_relaxed); }
+ // Track-level MIDI playback offset in milliseconds (negative = notes play earlier). Applied by
+ // the scheduler to arrangement clip notes only; the stored note positions never move. Atomic:
+ // written on the message thread, read on the audio thread.
+ double midiOffsetMs() const { return midiOffsetMs_.load(std::memory_order_relaxed); }
+ void setMidiOffsetMs(double ms) { midiOffsetMs_.store(ms, std::memory_order_relaxed); }
+
// Freeze (M7): when frozen, the render substitutes `frozenBuf` (this track's
// post-device, PRE-fader audio, captured offline over the whole arrangement) for
// the live instrument + device chain — the fader/pan/sends/mute/solo still run
@@ -334,6 +343,11 @@ class Track {
std::vector<AudioClip> clips; // audio tracks
std::vector<AudioTake> takes; // audio loop-recording passes (specs/067), recording order
std::vector<MidiClip> midiClips; // instrument tracks
+ // Articulation map (specs/085), instrument tracks: the compiled table the scheduler reads and
+ // the map itself as the UI's JSON (saved with the project, restored by undo). Both immutable
+ // and shared between snapshots; an edit swaps them as a pair. Null = no map.
+ std::shared_ptr<const ArticulationTable> articulationTable;
+ std::shared_ptr<const std::string> articulationMapJson;
std::vector<SessionSlot> sessionSlots; // Session view, one per scene (M5)
std::vector<TrackLane> automation; // parameter automation lanes (M9)
@@ -378,7 +392,7 @@ class Track {
std::shared_ptr<dsp::CompensationDelay> pdc = std::make_shared<dsp::CompensationDelay>();
// Session playback (M5-2). Shared across snapshots (position/state persists).
- std::shared_ptr<SessionPlayer> sessionPlayer = std::make_shared<SessionPlayer>();
+ std::shared_ptr<SessionPlayer> sessionPlayer; // constructor accepts the existing player for graph clones
// Freeze buffer (M7): interleaved stereo PCM (null = not frozen), captured at
// `frozenSpb` samples-per-beat. Shared across snapshots; only replaced on a
@@ -408,6 +422,8 @@ class Track {
std::atomic<int32_t> recordInputSource_{0}; // 0 hardware, -1 master, >0 source track id
std::atomic<int32_t> inputChannels_{kInputStereo}; // hardware input channels (#340)
std::atomic<bool> monitor_{false}; // live input monitoring (audio tracks)
+ std::atomic<double> midiOffsetMs_{0.0}; // track MIDI playback offset (ms)
+ static_assert(std::atomic<double>::is_always_lock_free, "the audio thread reads midiOffsetMs_: it must not take a lock");
std::atomic<int32_t> midiFromTrackId_{-1}; // -1 off, >0 forward MIDI to this track id
std::atomic<bool> frozen_{false}; // M7: play frozenBuf instead of the live chain
};
diff --git a/tests/Nota.SmokeTest/ArticulationEngineTests.cs b/tests/Nota.SmokeTest/ArticulationEngineTests.cs
new file mode 100644
index 00000000..c998ab2b
--- /dev/null
+++ b/tests/Nota.SmokeTest/ArticulationEngineTests.cs
@@ -0,0 +1,521 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Articulation maps through the engine (specs/085): the note's articulation id crosses the C ABI
+// intact (the NotaNoteData / NotaNote layouts agree), the track MIDI offset is clamped, copied with
+// the track and undone with it, moves playback by the requested milliseconds without moving notes,
+// and both survive saving and reopening; a v29 project opens with neither.
+// Runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --articulations`.
+
+using System.Text.Json.Nodes;
+using Nota.Application.Midi;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class ArticulationEngineTests
+{
+ private const int Block = 512, Rate = 48000;
+
+ private static float[] Render(NotaEngine e, int blocks)
+ {
+ var all = new float[blocks * Block];
+ var b = new float[Block * 2];
+ for (int k = 0; k < blocks; k++)
+ {
+ e.RenderOffline(b, Block, Rate);
+ for (int i = 0; i < Block; i++) all[k * Block + i] = (b[i * 2] + b[i * 2 + 1]) * 0.5f;
+ }
+ return all;
+ }
+
+ /// <summary>First sample louder than a quiet threshold, or -1.</summary>
+ private static int Onset(float[] x)
+ {
+ for (int i = 0; i < x.Length; i++) if (Math.Abs(x[i]) > 1e-3f) return i;
+ return -1;
+ }
+
+ /// <summary>Where one note at beat 1 (0.5 s at 120 BPM) starts sounding, with the track at <paramref name="offsetMs"/>.</summary>
+ private static int OnsetWithOffset(double offsetMs)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, 0);
+ int c = e.AddMidiClip(t, 0, 4);
+ e.SetClipNotes(t, c, new[] { new NotaNote(57, 1.0, 1.0, 0.9f) });
+ e.SetTrackMidiOffsetMs(t, offsetMs);
+ Render(e, 2); // let the graph settle before the clock starts
+ e.StopTransport(); e.Seek(0); e.Play();
+ return Onset(Render(e, 94)); // ~1 s
+ }
+
+ // The clip tools (generate / transform) keep articulations (T011): notes outside the selection
+ // pass through untouched, and notes made from a note play that note's articulation.
+ private static IEnumerable<(bool ok, string label)> ClipTools()
+ {
+ var ctx = new MidiToolContext { LengthBeats = 4, Grid = 0.25, ScaleOn = false, ScaleRoot = 0, ScaleMask = MidiScales.MaskAt(0), Seed = 11 };
+ var clip = new[]
+ {
+ new NotaNote(60, 0.0, 2.0, 0.8f) { ArticulationId = 1 },
+ new NotaNote(64, 0.0, 2.0, 0.8f) { ArticulationId = 2 },
+ new NotaNote(72, 2.0, 2.0, 0.8f) { ArticulationId = 9 }, // outside the selection below
+ };
+ var selection = new[] { 0, 1 };
+
+ int lost = 0;
+ string firstLost = "";
+ foreach (var tool in MidiToolCatalog.All)
+ {
+ var outp = MidiToolRunner.Apply(tool, clip, selection, tool.NewSettings(), ctx);
+ bool kept = outp.Any(n => n.Pitch == 72 && n.ArticulationId == 9) || !outp.Any(n => n.Pitch == 72 && Math.Abs(n.StartBeat - 2.0) < 1e-9);
+ if (!kept) { lost++; if (firstLost.Length == 0) firstLost = tool.Id; }
+ }
+ yield return (lost == 0, $"articulations: no clip tool strips the articulation of a note outside its selection ({lost} did{(lost > 0 ? ", first " + firstLost : "")})");
+
+ var trill = MidiTransforms.Ornament.NewSettings();
+ trill.Set("type", 1);
+ trill.Set("chance", 1.0);
+ var orn = MidiToolRunner.Apply(MidiTransforms.Ornament, new[] { new NotaNote(60, 0, 2, 0.8f) { ArticulationId = 4 } }, null, trill, ctx);
+ yield return (orn.Count > 1 && orn.All(n => n.ArticulationId == 4),
+ $"articulations: a trill's notes all play the ornamented note's articulation ({orn.Count} notes)");
+
+ var arp = MidiToolRunner.Apply(MidiTransforms.Arpeggiate, clip[..2], null, MidiTransforms.Arpeggiate.NewSettings(), ctx);
+ bool byChordNote = arp.Count > 2 && arp.All(n => n.ArticulationId == ((n.Pitch % 12) == 0 ? 1 : (n.Pitch % 12) == 4 ? 2 : -1));
+ yield return (byChordNote, $"articulations: each arpeggio step plays the articulation of the chord note it came from ({arp.Count} notes)");
+ }
+
+ // A map on a track (T016–T023): the engine validates the table, keeps the map JSON, undoes and
+ // redoes it, copies it with the track, and a project saves and reopens it — or opens without it.
+ private static IEnumerable<(bool ok, string label)> MapOnTrack()
+ {
+ var map = ArticulationFileTests.Full();
+ string json = Nota.Application.Articulations.ArticulationMapFile.Write(map);
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ int audio = e.AddAudioTrack();
+ e.ClearUndoHistory();
+ yield return (e.GetTrackArticulationMapJson(t) is null, "articulations: a new track has no map");
+ yield return (Nota.Application.Articulations.ArticulationMapAssignment.Assign(e, t, map) && e.GetTrackArticulationMapJson(t) == json,
+ "articulations: a compiled map is accepted and the track keeps its JSON exactly");
+ var readBack = Nota.Application.Articulations.ArticulationMapAssignment.Read(e, t);
+ yield return (readBack is not null && Nota.Application.Articulations.ArticulationMapFile.Write(readBack) == json,
+ "articulations: the map read back from the track equals the one given");
+
+ // Every rule of the table, each refused with nothing changed.
+ var ok = Nota.Application.Articulations.ArticulationMapCompiler.Compile(map);
+ NotaArticulationEntry[] E(params NotaArticulationEntry[] x) => x;
+ var bad = new List<(string why, int def, NotaArticulationEntry[] en, NotaArticulationAction[] ac)>
+ {
+ ("ids not ascending", 0, E(ok.Entries[1], ok.Entries[0]), ok.Actions),
+ ("a repeated id", 0, E(ok.Entries[0], ok.Entries[0]), ok.Actions),
+ ("an id of 0", 0, E(ok.Entries[0] with { Id = 0 }), ok.Actions),
+ ("an action range past the array", 0, E(ok.Entries[0] with { ActionCount = 99 }), ok.Actions),
+ ("a negative action start", 0, E(ok.Entries[0] with { ActionStart = -1 }), ok.Actions),
+ ("an unknown trigger mode", 0, E(ok.Entries[0] with { TriggerMode = 5 }), ok.Actions),
+ ("a NaN offset", 0, E(ok.Entries[0] with { OffsetMs = double.NaN }), ok.Actions),
+ ("an offset past 2000 ms", 0, E(ok.Entries[0] with { OffsetMs = 2500 }), ok.Actions),
+ ("a negative lead", 0, E(ok.Entries[0] with { LeadMs = -1 }), ok.Actions),
+ ("a default that isn't an entry", 5, ok.Entries, ok.Actions),
+ ("data past 127", 0, ok.Entries, ok.Actions.Select((x, i) => i == 0 ? x with { Data1 = 128 } : x).ToArray()),
+ ("channel 17", 0, ok.Entries, ok.Actions.Select((x, i) => i == 0 ? x with { Channel = 17 } : x).ToArray()),
+ ("an unknown action kind", 0, ok.Entries, ok.Actions.Select((x, i) => i == 0 ? x with { Kind = 9 } : x).ToArray()),
+ };
+ var refusedWrongly = new List<string>();
+ foreach (var (why, def, en, ac) in bad)
+ if (e.SetTrackArticulationMap(t, def, en, ac, "{}") || e.GetTrackArticulationMapJson(t) != json) refusedWrongly.Add(why);
+ yield return (refusedWrongly.Count == 0, $"articulations: the engine refuses a broken table and keeps the map it had ({bad.Count} cases{(refusedWrongly.Count > 0 ? "; not refused: " + string.Join(", ", refusedWrongly) : "")})");
+ yield return (!e.SetTrackArticulationMap(audio, ok.DefaultId, ok.Entries, ok.Actions, json) && e.GetTrackArticulationMapJson(audio) is null,
+ "articulations: an audio track can't take a map");
+ yield return (!e.SetTrackArticulationMap(9999, ok.DefaultId, ok.Entries, ok.Actions, json), "articulations: no such track is refused");
+ yield return (e.SetTrackArticulationMap(t, 0, Array.Empty<NotaArticulationEntry>(), Array.Empty<NotaArticulationAction>(), "{}")
+ && e.GetTrackArticulationMapJson(t) == "{}", "articulations: an empty map is allowed (it sends nothing)");
+
+ // Undo and redo, one step each.
+ e.Undo();
+ yield return (e.GetTrackArticulationMapJson(t) == json, "articulations: undo restores the previous map");
+ e.Undo();
+ yield return (e.GetTrackArticulationMapJson(t) is null, "articulations: undoing the first assignment leaves no map");
+ e.Redo();
+ yield return (e.GetTrackArticulationMapJson(t) == json, "articulations: redo assigns it again");
+ yield return (e.ClearTrackArticulationMap(t) && e.GetTrackArticulationMapJson(t) is null, "articulations: clearing removes the map");
+ e.Undo();
+ yield return (e.GetTrackArticulationMapJson(t) == json, "articulations: undoing the clear brings it back");
+ int dup = e.DuplicateTrack(t);
+ yield return (dup > 0 && e.GetTrackArticulationMapJson(dup) == json, "articulations: a duplicated track keeps its map");
+ int plain = e.AddInstrumentTrack();
+ bool couldUndo = e.CanUndo;
+ e.ClearUndoHistory();
+ yield return (couldUndo && e.ClearTrackArticulationMap(plain) && !e.CanUndo,
+ "articulations: clearing an instrument track with no map succeeds and adds no undo step");
+ yield return (!e.ClearTrackArticulationMap(audio), "articulations: an audio track refuses a clear too");
+ }
+
+ // Save and reopen; a damaged map in a project opens without it.
+ string bundle = Path.Combine(Path.GetTempPath(), "nota-artmap-" + Guid.NewGuid().ToString("N") + ".nota");
+ try
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ e.AddInstrumentTrack(); // a second one without a map
+ Nota.Application.Articulations.ArticulationMapAssignment.Assign(e, t, map);
+ var doc = ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), new List<string>());
+ yield return (doc.Tracks.Count(d => d.ArticulationMap is not null) == 1, "articulations: only the track with a map writes one");
+ ProjectService.Save(doc, bundle, e);
+
+ using var e2 = new NotaEngine();
+ var warnings = ProjectService.Apply(ProjectService.Load(bundle), e2, bundle);
+ var jsons = new List<string?>();
+ for (int i = 0; i < e2.TrackCount; i++)
+ if (e2.TryGetTrackInfo(i, out var ti) && ti.IsInstrument) jsons.Add(e2.GetTrackArticulationMapJson(ti.Id));
+ yield return (jsons.Count == 2 && jsons[0] == json && jsons[1] is null && warnings.Count == 0,
+ "articulations: the map survives saving and reopening exactly");
+
+ // The same document with its map damaged: it opens, the track has no map, a warning says why.
+ var broken = ProjectService.Load(bundle);
+ broken.Tracks.First(d => d.ArticulationMap is not null).ArticulationMap = new System.Text.Json.Nodes.JsonObject { ["format"] = "nonsense" };
+ using var e3 = new NotaEngine();
+ var w3 = ProjectService.Apply(broken, e3, bundle);
+ bool noMap = true;
+ for (int i = 0; i < e3.TrackCount; i++)
+ if (e3.TryGetTrackInfo(i, out var ti) && e3.GetTrackArticulationMapJson(ti.Id) is not null) noMap = false;
+ yield return (noMap && w3.Count >= 1 && e3.TrackCount == 2, $"articulations: a project with a damaged map still opens, without it, and warns ({w3.Count})");
+ }
+ finally
+ {
+ try { if (Directory.Exists(bundle)) Directory.Delete(bundle, recursive: true); } catch (IOException) { }
+ }
+ }
+
+ // Phase 4/5 (US2, US3): the engine's own check of the scheduler, then the articulation offset
+ // moving real notes, through the C ABI, at two tempos.
+ private static IEnumerable<(bool ok, string label)> Playback()
+ {
+ using (var e = new NotaEngine())
+ {
+ int code = e.ArticulationSelfTest();
+ yield return (code == 0, $"articulations: the engine schedules keyswitches, controllers and programs block by block — map order, one switch per phrase, offsets and lead, momentary holds, chase on seek and loop wrap, seam releases, delivery ahead of the note on its channel (failed check: {code})");
+ }
+
+ // A Legato note with track −100 ms and articulation −150 ms sounds 250 ms early, at 120 and 60 BPM.
+ foreach (double bpm in new[] { 120.0, 60.0 })
+ {
+ int plain = OnsetWithMap(bpm, trackMs: 0, articulationMs: 0);
+ int moved = OnsetWithMap(bpm, trackMs: -100, articulationMs: -150);
+ int want = Rate / 4; // 250 ms = 12000 samples
+ yield return (plain > 0 && moved > 0 && Math.Abs((plain - moved) - want) <= 64,
+ $"articulations: at {bpm:0} BPM, track −100 ms + Legato −150 ms plays the note 250 ms early ({plain - moved} samples, want {want})");
+ }
+
+ // Session slots (T049): the same offset moves a slot's note, the slot's clock untouched.
+ int slot0 = OnsetInSlot(0), slotEarly = OnsetInSlot(-100), slotLate = OnsetInSlot(100);
+ yield return (slot0 > 0 && slotEarly > 0 && slotLate > 0
+ && Math.Abs((slot0 - slotEarly) - Rate / 10) <= 64 && Math.Abs((slotLate - slot0) - Rate / 10) <= 64,
+ $"articulations: a Session slot's note moves with the track offset (−100 ms: {slot0 - slotEarly}, +100 ms: {slotLate - slot0} samples, want {Rate / 10})");
+
+ // A short loop with a large offset: +1500 ms on a 500 ms loop moves each pass's note three
+ // passes on. It must still sound, 1.5 s after launch, not be lost between passes.
+ int short0 = OnsetInShortSlot(0), shortLate = OnsetInShortSlot(1500);
+ yield return (short0 >= 0 && shortLate > 0 && Math.Abs((shortLate - short0) - Rate * 3 / 2) <= 64,
+ $"articulations: a +1500 ms offset on a 500 ms Session loop plays the note 1.5 s after launch ({shortLate - short0} samples, want {Rate * 3 / 2})");
+ int tiny0 = OnsetInShortSlot(0, 0.0625), tinyLate = OnsetInShortSlot(1500, 0.0625);
+ yield return (tiny0 >= 0 && tinyLate > 0 && Math.Abs((tinyLate - tiny0) - Rate * 3 / 2) <= 64,
+ $"articulations: a +1500 ms offset survives 48 passes of a 31.25 ms Session loop ({tinyLate - tiny0} samples, want {Rate * 3 / 2})");
+ }
+
+ /// <summary>Where a Session slot's note on beat 1 starts sounding after the slot is launched, with a
+ /// track MIDI offset (T049).</summary>
+ private static int OnsetInSlot(double trackMs)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ e.SetLaunchQuant(0.0);
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, 0);
+ e.AddSessionMidiClip(t, 0, 4.0);
+ e.SetSessionNotes(t, 0, new[] { new NotaNote(57, 1.0, 1.0, 0.9f) });
+ e.SetTrackMidiOffsetMs(t, trackMs);
+ Render(e, 2);
+ e.StopTransport(); e.Seek(0); e.Play();
+ e.LaunchSlot(t, 0);
+ return Onset(Render(e, 94)); // ~1 s: beat 1 is at 0.5 s
+ }
+
+ /// <summary>Where a one-beat Session slot's note on beat 0 first sounds after launch, with a track
+ /// offset that can move it several passes (a 500 ms loop at 120 BPM).</summary>
+ private static int OnsetInShortSlot(double trackMs, double loopBeats = 1.0)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ e.SetLaunchQuant(0.0);
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, 0);
+ e.AddSessionMidiClip(t, 0, loopBeats);
+ e.SetSessionNotes(t, 0, new[] { new NotaNote(57, 0.0, loopBeats / 4, 0.9f) });
+ e.SetTrackMidiOffsetMs(t, trackMs);
+ Render(e, 2);
+ e.StopTransport(); e.Seek(0); e.Play();
+ e.LaunchSlot(t, 0);
+ return Onset(Render(e, 200)); // ~2.1 s
+ }
+
+ /// <summary>Where a note on beat 2 with articulation 2 starts sounding (built-in synth: it gets
+ /// no keyswitches, only the timing), with the track and the articulation offset given.</summary>
+ private static int OnsetWithMap(double bpm, double trackMs, double articulationMs)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(bpm);
+ int t = e.AddInstrumentTrack();
+ e.SetTrackBuiltinInstrument(t, 0);
+ int c = e.AddMidiClip(t, 0, 8);
+ e.SetClipNotes(t, c, new[] { new NotaNote(57, 2.0, 1.0, 0.9f) { ArticulationId = 2 } });
+ var map = new Nota.Application.Articulations.ArticulationMap
+ {
+ Name = "Timing",
+ Articulations =
+ {
+ new Nota.Application.Articulations.Articulation { Id = 1, Name = "Long" },
+ new Nota.Application.Articulations.Articulation { Id = 2, Name = "Legato", NoteOffsetMs = articulationMs, TriggerLeadMs = 30 },
+ },
+ };
+ Nota.Application.Articulations.ArticulationMapAssignment.Assign(e, t, map);
+ e.SetTrackMidiOffsetMs(t, trackMs);
+ Render(e, 2);
+ e.StopTransport(); e.Seek(0); e.Play();
+ double seconds = 2.0 * 60.0 / bpm + 0.6; // past beat 2 with room
+ return Onset(Render(e, (int)(seconds * Rate / Block) + 1));
+ }
+
+ // Regression (owner report, 2026-11-09): an articulation-only edit in the piano roll never reached
+ // the engine because the roll's "did this clip change?" test compared fields by hand and skipped
+ // the articulation. NotaNote.Same is that test now; it must notice a change to every field.
+ private static IEnumerable<(bool ok, string label)> NoteEquality()
+ {
+ var baseNote = new NotaNote(60, 1.0, 2.0, 0.5f) { ExprId = 3, ArticulationId = 4 };
+ var fields = typeof(NotaNote).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
+ var missed = new List<string>();
+ foreach (var f in fields)
+ {
+ object boxed = baseNote;
+ object? v = f.GetValue(boxed);
+ // Each arm boxed as object: a switch expression would otherwise widen them all to double.
+ object changed = v switch
+ {
+ int i => (object)(i + 1),
+ double d => (object)(d + 0.5),
+ float s => (object)(s * 0.5f),
+ _ => throw new InvalidOperationException($"NotaNote.{f.Name}: add its type to this test"),
+ };
+ f.SetValue(boxed, changed);
+ if (NotaNote.Same(baseNote, (NotaNote)boxed)) missed.Add(f.Name);
+ }
+ yield return (fields.Length >= 6 && missed.Count == 0,
+ $"articulations: NotaNote.Same notices a change to every field ({fields.Length} fields{(missed.Count > 0 ? "; missed: " + string.Join(", ", missed) : "")})");
+ yield return (NotaNote.Same(baseNote, baseNote with { }), "articulations: NotaNote.Same holds for an unchanged copy");
+ }
+
+ // T045 / FR-013: a note's articulation survives every clip and note operation that keeps the note.
+ private static IEnumerable<(bool ok, string label)> EditsKeepArticulations()
+ {
+ // The articulation of each note, by (pitch, absolute start).
+ static Dictionary<(int, double), int> Arts(NotaEngine e, int t)
+ {
+ var d = new Dictionary<(int, double), int>();
+ for (int c = 0; e.TryGetClipInfo(t, c, out var info); c++)
+ if (info.IsMidi)
+ foreach (var n in e.GetClipNotes(t, c)) d[(n.Pitch, Math.Round(info.StartBeat + n.StartBeat, 6))] = n.ArticulationId;
+ return d;
+ }
+ var notes = new[]
+ {
+ new NotaNote(60, 0.0, 1.0, 0.8f) { ArticulationId = 1 },
+ new NotaNote(64, 0.0, 1.0, 0.8f) { ArticulationId = 2 }, // a chord, two articulations
+ new NotaNote(67, 2.0, 1.0, 0.8f) { ArticulationId = 3 },
+ };
+
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(t, 0, 4);
+ e.SetClipNotes(t, c, notes);
+ int dup = e.DuplicateClip(t, c); // lands at beat 4
+ var a = Arts(e, t);
+ yield return (dup >= 0 && a[(60, 4.0)] == 1 && a[(64, 4.0)] == 2 && a[(67, 6.0)] == 3,
+ "articulations: duplicating a clip keeps every note's articulation");
+ int right = e.SplitClip(t, c, 2.0);
+ a = Arts(e, t);
+ yield return (right >= 0 && a[(60, 0.0)] == 1 && a[(64, 0.0)] == 2 && a[(67, 2.0)] == 3,
+ "articulations: splitting a clip keeps the articulations on both sides");
+ e.TrimClip(t, c, 0.0, 1.5);
+ yield return (Arts(e, t)[(64, 0.0)] == 2, "articulations: trimming a clip keeps the articulations of the notes left in it");
+ // The split put its right half after the original, so find the duplicate (at beat 4) by place.
+ int dupNow = -1;
+ for (int k = 0; e.TryGetClipInfo(t, k, out var ci); k++) if (ci.IsMidi && ci.StartBeat == 4.0) dupNow = k;
+ e.CopyClip(t, dupNow);
+ int pasted = e.PasteClip(t, 16.0);
+ a = Arts(e, t);
+ yield return (pasted >= 0 && a.Where(kv => kv.Key.Item2 >= 16).Select(kv => kv.Value).OrderBy(x => x).SequenceEqual(new[] { 1, 2, 3 }),
+ "articulations: copying and pasting a clip keeps the articulations");
+ }
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ int c1 = e.AddMidiClip(t, 0, 2), c2 = e.AddMidiClip(t, 2, 2);
+ e.SetClipNotes(t, c1, notes[..2]);
+ e.SetClipNotes(t, c2, new[] { new NotaNote(67, 0.0, 1.0, 0.8f) { ArticulationId = 3 } });
+ bool merged = e.ConsolidateRange(new[] { t }, 0, 4);
+ var a = Arts(e, t);
+ yield return (merged && a[(60, 0.0)] == 1 && a[(64, 0.0)] == 2 && a[(67, 2.0)] == 3,
+ "articulations: consolidating clips into one keeps every note's articulation");
+
+ e.AddSessionMidiClip(t, 0, 4.0);
+ e.SetSessionNotes(t, 0, notes);
+ var back = e.GetSessionNotes(t, 0);
+ int moved = e.SessionSlotToArrangement(t, 0, 8.0);
+ a = Arts(e, t);
+ yield return (back.Select(n => n.ArticulationId).OrderBy(x => x).SequenceEqual(new[] { 1, 2, 3 })
+ && moved >= 0 && a[(60, 8.0)] == 1 && a[(64, 8.0)] == 2 && a[(67, 10.0)] == 3,
+ "articulations: a Session slot keeps its notes' articulations, and so does moving it to the arrangement");
+ }
+
+ // The piano roll's own edits run through ClipSet (multi-clip split / merge) and NoteOverwrite.
+ var set = new Nota.Application.Editing.ClipSet(new[]
+ {
+ new Nota.Application.Editing.OpenClip(1, 0, 0.0, 4.0), new Nota.Application.Editing.OpenClip(1, 1, 4.0, 4.0),
+ }, 1, 0);
+ var editor = new List<NotaNote> { notes[0], notes[1] with { StartBeat = 4.5 } };
+ var owners = new List<int> { 0, 1 };
+ var split = set.Split(editor, owners);
+ var mergedBack = new List<NotaNote>();
+ set.Merge(split, mergedBack, new List<int>());
+ yield return (split.Sum(s => s.Notes.Count) == 2 && split.SelectMany(s => s.Notes).Select(n => n.ArticulationId).OrderBy(x => x).SequenceEqual(new[] { 1, 2 })
+ && mergedBack.Select(n => n.ArticulationId).OrderBy(x => x).SequenceEqual(new[] { 1, 2 }),
+ "articulations: the piano roll's multi-clip split and merge keep each note's articulation");
+ var resized = new List<NotaNote> { notes[0], notes[2] };
+ Nota.Application.Editing.NoteOverwrite.ResizeBy(resized, new[] { 0, 1 }, 0.5, 0.05, 8.0);
+ yield return (resized[0].ArticulationId == 1 && resized[1].ArticulationId == 3 && resized[0].LengthBeats == 1.5,
+ "articulations: resizing notes keeps their articulations");
+ }
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in NoteEquality()) yield return r;
+ foreach (var r in EditsKeepArticulations()) yield return r;
+
+ // ---- the note field crosses the ABI with every other field intact ----
+ using (var e = new NotaEngine())
+ {
+ int t = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(t, 0, 4);
+ int expr = e.CreateNoteExpression(new[] { new NotaExprPoint(NoteExpressionDim.Bend, 0f, 2f) });
+ var notes = new[]
+ {
+ new NotaNote(60, 0.0, 1.0, 0.5f) { ArticulationId = 7 },
+ new NotaNote(64, 0.0, 1.0, 0.6f) { ArticulationId = 12, ExprId = expr }, // a chord, two articulations
+ new NotaNote(67, 1.5, 0.25, 0.7f), // none
+ };
+ e.SetClipNotes(t, c, notes);
+ var back = e.GetClipNotes(t, c);
+ var byPitch = back.ToDictionary(n => n.Pitch);
+ yield return (back.Length == 3
+ && byPitch.TryGetValue(60, out var a) && a.ArticulationId == 7 && a.StartBeat == 0.0 && a.LengthBeats == 1.0 && Math.Abs(a.Velocity - 0.5f) < 1e-6
+ && byPitch.TryGetValue(64, out var b) && b.ArticulationId == 12 && b.ExprId == expr
+ && byPitch.TryGetValue(67, out var d) && d.ArticulationId == 0 && d.StartBeat == 1.5 && d.LengthBeats == 0.25,
+ "articulations: each note's articulation id crosses the C ABI with every other field intact");
+
+ // One note's change touches only that note, and undoes in one step.
+ var edited = back.ToArray();
+ for (int i = 0; i < edited.Length; i++) if (edited[i].Pitch == 60) edited[i].ArticulationId = 3;
+ e.SetClipNotes(t, c, edited);
+ var after = e.GetClipNotes(t, c).ToDictionary(n => n.Pitch);
+ yield return (after[60].ArticulationId == 3 && after[64].ArticulationId == 12 && after[67].ArticulationId == 0,
+ "articulations: changing one note's articulation leaves the others alone");
+ e.Undo();
+ yield return (e.GetClipNotes(t, c).First(n => n.Pitch == 60).ArticulationId == 7, "articulations: undo restores a note's articulation");
+ e.Redo();
+ yield return (e.GetClipNotes(t, c).First(n => n.Pitch == 60).ArticulationId == 3, "articulations: redo reapplies it");
+
+ int bad = e.GetClipNotes(t, c).Length;
+ e.SetClipNotes(t, c, new[] { new NotaNote(60, 0, 1, 0.5f) { ArticulationId = -5 } });
+ yield return (e.GetClipNotes(t, c).Single().ArticulationId == 0 && bad == 3, "articulations: a negative articulation id is stored as none");
+
+ // ---- the track offset ----
+ yield return (e.GetTrackMidiOffsetMs(t) == 0.0, "articulations: a new track has no MIDI offset");
+ e.SetTrackMidiOffsetMs(t, -150);
+ yield return (e.GetTrackMidiOffsetMs(t) == -150.0, "articulations: the track offset is stored (-150 ms)");
+ e.SetTrackMidiOffsetMs(t, 5000);
+ yield return (e.GetTrackMidiOffsetMs(t) == 2000.0, "articulations: the track offset is clamped to +2000 ms");
+ e.SetTrackMidiOffsetMs(t, double.NaN);
+ yield return (e.GetTrackMidiOffsetMs(t) == 0.0, "articulations: a NaN offset is stored as 0");
+ e.SetTrackMidiOffsetMs(t, -80);
+ int dup = e.DuplicateTrack(t);
+ yield return (dup > 0 && e.GetTrackMidiOffsetMs(dup) == -80.0, "articulations: a duplicated track keeps its MIDI offset");
+
+ // T051: the offset is one undo step; setting the same value is none.
+ e.ClearUndoHistory();
+ e.SetTrackMidiOffsetMs(t, -150);
+ e.SetTrackMidiOffsetMs(t, -150);
+ e.Undo();
+ bool undone = e.GetTrackMidiOffsetMs(t) == -80.0 && !e.CanUndo;
+ e.Redo();
+ yield return (undone && e.GetTrackMidiOffsetMs(t) == -150.0,
+ "articulations: a track offset change is one undo step (undo −150 → −80, redo back); the same value again adds none");
+ yield return (e.GetTrackMidiOffsetMs(9999) == 0.0, "articulations: no such track reads offset 0");
+ }
+
+ // ---- the offset moves playback, not the notes ----
+ int at0 = OnsetWithOffset(0), early = OnsetWithOffset(-100), late = OnsetWithOffset(100);
+ int ms100 = Rate / 10; // 4800 samples
+ yield return (at0 > 0 && Math.Abs(at0 - 24000) < 256, $"articulations: with no offset the note sounds on its beat (onset {at0}, beat at 24000)");
+ yield return (at0 > 0 && early > 0 && Math.Abs((at0 - early) - ms100) <= 64,
+ $"articulations: a -100 ms track offset plays the note 100 ms early ({at0 - early} samples, want {ms100})");
+ yield return (at0 > 0 && late > 0 && Math.Abs((late - at0) - ms100) <= 64,
+ $"articulations: a +100 ms track offset plays the note 100 ms late ({late - at0} samples, want {ms100})");
+
+ // ---- save and reopen; old projects ----
+ string bundle = Path.Combine(Path.GetTempPath(), "nota-art-" + Guid.NewGuid().ToString("N") + ".nota");
+ try
+ {
+ using var e = new NotaEngine();
+ int t = e.AddInstrumentTrack();
+ int plain = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(t, 0, 4);
+ e.SetClipNotes(t, c, new[] { new NotaNote(60, 0, 1, 0.8f) { ArticulationId = 5 }, new NotaNote(62, 1, 1, 0.8f) });
+ e.SetTrackMidiOffsetMs(t, -120);
+ var doc = ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), new List<string>());
+ var savedTrack = doc.Tracks.FirstOrDefault(d => d.MidiOffsetMs is not null);
+ yield return (savedTrack?.MidiOffsetMs == -120.0 && doc.Tracks.Count(d => d.MidiOffsetMs is not null) == 1,
+ "articulations: only the track with an offset writes one");
+ ProjectService.Save(doc, bundle, e);
+
+ using var e2 = new NotaEngine();
+ ProjectService.Apply(ProjectService.Load(bundle), e2, bundle);
+ int lt = -1, lplain = -1;
+ for (int i = 0; i < e2.TrackCount; i++)
+ if (e2.TryGetTrackInfo(i, out var ti) && ti.IsInstrument)
+ {
+ if (ti.ClipCount > 0) lt = ti.Id; else lplain = ti.Id;
+ }
+ var ln = lt > 0 ? e2.GetClipNotes(lt, 0).ToDictionary(n => n.Pitch) : new Dictionary<int, NotaNote>();
+ yield return (lt > 0 && e2.GetTrackMidiOffsetMs(lt) == -120.0 && lplain > 0 && e2.GetTrackMidiOffsetMs(lplain) == 0.0,
+ "articulations: the track offset survives saving and reopening");
+ yield return (ln.Count == 2 && ln[60].ArticulationId == 5 && ln[62].ArticulationId == 0,
+ "articulations: each note's articulation survives saving and reopening");
+ }
+ finally
+ {
+ try { if (Directory.Exists(bundle)) Directory.Delete(bundle, recursive: true); } catch (IOException) { }
+ }
+
+ foreach (var r in ClipTools()) yield return r;
+ foreach (var r in MapOnTrack()) yield return r;
+ foreach (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
+ && 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");
+ }
+}
diff --git a/tests/Nota.SmokeTest/ArticulationFileTests.cs b/tests/Nota.SmokeTest/ArticulationFileTests.cs
new file mode 100644
index 00000000..1f77db09
--- /dev/null
+++ b/tests/Nota.SmokeTest/ArticulationFileTests.cs
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota's articulation map file and the table compiler (specs/085,
+// contracts/nota-articulation-map-file.md, contracts/c-abi.md): a map survives writing and reading
+// unchanged; what a damaged file gets wrong is repaired and reported, or the file is refused; the
+// compiler hands the engine only what it should schedule. Pure: no engine.
+// Runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --articulations`.
+
+using System.Text;
+using Nota.Application.Articulations;
+
+namespace Nota.SmokeTest;
+
+internal static class ArticulationFileTests
+{
+ /// <summary>A map using every field the format has.</summary>
+ internal static ArticulationMap Full() => new()
+ {
+ Id = "0123456789abcdef0123456789abcdef",
+ Name = "Test Strings",
+ InstrumentName = "Test Library",
+ Description = "every field",
+ DefaultArticulationId = 2,
+ Groups = { new ArticulationGroup { Id = 1, Name = "Bowing" }, new ArticulationGroup { Id = 2, Name = "" } },
+ Articulations =
+ {
+ new Articulation
+ {
+ Id = 2, Name = "Long", ShortName = "Lng", ColorArgb = 0xFF336699, SourceColorIndex = 3, GroupId = 1,
+ Actions = { new MidiAction { Kind = MidiActionKind.Keyswitch, Data1 = 24, Data2 = 1 },
+ new MidiAction { Kind = MidiActionKind.ControlChange, Channel = 5, Data1 = 58, Data2 = 81 } },
+ NoteOffsetMs = -150.5, TriggerLeadMs = 30, Metadata = { ["description"] = "Long notes" },
+ },
+ new Articulation
+ {
+ Id = 7, Name = "Pizz", ShortName = "Pz", Trigger = TriggerMode.Momentary, GroupId = 2,
+ Actions = { new MidiAction { Kind = MidiActionKind.BankSelectMsb, Data1 = 0, Data2 = 1 },
+ new MidiAction { Kind = MidiActionKind.BankSelectLsb, Data1 = 32, Data2 = 2 },
+ new MidiAction { Kind = MidiActionKind.ProgramChange, Channel = 16, Data1 = 12 } },
+ NoteOffsetMs = 200,
+ },
+ new Articulation { Id = 9, Name = "Off", ShortName = "Off", Enabled = false,
+ Actions = { new MidiAction { Kind = MidiActionKind.Keyswitch, Data1 = 30, Data2 = 127 } } },
+ },
+ Metadata = { ["source.format"] = "nota" },
+ };
+
+ private static ArticulationImportResult Read(string json) => ArticulationMapFile.Read(json, "fallback");
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ // ---- write → read → write is stable ----
+ var full = Full();
+ string w1 = ArticulationMapFile.Write(full);
+ var r1 = Read(w1);
+ string? w2 = r1.Map is null ? null : ArticulationMapFile.Write(r1.Map);
+ yield return (r1.Succeeded && !r1.Warnings.Any() && w2 == w1, "articulations: a map using every field writes, reads and writes back identically");
+ var back = r1.Map;
+ yield return (back is not null && back.Articulations.Count == 3 && back.Find(7)!.Trigger == TriggerMode.Momentary
+ && back.Find(2)!.Actions[1].Channel == 5 && back.Find(2)!.NoteOffsetMs == -150.5 && back.Find(2)!.ColorArgb == 0xFF336699
+ && !back.Find(9)!.Enabled && back.DefaultArticulationId == 2 && back.Groups.Count == 2,
+ "articulations: trigger mode, channel, offset, colour, enabled, default and groups survive the file");
+
+ // ---- repairs, each reported ----
+ string dupIds = """
+ {"format":"nota-articulation-map","version":1,"id":"x","name":"R","defaultArticulationId":42,
+ "groups":[{"id":1,"name":"A"},{"id":1,"name":"B"},{"name":"C"}],
+ "articulations":[
+ {"id":3,"name":"First","groupId":1,"actions":[{"kind":"keyswitch","channel":null,"data1":24,"data2":1}]},
+ {"id":3,"name":"Second","trigger":"sticky","noteOffsetMs":5000,"triggerLeadMs":-4,
+ "actions":[{"kind":"keyswitch","data1":300,"data2":1},{"kind":"pitchBend","data1":0,"data2":0},{"kind":"controlChange","channel":17,"data1":1,"data2":1},{"kind":"controlChange","data1":1,"data2":64}]},
+ {"name":"Third","groupId":9}
+ ]}
+ """;
+ var rep = Read(dupIds);
+ var m = rep.Map;
+ yield return (m is not null && m.Articulations.Select(x => x.Id).SequenceEqual(new[] { 3, 4, 5 })
+ && rep.Warnings.Count(x => x.Text.Contains("is now")) == 2,
+ "articulations: a repeated or missing articulation id gets the next free id, and each is reported");
+ yield return (m is not null && m.DefaultArticulationId is null && rep.Warnings.Any(x => x.Text.Contains("default articulation")),
+ "articulations: a default that isn't in the map is dropped and reported");
+ var second = m?.Articulations.ElementAtOrDefault(1);
+ yield return (second is not null && second.NoteOffsetMs == 2000 && second.TriggerLeadMs == 0
+ && second.Trigger == TriggerMode.Latching && second.Actions.Count == 1 && second.Actions[0].Data2 == 64,
+ "articulations: an out-of-range offset and lead are clamped, an unknown trigger plays latching, invalid actions are dropped");
+ yield return (rep.Warnings.Any(x => x.Text.Contains("brought into range")) && rep.Warnings.Any(x => x.Text.Contains("Latching"))
+ && rep.Warnings.Any(x => x.Text.Contains("invalid MIDI action")),
+ "articulations: each of those repairs is reported");
+ yield return (m is not null && m.Groups.Count == 1 && m.Groups[0].Name == "A" && m.Articulations[0].GroupId == 1 && m.Articulations[2].GroupId == 0
+ && rep.Warnings.Any(x => x.Text.Contains("group")),
+ "articulations: a repeated or id-less group is dropped and an articulation pointing at a missing group is ungrouped");
+ var nameless = Read("""{"format":"nota-articulation-map","articulations":[]}""");
+ yield return (nameless.Map?.Name == "fallback" && nameless.Map.Id.Length == 32, "articulations: a nameless map takes the file name and gets a new id");
+
+ // ---- refusals ----
+ yield return (Read("{ not json").Messages.Any(x => x.Severity == ImportSeverity.Error) && !Read("{ not json").Succeeded,
+ "articulations: a file that isn't JSON is refused");
+ yield return (!Read("""{"format":"something-else"}""").Succeeded && !Read("[1,2,3]").Succeeded,
+ "articulations: JSON that isn't a Nota map is refused by its format field");
+ var newer = Read("""{"format":"nota-articulation-map","version":99}""");
+ yield return (!newer.Succeeded && newer.Messages.Any(x => x.Text.Contains("newer")), "articulations: a map from a newer version is refused, not half read");
+ var deep = new StringBuilder("{\"format\":\"nota-articulation-map\",\"metadata\":");
+ for (int i = 0; i < 100; i++) deep.Append("{\"a\":");
+ deep.Append("1").Append('}', 100).Append('}');
+ yield return (!Read(deep.ToString()).Succeeded, "articulations: JSON nested past 64 levels is refused, not a crash");
+ yield return (!ArticulationMapFile.ReadFile(Path.Combine(Path.GetTempPath(), "nota-missing-" + Guid.NewGuid().ToString("N") + ".notamap")).Succeeded,
+ "articulations: a missing map file is reported");
+
+ // ---- the compiler ----
+ var c = ArticulationMapCompiler.Compile(full);
+ yield return (c.Entries.Select(e => e.Id).SequenceEqual(new[] { 2, 7 }), "articulations: the compiler leaves disabled articulations out, ids ascending");
+ yield return (c.DefaultId == 2 && c.Entries[0].OffsetMs == -150.5 && c.Entries[0].LeadMs == 30 && c.Entries[1].TriggerMode == 1,
+ "articulations: offsets, leads, trigger mode and the default reach the table");
+ yield return (c.Entries[0].ActionStart == 0 && c.Entries[0].ActionCount == 2 && c.Entries[1].ActionStart == 2 && c.Entries[1].ActionCount == 3
+ && c.Actions[0].Channel == 0 && c.Actions[1].Channel == 5 && c.Actions[2].Kind == 3 && c.Actions[3].Data1 == 32 && c.Actions[4].Kind == 2 && c.Actions[4].Channel == 16,
+ "articulations: actions keep their order; the note's own channel compiles to 0");
+ var noDefault = Full();
+ noDefault.DefaultArticulationId = 9; // the disabled one
+ yield return (ArticulationMapCompiler.Compile(noDefault).DefaultId == 0, "articulations: a disabled default compiles to no default");
+
+ // ---- how actions read in the preview and inspector ----
+ var longArt = full.Find(2)!;
+ string longText = ArticulationText.Actions(longArt);
+ yield return (longText == "Keyswitch C1 · vel 1 · CC 58 = 81 (ch 5)", $"articulations: actions read in send order with their channel ({longText})");
+ string pizz = ArticulationText.Actions(full.Find(7)!);
+ yield return (pizz == "Bank MSB 1 · Bank LSB 2 · Program 12 (ch 16)", $"articulations: bank and program actions read plainly ({pizz})");
+ yield return (ArticulationText.Actions(new Articulation()) == "Sends nothing", "articulations: an articulation without actions says it sends nothing");
+ yield return (ArticulationText.Count(full) == "3 articulations" && ArticulationText.Count(new ArticulationMap { Articulations = { new Articulation { Id = 1 } } }) == "1 articulation",
+ "articulations: the count is counted (1 articulation, 3 articulations)");
+ yield return (ArticulationText.Group(full.Groups[0]) == "Bowing" && ArticulationText.Group(full.Groups[1]) == "Group 2",
+ "articulations: an unnamed group reads as a numbered group");
+
+ // FR-018 / T053: track + articulation, once; only articulations with an offset of their own, enabled ones.
+ var eff = ArticulationText.EffectiveOffsets(full, -100);
+ yield return (eff.Count == 2 && eff[0] == ("Long", -250.5) && eff[1] == ("Pizz", 100.0),
+ $"articulations: effective offsets add the track's once (Long −100 + −150.5 = −250.5, Pizz −100 + 200 = 100; the disabled one left out) ({string.Join(", ", eff)})");
+ }
+}
diff --git a/tests/Nota.SmokeTest/ArticulationImportTests.cs b/tests/Nota.SmokeTest/ArticulationImportTests.cs
new file mode 100644
index 00000000..74fe385f
--- /dev/null
+++ b/tests/Nota.SmokeTest/ArticulationImportTests.cs
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Articulation map importers (specs/085) on small maps written here: a Cubase expression map and a
+// Studio One keyswitch list in the formats' own shape, plus malformed and hostile input. No vendor
+// file is in the repo (they are third-party works), so a real library's map is checked by hand
+// (quickstart A, B). Pure, except the library round trip onto a track.
+// Runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --articulations`.
+
+using System.Security.Cryptography;
+using System.Text;
+using Nota.Application.Articulations;
+
+namespace Nota.SmokeTest;
+
+internal static class ArticulationImportTests
+{
+ private static string Describe(IEnumerable<MidiAction> acts) =>
+ string.Join(" ", acts.Select(a => $"{a.Kind}:{a.Data1}/{a.Data2}"));
+
+ private static ArticulationImportResult FromText(Func<Stream, string, ArticulationImportResult> import, string xml) =>
+ import(new MemoryStream(Encoding.UTF8.GetBytes(xml)), "test");
+
+ // A Cubase sound slot: its MIDI output events (status, data1, data2) and its name.
+ private static string Slot(string name, params (int Status, int D1, int D2)[] events) =>
+ "<obj class=\"PSoundSlot\"><obj class=\"PSlotMidiAction\" name=\"action\"><member name=\"midiMessages\"><list name=\"obj\" type=\"obj\">"
+ + string.Concat(events.Select(e => $"<obj class=\"POutputEvent\"><int name=\"status\" value=\"{e.Status}\"/><int name=\"data1\" value=\"{e.D1}\"/><int name=\"data2\" value=\"{e.D2}\"/></obj>"))
+ + $"</list></member></obj><member name=\"name\"><string name=\"s\" value=\"{name}\"/></member></obj>";
+
+ private static string ExpressionMap(params string[] slots) =>
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><InstrumentMap><string name=\"name\" value=\"Test Map\"/>"
+ + "<member name=\"slots\"><list name=\"obj\" type=\"obj\">" + string.Concat(slots) + "</list></member></InstrumentMap>";
+
+ // Two articulations: Long (two keyswitches and a CC, in that order) and Pizz (a velocity-coded keyswitch).
+ private static readonly string TestExpressionMap = ExpressionMap(
+ Slot("Long", (144, 24, 1), (144, 35, 1), (176, 58, 81)),
+ Slot("Pizz", (144, 30, 127)));
+
+ private const string TestKeySwitchList =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Music.KeySwitchList name=\"Test List\">"
+ + "<Attributes name=\"Long\" id=\"1\" activation=\"note24.1|note35.1|unknown\"/>"
+ + "<Attributes name=\"Pizz\" id=\"2\" activation=\"note30\"/></Music.KeySwitchList>";
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ string dir = Path.Combine(Path.GetTempPath(), "nota-art-import-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ string cubasePath = Path.Combine(dir, "test.expressionmap"), ksPath = Path.Combine(dir, "test.keyswitch");
+ File.WriteAllText(cubasePath, TestExpressionMap);
+ File.WriteAllText(ksPath, TestKeySwitchList);
+ try
+ {
+ // ---- content sniffing, not extensions -------------------------------------------------
+ yield return (ExpressionMapImporter.Sniff(cubasePath), "articulations: a Cubase map is recognised by its content");
+ yield return (!ExpressionMapImporter.Sniff(ksPath), "articulations: a keyswitch list is not taken for an expression map");
+ yield return (KeySwitchListImporter.Sniff(ksPath), "articulations: a keyswitch list is recognised by its content");
+ yield return (!KeySwitchListImporter.Sniff(cubasePath), "articulations: an expression map is not taken for a keyswitch list");
+
+ // ---- Cubase expression map ----------------------------------------------------------
+ byte[] before = SHA256.HashData(File.ReadAllBytes(cubasePath));
+ var cub = ExpressionMapImporter.ImportFile(cubasePath);
+ byte[] after = SHA256.HashData(File.ReadAllBytes(cubasePath));
+ yield return (before.AsSpan().SequenceEqual(after), "articulations: importing never modifies the source file");
+ var longArt = cub.Map?.Articulations.FirstOrDefault(a => a.Name == "Long");
+ yield return (cub.Map?.Articulations.Count == 2 && longArt is not null
+ && Describe(longArt.Actions) == "Keyswitch:24/1 Keyswitch:35/1 ControlChange:58/81" && longArt.Actions.All(a => a.Channel is null),
+ $"articulations: a Cubase map imports its slots, actions in file order on the note's channel ({(longArt is null ? "none" : Describe(longArt.Actions))})");
+ yield return (cub.Map?.Articulations.All(a => a.Trigger == TriggerMode.Latching) == true
+ && cub.Messages.Any(m => m.Text.Contains("Switch mode is not stored")),
+ "articulations: switch mode is reported as not in the file, defaulting to Latching");
+
+ // ---- Studio One keyswitch list ----------------------------------------------------
+ var ks = KeySwitchListImporter.ImportFile(ksPath);
+ var ksLong = ks.Map?.Articulations.FirstOrDefault(a => a.Name == "Long");
+ yield return (ks.Map?.Articulations.Count == 2 && ksLong?.Id == 1 && ksLong is not null && Describe(ksLong.Actions) == "Keyswitch:24/1 Keyswitch:35/1"
+ && Describe(ks.Map.Articulations[1].Actions) == "Keyswitch:30/127",
+ "articulations: a keyswitch list keeps its ids; noteP.V is velocity V, noteP is velocity 127");
+ yield return (ks.Warnings.Any(m => m.Text.Contains("\"unknown\"")) && ksLong?.Metadata.ContainsKey("source.activation") == true,
+ "articulations: the action the keyswitch format cannot describe is reported, and the activation string kept");
+ yield return (cub.Map is { } cm && ks.Map is { } km && km.Articulations.All(a =>
+ cm.Articulations.FirstOrDefault(c => c.Name == a.Name) is { } twin
+ && Describe(a.Actions) == Describe(twin.Actions.Where(x => x.Kind == MidiActionKind.Keyswitch))),
+ "articulations: the same articulations read from both formats send the same keyswitches");
+
+ // ---- malformed and hostile input ------------------------------------------------------
+ var broken = FromText(ExpressionMapImporter.Import, "<InstrumentMap><member name=\"slots\">");
+ yield return (!broken.Succeeded && broken.Messages.Any(m => m.Severity == ImportSeverity.Error && m.Text.Contains("XML error")),
+ "articulations: truncated XML is an error, not a crash");
+ var wrongRoot = FromText(ExpressionMapImporter.Import, "<?xml version=\"1.0\"?><Something/>");
+ yield return (!wrongRoot.Succeeded && wrongRoot.Messages.Any(m => m.Text.Contains("<InstrumentMap>")),
+ "articulations: a different XML document is rejected by its root");
+ var noSlots = FromText(ExpressionMapImporter.Import, "<InstrumentMap><string name=\"name\" value=\"X\"/></InstrumentMap>");
+ yield return (!noSlots.Succeeded && noSlots.Messages.Any(m => m.Text.Contains("no sound slots")),
+ "articulations: a map with no slots is rejected");
+ var badEvent = FromText(ExpressionMapImporter.Import, ExpressionMap(Slot("Odd", (224, 0, 64), (144, 300, 1), (192, 5, 0))));
+ var odd = badEvent.Map?.Articulations.FirstOrDefault();
+ yield return (odd is not null && Describe(odd.Actions) == "ProgramChange:5/0"
+ && badEvent.Warnings.Any(m => m.Text.Contains("unsupported"))
+ && badEvent.Warnings.Any(m => m.Text.Contains("out of range")),
+ "articulations: unsupported and out-of-range messages are reported; valid ones (program change) are kept");
+ var dtd = FromText(ExpressionMapImporter.Import,
+ "<?xml version=\"1.0\"?><!DOCTYPE lolz [<!ENTITY lol \"lol\"><!ENTITY lol2 \"&lol;&lol;&lol;\">]><InstrumentMap>&lol2;</InstrumentMap>");
+ yield return (!dtd.Succeeded, "articulations: a document type declaration (entity expansion) is refused");
+ var ksBad = FromText(KeySwitchListImporter.Import,
+ "<Music.KeySwitchList name=\"T\"><Attributes name=\"A\" id=\"1\" activation=\"note200.1|cc12|note60\"/></Music.KeySwitchList>");
+ var ksA = ksBad.Map?.Articulations.FirstOrDefault();
+ yield return (ksA is not null && Describe(ksA.Actions) == "Keyswitch:60/127" && ksBad.Warnings.Count() >= 2,
+ "articulations: bad keyswitch tokens are reported and skipped, the good one is kept");
+ var empty = FromText(KeySwitchListImporter.Import, "");
+ yield return (!empty.Succeeded, "articulations: an empty file is an error, not a crash");
+ var missing = ExpressionMapImporter.ImportFile(Path.Combine(dir, "does-not-exist.expressionmap"));
+ yield return (!missing.Succeeded && missing.Messages.Any(m => m.Text.Contains("not found")), "articulations: a missing file is reported");
+
+ foreach (var r in Dispatch()) yield return r;
+ foreach (var r in Library(cubasePath)) yield return r;
+ }
+ finally { try { Directory.Delete(dir, recursive: true); } catch (IOException) { } }
+ }
+
+ // T028: the importer is picked by content, whatever the file is named.
+ private static IEnumerable<(bool ok, string label)> Dispatch()
+ {
+ string dir = Path.Combine(Path.GetTempPath(), "nota-art-dispatch-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ try
+ {
+ string cubaseAsTxt = Path.Combine(dir, "violins.txt");
+ string ksAsExpr = Path.Combine(dir, "strings.expressionmap");
+ string notaAsKs = Path.Combine(dir, "mine.keyswitch");
+ string fakeExpr = Path.Combine(dir, "fake.expressionmap");
+ string soundVar = Path.Combine(dir, "strings.soundvariation");
+ File.WriteAllText(cubaseAsTxt, TestExpressionMap);
+ File.WriteAllText(ksAsExpr, TestKeySwitchList);
+ File.WriteAllText(notaAsKs, ArticulationMapFile.Write(ArticulationFileTests.Full()));
+ File.WriteAllText(fakeExpr, "just some text, not a map");
+ File.WriteAllText(soundVar, "<?xml version=\"1.0\"?><SoundVariation/>");
+
+ yield return (ArticulationImport.Detect(cubaseAsTxt) == ArticulationFileKind.CubaseExpressionMap
+ && ArticulationImport.ImportFile(cubaseAsTxt).Map?.Articulations.Count == 2,
+ "articulations: a Cubase map renamed to .txt is still recognised and imported");
+ yield return (ArticulationImport.Detect(ksAsExpr) == ArticulationFileKind.StudioOneKeySwitchList
+ && ArticulationImport.ImportFile(ksAsExpr).Map?.Articulations.Count == 2,
+ "articulations: a keyswitch list named .expressionmap goes to the keyswitch importer");
+ var nota = ArticulationImport.ImportFile(notaAsKs);
+ yield return (ArticulationImport.Detect(notaAsKs) == ArticulationFileKind.NotaMap && nota.Map?.Name == "Test Strings",
+ "articulations: a Nota map named .keyswitch is read as a Nota map");
+ var fake = ArticulationImport.ImportFile(fakeExpr);
+ yield return (!fake.Succeeded && fake.Messages.Any(m => m.Severity == ImportSeverity.Error),
+ "articulations: a text file with a map's extension is refused");
+ var sv = ArticulationImport.ImportFile(soundVar);
+ yield return (!sv.Succeeded && sv.Messages.Any(m => m.Text.Contains(".soundvariation")),
+ "articulations: a .soundvariation file is refused with a message saying it isn't supported yet");
+ yield return (!ArticulationImport.ImportFile(Path.Combine(dir, "nope.expressionmap")).Succeeded,
+ "articulations: a missing file is refused through the facade too");
+ }
+ finally { try { Directory.Delete(dir, recursive: true); } catch (IOException) { } }
+ }
+
+ // T029 + T034: the library store, and an imported map onto a track and back.
+ private static IEnumerable<(bool ok, string label)> Library(string cubasePath)
+ {
+ string dir = Path.Combine(Path.GetTempPath(), "nota-art-library-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var lib = new Nota.Infrastructure.Articulations.ArticulationLibraryStore(dir);
+ yield return (lib.List().Count == 0, "articulations: an empty library lists nothing (no folder yet)");
+
+ var imported = ArticulationImport.ImportFile(cubasePath).Map!;
+ var full = ArticulationFileTests.Full();
+ lib.Save(imported);
+ lib.Save(full);
+ var listed = lib.List();
+ yield return (listed.Count == 2 && listed.Select(m => m.Name).SequenceEqual(new[] { "Test Map", "Test Strings" }),
+ "articulations: saved maps are listed by name");
+ var got = lib.Get(imported.Id);
+ yield return (got is not null && ArticulationMapFile.Write(got) == ArticulationMapFile.Write(imported),
+ "articulations: a map read back from the library equals the one saved");
+
+ full.Name = "Renamed";
+ lib.Save(full);
+ yield return (lib.List().Count == 2 && lib.Get(full.Id)?.Name == "Renamed"
+ && Directory.GetFiles(dir, "*.notamap").Length == 2 && !Directory.GetFiles(dir, "*.tmp").Any(),
+ "articulations: saving the same map again replaces it in place (file named by id, no temp file left)");
+
+ File.WriteAllText(Path.Combine(dir, "broken.notamap"), "{ not a map");
+ var withBroken = lib.List();
+ yield return (withBroken.Count == 2 && lib.Unreadable.Count == 1, "articulations: an unreadable file is skipped and reported, not thrown");
+
+ bool refusedPath;
+ try { lib.Save(new ArticulationMap { Id = "../escape", Name = "x" }); refusedPath = false; }
+ catch (ArgumentException) { refusedPath = true; }
+ yield return (refusedPath && !File.Exists(Path.Combine(Path.GetDirectoryName(dir)!, "escape.notamap")) && lib.Get("../escape") is null,
+ "articulations: a map id that is a path is refused (nothing written outside the folder)");
+
+ yield return (lib.Delete(full.Id) && lib.Get(full.Id) is null && !lib.Delete(full.Id),
+ "articulations: deleting a map removes it; deleting it again reports nothing to delete");
+
+ // Import → library → track → read back, through the real engine.
+ using var e = new Nota.Infrastructure.NotaEngine();
+ int t = e.AddInstrumentTrack();
+ var fromLib = lib.Get(imported.Id)!;
+ yield return (ArticulationMapAssignment.Assign(e, t, fromLib)
+ && ArticulationMapAssignment.Read(e, t) is { } onTrack
+ && ArticulationMapFile.Write(onTrack) == ArticulationMapFile.Write(imported),
+ "articulations: an imported map goes from the library onto a track and reads back equal");
+ }
+ finally { try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { } }
+ }
+}
diff --git a/tests/Nota.SmokeTest/ArticulationManagerTests.cs b/tests/Nota.SmokeTest/ArticulationManagerTests.cs
new file mode 100644
index 00000000..8d7c011c
--- /dev/null
+++ b/tests/Nota.SmokeTest/ArticulationManagerTests.cs
@@ -0,0 +1,198 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The articulation map manager's rules (specs/085, US5, T066): ids are never reused, the default
+// follows removals, copies are deep, typed MIDI values read as numbers or note names, a map is
+// checked before saving, and an edit reaches every track holding the map — as one undo step —
+// while a duplicate is left alone. Runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --articulations`.
+
+using Nota.Application.Articulations;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class ArticulationManagerTests
+{
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ // ---- ids ----
+ var m = ArticulationFileTests.Full(); // ids 2, 7, 9
+ int added = ArticulationMapEdits.Add(m, "Tremolo");
+ yield return (added == 10 && m.Articulations[^1].Name == "Tremolo" && m.Articulations[^1].ShortName == "Tremol",
+ $"articulations: a new articulation takes the next id after the highest (10) and a short name ({added})");
+ ArticulationMapEdits.Remove(m, 10);
+ int again = ArticulationMapEdits.Add(m, "Trill");
+ yield return (again == 11, $"articulations: a removed id is never handed out again, even when it was the highest ({again})");
+ // The memory of removed ids survives saving the map: with 10 and 11 removed, the highest id
+ // left is 9, so only the remembered ids keep the next one from being 10.
+ ArticulationMapEdits.Remove(m, 11);
+ var reread = ArticulationMapFile.Read(ArticulationMapFile.Write(m), "").Map!;
+ yield return (ArticulationMapEdits.Add(reread, "Spiccato") == 12, "articulations: removed ids are remembered in the saved map (next is 12, not 10)");
+
+ yield return (ArticulationMapEdits.Remove(m, 2) && m.DefaultArticulationId is null && m.Find(2) is null,
+ "articulations: removing the default articulation leaves the map without a default");
+ yield return (!ArticulationMapEdits.Remove(m, 999), "articulations: removing an id the map doesn't have changes nothing");
+
+ // ---- order ----
+ var o = ArticulationFileTests.Full();
+ yield return (ArticulationMapEdits.Move(o, 9, -2) && o.Articulations.Select(a => a.Id).SequenceEqual(new[] { 9, 2, 7 })
+ && !ArticulationMapEdits.Move(o, 9, -1),
+ "articulations: articulations move up and down and stop at the ends");
+ var pizz = o.Find(7)!;
+ yield return (ArticulationMapEdits.MoveAction(pizz, 2, -2) && pizz.Actions[0].Kind == MidiActionKind.ProgramChange
+ && !ArticulationMapEdits.MoveAction(pizz, 5, 1),
+ "articulations: actions move in their send order");
+
+ // ---- copies are deep ----
+ var c = ArticulationFileTests.Full();
+ int copyId = ArticulationMapEdits.Copy(c, 2, "Long copy");
+ var copy = c.Find(copyId)!;
+ copy.Actions[0].Data1 = 99;
+ copy.Metadata["x"] = "y";
+ yield return (copyId == 10 && c.Articulations[1].Id == copyId && c.Find(2)!.Actions[0].Data1 == 24 && !c.Find(2)!.Metadata.ContainsKey("x"),
+ "articulations: a copied articulation sits after its original and shares nothing with it");
+ var dup = c.DuplicateAs("Strings B");
+ dup.Articulations[0].Name = "Changed";
+ yield return (dup.Id != c.Id && c.Articulations[0].Name == "Long" && dup.Articulations.Select(a => a.Id).SequenceEqual(c.Articulations.Select(a => a.Id)),
+ "articulations: a duplicated map gets its own id, keeps the articulation ids, and shares nothing");
+
+ // ---- checks before saving ----
+ var bad = ArticulationFileTests.Full();
+ bad.Name = " ";
+ bad.Articulations[0].Name = "";
+ bad.Articulations[1].Actions.Add(new MidiAction { Kind = MidiActionKind.ControlChange, Data1 = 200 });
+ bad.DefaultArticulationId = 42;
+ var problems = ArticulationMapEdits.Check(bad).Select(p => p.Problem).ToHashSet();
+ yield return (problems.SetEquals(new[] { ArticulationMapEdits.Problem.NoName, ArticulationMapEdits.Problem.ArticulationWithoutName,
+ ArticulationMapEdits.Problem.InvalidAction, ArticulationMapEdits.Problem.DefaultMissing })
+ && ArticulationMapEdits.Check(ArticulationFileTests.Full()).Count == 0,
+ "articulations: a map is checked before saving (no name, a nameless articulation, an invalid action, a missing default); a good one passes");
+
+ // ---- typed MIDI values ----
+ var cases = new (string Text, bool Notes, int? Want)[]
+ {
+ ("24", true, 24), ("C1", true, 24), ("c#1", true, 25), ("Db1", true, 25), ("C-1", true, 0), ("C\u22121", true, 0),
+ ("G9", true, 127), ("128", true, null), ("-1", true, null), ("H2", true, null), ("C1", false, null), ("64", false, 64), ("", true, null),
+ };
+ var wrong = cases.Where(k => ArticulationMapEdits.ParseMidiValue(k.Text, k.Notes) != k.Want).Select(k => k.Text).ToList();
+ yield return (wrong.Count == 0, $"articulations: MIDI values read as numbers 0–127 or, for keyswitches, note names (C1 = 24){(wrong.Count > 0 ? "; wrong: " + string.Join(", ", wrong) : "")}");
+
+ // ---- an edit reaches every track holding the map, as one undo step; a duplicate is left alone ----
+ using var e = new NotaEngine();
+ int t1 = e.AddInstrumentTrack(), t2 = e.AddInstrumentTrack(), t3 = e.AddInstrumentTrack(), t4 = e.AddInstrumentTrack();
+ var shared = ArticulationFileTests.Full();
+ var other = shared.DuplicateAs("Copy");
+ ArticulationMapAssignment.Assign(e, t1, shared);
+ ArticulationMapAssignment.Assign(e, t2, shared);
+ ArticulationMapAssignment.Assign(e, t3, other);
+ yield return (ArticulationMapUsage.TracksUsing(e, shared.Id).SequenceEqual(new[] { t1, t2 }) && ArticulationMapUsage.TracksUsing(e, other.Id).SequenceEqual(new[] { t3 }),
+ "articulations: the tracks using a map are found by its id");
+ e.ClearUndoHistory();
+ var edited = ArticulationMapFile.Read(ArticulationMapFile.Write(shared), "").Map!;
+ edited.Find(2)!.NoteOffsetMs = -180;
+ int n = ArticulationMapUsage.ApplyEverywhere(e, edited);
+ double OffsetOn(int t) => ArticulationMapAssignment.Read(e, t)!.Find(2)!.NoteOffsetMs;
+ yield return (n == 2 && OffsetOn(t1) == -180 && OffsetOn(t2) == -180 && OffsetOn(t3) == -150.5 && ArticulationMapAssignment.Read(e, t4) is null,
+ $"articulations: an edit reaches both tracks holding the map ({n}); the duplicate's track and a track without a map are untouched");
+ e.Undo();
+ yield return (OffsetOn(t1) == -150.5 && OffsetOn(t2) == -150.5 && !e.CanUndo,
+ "articulations: one undo takes the edit off every track that got it");
+
+ // ---- the manager's list: the library's maps plus project-only copies ----
+ string dir = Path.Combine(Path.GetTempPath(), "nota-art-catalog-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var lib = new Nota.Infrastructure.Articulations.ArticulationLibraryStore(dir);
+ lib.Save(shared);
+ var cat = ArticulationMapUsage.Catalog(e, lib);
+ yield return (cat.Count == 2 && cat.Single(x => x.Map.Id == shared.Id).OnlyInProject == false
+ && cat.Single(x => x.Map.Id == other.Id).OnlyInProject,
+ "articulations: the manager lists library maps once and flags a map only the project holds");
+
+ // The library got a newer version (saved, then undone on the tracks): the manager lists
+ // what the tracks play, flagged, so saving an edit can't put the library's version on them.
+ var newer = ArticulationMapFile.Read(ArticulationMapFile.Write(shared), "").Map!;
+ newer.Find(2)!.NoteOffsetMs = -321;
+ lib.Save(newer);
+ ArticulationMapUsage.ApplyEverywhere(e, newer);
+ e.Undo();
+ var cat2 = ArticulationMapUsage.Catalog(e, lib);
+ var listed = cat2.Single(x => x.Map.Id == shared.Id);
+ yield return (cat2.Count == 2 && listed.DiffersFromLibrary && !listed.OnlyInProject
+ && ArticulationMapFile.Write(listed.Map) == ArticulationMapFile.Write(ArticulationMapAssignment.Read(e, t1)!),
+ "articulations: when the project's copy differs from the library's, the manager lists the project's, flagged");
+ listed.Map.Name = "Restored project map";
+ lib.Save(listed.Map);
+ int restored = ArticulationMapUsage.ApplyEverywhere(e, listed.Map);
+ yield return (restored == 2 && OffsetOn(t1) == -150.5 && OffsetOn(t2) == -150.5
+ && !ArticulationMapUsage.Catalog(e, lib).Single(x => x.Map.Id == shared.Id).DiffersFromLibrary,
+ "articulations: saving a small edit after undo preserves the restored project offsets on every track");
+
+ // Copy readable map files to other filenames, including a differing version of the
+ // same ID. Both project-backed maps and maps only in the library must remain usable.
+ File.Copy(Path.Combine(dir, shared.Id + ArticulationMapFile.Extension), Path.Combine(dir, "copied.notamap"));
+ var onlyInLibrary = shared.DuplicateAs("Library-only map");
+ lib.Save(onlyInLibrary);
+ var different = ArticulationMapFile.Read(ArticulationMapFile.Write(onlyInLibrary), "").Map!;
+ different.Name = "Another copy";
+ File.WriteAllText(Path.Combine(dir, "different.notamap"), ArticulationMapFile.Write(different));
+ var readable = lib.List();
+ var duplicateCatalog = ArticulationMapUsage.Catalog(e, lib);
+ yield return (readable.Count == 4 && duplicateCatalog.Count == 3
+ && duplicateCatalog.Count(x => x.Map.Id == shared.Id) == 1
+ && duplicateCatalog.Count(x => x.Map.Id == onlyInLibrary.Id) == 1
+ && OffsetOn(t1) == -150.5 && !duplicateCatalog.Single(x => x.Map.Id == shared.Id).DiffersFromLibrary,
+ "articulations: copied map files with duplicate IDs do not block the manager or replace the project's map");
+ using var emptyProject = new NotaEngine();
+ var libraryCatalog = ArticulationMapUsage.Catalog(emptyProject, lib);
+ yield return (libraryCatalog.Count == 2 && libraryCatalog.All(x => !x.OnlyInProject && !x.DiffersFromLibrary)
+ && ArticulationMapFile.Write(libraryCatalog.Single(x => x.Map.Id == onlyInLibrary.Id).Map)
+ == ArticulationMapFile.Write(readable.First(x => x.Id == onlyInLibrary.Id)),
+ "articulations: a library-only catalog lists each duplicate ID once and retains the first readable copy");
+ }
+ finally { try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { } }
+
+ // ---- removing an articulation and saving leaves the notes' ids alone (data-model: ids are not reused) ----
+ int t5 = e.AddInstrumentTrack();
+ int c5 = e.AddMidiClip(t5, 0, 4);
+ e.SetClipNotes(t5, c5, new[] { new NotaNote(60, 0, 1, 0.8f) { ArticulationId = 7 }, new NotaNote(62, 1, 1, 0.8f) { ArticulationId = 9 } });
+ ArticulationMapAssignment.Assign(e, t5, shared);
+ var pruned = ArticulationMapFile.Read(ArticulationMapFile.Write(shared), "").Map!;
+ ArticulationMapEdits.Remove(pruned, 7);
+ int took = ArticulationMapUsage.ApplyEverywhere(e, pruned);
+ var kept = e.GetClipNotes(t5, c5).Select(x => x.ArticulationId).OrderBy(x => x).ToArray();
+ var onTrack = ArticulationMapAssignment.Read(e, t5)!;
+ yield return (took == 3 && kept.SequenceEqual(new[] { 7, 9 }) && onTrack.Find(7) is null && ArticulationMapEdits.NextId(onTrack) > 9,
+ $"articulations: saving a map without an articulation keeps the notes' ids ({string.Join(",", kept)}) and the id stays retired on the track ({took} tracks)");
+
+ // ---- the manager tells unsaved edits by comparing the written map; a map read back must write the same ----
+ // An imported map too: the importers fill fields (metadata, palette indices) Full() doesn't.
+ var maps = new List<(string Name, ArticulationMap? Map)>
+ {
+ ("Nota", ArticulationFileTests.Full()),
+ ("Cubase", ExpressionMapImporter.Import(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(
+ "<InstrumentMap><string name=\"name\" value=\"M\"/><member name=\"slots\"><list name=\"obj\" type=\"obj\">"
+ + "<obj class=\"PSoundSlot\"><obj class=\"PSlotMidiAction\" name=\"action\"><member name=\"midiMessages\"><list name=\"obj\" type=\"obj\">"
+ + "<obj class=\"POutputEvent\"><int name=\"status\" value=\"144\"/><int name=\"data1\" value=\"24\"/><int name=\"data2\" value=\"1\"/></obj>"
+ + "</list></member></obj><member name=\"name\"><string name=\"s\" value=\"Long\"/></member></obj></list></member></InstrumentMap>")), "m").Map),
+ ("Studio One", KeySwitchListImporter.Import(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(
+ "<Music.KeySwitchList name=\"K\"><Attributes name=\"Long\" id=\"1\" activation=\"note24.1|unknown\"/></Music.KeySwitchList>")), "k").Map),
+ };
+ var unstable = maps.Where(x => x.Map is null
+ || ArticulationMapFile.Write(ArticulationMapFile.Read(ArticulationMapFile.Write(x.Map), x.Map.Name).Map!) != ArticulationMapFile.Write(x.Map)).Select(x => x.Name).ToList();
+ // ---- the manager's effective-offset readout takes the right track offset (T053) ----
+ e.SetTrackMidiOffsetMs(t1, -100);
+ e.SetTrackMidiOffsetMs(t2, -40);
+ e.SetTrackMidiOffsetMs(t5, -40);
+ double? onSelected = ArticulationMapUsage.TrackOffsetFor(e, shared.Id, t1);
+ double? mixed = ArticulationMapUsage.TrackOffsetFor(e, shared.Id, t3); // t3 holds another map
+ e.SetTrackMidiOffsetMs(t1, -40);
+ double? sharedOff = ArticulationMapUsage.TrackOffsetFor(e, shared.Id, 0);
+ double? unused = ArticulationMapUsage.TrackOffsetFor(e, "no-such-map", t1);
+ yield return (onSelected == -100 && mixed is null && sharedOff == -40 && unused is null,
+ $"articulations: the manager's readout uses the selected track's offset when it holds the map ({onSelected}), else the one all its tracks share ({sharedOff}); none when they differ or no track holds it");
+
+ yield return (maps.Count == 3 && unstable.Count == 0,
+ $"articulations: a map read back from its file writes the same, so an opened map isn't taken for an edited one ({maps.Count} maps{(unstable.Count > 0 ? "; differ: " + string.Join(", ", unstable) : "")})");
+ }
+}
diff --git a/tests/Nota.SmokeTest/ArticulationUiTests.cs b/tests/Nota.SmokeTest/ArticulationUiTests.cs
new file mode 100644
index 00000000..8cd5aa5f
--- /dev/null
+++ b/tests/Nota.SmokeTest/ArticulationUiTests.cs
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Note colour by articulation (specs/085, US4, T059): which articulation's colour a note shows —
+// its own, else the default it plays as; a missing or disabled id keeps the track colour (it is
+// marked missing instead, FR-014) — and the palette slot of an articulation without a colour of
+// its own. Runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --articulations`.
+
+using Nota.Application.Articulations;
+
+namespace Nota.SmokeTest;
+
+internal static class ArticulationUiTests
+{
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ var m = ArticulationFileTests.Full(); // ids 2 (default), 7, and 9 (disabled)
+ int?[] Shown(params int[] ids) => ids.Select(id => ArticulationColours.Shown(m, id)?.Id).ToArray();
+
+ yield return (Shown(2, 7).SequenceEqual(new int?[] { 2, 7 }),
+ "articulations: a note shows its own articulation's colour");
+ yield return (ArticulationColours.Shown(m, 9) is null,
+ "articulations: a note on a disabled articulation keeps the track colour (it plays the default and is marked missing)");
+ yield return (ArticulationColours.Shown(m, 0)?.Id == m.DefaultArticulationId && m.DefaultArticulationId is not null,
+ $"articulations: a note without one shows the default it plays as ({m.DefaultArticulationId})");
+ yield return (ArticulationColours.Shown(m, 999) is null,
+ "articulations: a note whose articulation the map doesn't hold keeps the track colour (it is marked missing)");
+
+ var off = ArticulationFileTests.Full();
+ off.Find(7)!.Enabled = false;
+ off.Find(2)!.Enabled = false;
+ yield return (ArticulationColours.Shown(off, 7) is null && ArticulationColours.Shown(off, 0) is null,
+ "articulations: a disabled articulation, or a disabled default, shows the track colour");
+
+ var none = ArticulationFileTests.Full();
+ none.DefaultArticulationId = null;
+ yield return (ArticulationColours.Shown(none, 0) is null && ArticulationColours.Shown(null, 7) is null,
+ "articulations: no default, or no map, shows the track colour");
+
+ // The palette slot: the source's index when it gave one, else the id; stable and in range.
+ var a = new Articulation { Id = 23 };
+ var cub = new Articulation { Id = 23, SourceColorIndex = 4 };
+ var neg = new Articulation { Id = 1, SourceColorIndex = -3 };
+ yield return (ArticulationColours.PaletteSlot(a, 10) == 3 && ArticulationColours.PaletteSlot(cub, 10) == 4
+ && ArticulationColours.PaletteSlot(neg, 10) == 7 && ArticulationColours.PaletteSlot(a, 0) == 0,
+ "articulations: an articulation without a colour takes a palette slot from its source index, else its id (always in range)");
+
+ // Reordering the map doesn't change a note's colour: the slot follows the id, not the position.
+ var r = ArticulationFileTests.Full();
+ int before = ArticulationColours.PaletteSlot(r.Find(9)!, 10);
+ ArticulationMapEdits.Move(r, 9, -2);
+ yield return (ArticulationColours.PaletteSlot(r.Find(9)!, 10) == before,
+ "articulations: moving an articulation in the list keeps its notes' colour");
+ }
+}
diff --git a/tests/Nota.SmokeTest/LocalizationAllowList.txt b/tests/Nota.SmokeTest/LocalizationAllowList.txt
index 7f8679f2..494feb3f 100644
--- a/tests/Nota.SmokeTest/LocalizationAllowList.txt
+++ b/tests/Nota.SmokeTest/LocalizationAllowList.txt
@@ -2913,6 +2913,7 @@ Nota.Application/Palette/CommandCatalog.cs detach float pop out # data: search k
Nota.Application/Palette/CommandCatalog.cs devices clip # data: search keyword or alias of the palette and the browser, not shown
Nota.Application/Palette/CommandCatalog.cs dock undock float pop out mixer window # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)
Nota.Application/Palette/CommandCatalog.cs envelopes lanes # data: search keyword or alias of the palette and the browser, not shown
+Nota.Application/Palette/CommandCatalog.cs expression map keyswitch articulation manager library # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)
Nota.Application/Palette/CommandCatalog.cs faders channels # data: search keyword or alias of the palette and the browser, not shown
Nota.Application/Palette/CommandCatalog.cs find locate scroll reveal cursor position # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)
Nota.Application/Palette/CommandCatalog.cs finer smaller snap # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 003b2b4d..aec5cce6 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -453,6 +453,19 @@ if (args.Length >= 1 && args[0] == "--linux-desktop")
return failures == 0 ? 0 : 1;
}
+// Articulation map importers alone: `--articulations` (specs/085). Also part of the full run.
+if (args.Length >= 1 && args[0] == "--articulations")
+{
+ Console.WriteLine("-- articulations --");
+ foreach (var (ok, label) in ArticulationImportTests.Run()) Check(ok, label);
+ foreach (var (ok, label) in ArticulationFileTests.Run()) Check(ok, label);
+ foreach (var (ok, label) in ArticulationEngineTests.Run()) Check(ok, label);
+ foreach (var (ok, label) in ArticulationManagerTests.Run()) Check(ok, label);
+ foreach (var (ok, label) in ArticulationUiTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "ARTICULATIONS PASSED" : $"ARTICULATIONS FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+
// OS user-folder defaults alone: `--user-dirs` (#522). Also part of the full run.
if (args.Length >= 1 && args[0] == "--user-dirs")
{
@@ -14479,6 +14492,13 @@ Console.WriteLine("-- MCP tools --");
}).Wait();
var mcpNotes = mcpMidi.GetClipNotes(mcpT, mcpClip).Result;
Check(mcpNotes.Length == 3 && mcpNotes[0].Pitch == 60 && Math.Abs(mcpNotes[2].Length - 2) < 1e-3, $"MCP set/get_clip_notes round-trip ({mcpNotes.Length})");
+ // specs/085: an agent's get → edit → set keeps each note's articulation, and can set one.
+ mcpMidi.SetClipNotes(mcpT, mcpClip, new[] { mcpNotes[0] with { Articulation = 3 }, mcpNotes[1], mcpNotes[2] }).Wait();
+ var mcpArt = mcpMidi.GetClipNotes(mcpT, mcpClip).Result;
+ mcpMidi.SetClipNotes(mcpT, mcpClip, mcpArt).Wait(); // a plain round trip
+ var mcpArt2 = mcpMidi.GetClipNotes(mcpT, mcpClip).Result;
+ Check(mcpArt2.Length == 3 && mcpArt2.Single(n => n.Pitch == 60).Articulation == 3 && mcpArt2.Single(n => n.Pitch == 64).Articulation == 0,
+ "MCP set/get_clip_notes carries each note's articulation through a round trip");
mcpMidi.SetClipController(mcpT, mcpClip, "sustain", new[]
{
new Nota.Mcp.Tools.MidiTools.ControllerPoint(0, 1f), new Nota.Mcp.Tools.MidiTools.ControllerPoint(3.9, 0f),
@@ -15608,6 +15628,13 @@ foreach (var (ok, label) in LinuxDesktopTests.Run()) Check(ok, label);
Console.WriteLine("-- user dirs --");
foreach (var (ok, label) in UserDirsTests.Run()) Check(ok, label);
+Console.WriteLine("-- articulations --");
+foreach (var (ok, label) in ArticulationImportTests.Run()) Check(ok, label);
+foreach (var (ok, label) in ArticulationFileTests.Run()) Check(ok, label);
+foreach (var (ok, label) in ArticulationEngineTests.Run()) Check(ok, label);
+foreach (var (ok, label) in ArticulationManagerTests.Run()) Check(ok, label);
+foreach (var (ok, label) in ArticulationUiTests.Run()) Check(ok, label);
+
Console.WriteLine("-- range clipboard --");
foreach (var (ok, label) in RangeClipboardTests.Run()) Check(ok, label);