Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) MIDI recording: show notes while keys are held; record count-in pickups (#56) (#95)
Egor Khindikaynendd7b38d794b5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1790282e..9749c7e1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,18 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.### Added- **MCP `list_sections` and `set_sections`**: read and replace the arrangement's sections.+- **See MIDI notes while you record** (nota-daw/nota#56): a note now shows up in the take+ the moment the key goes down and grows with the playhead while the key is held, instead+ of appearing only on release. A new note fades in from the accent colour. Works in the+ arrangement, in a Session slot being recorded, and in the piano roll when it shows the+ take, for keyboard and MIDI input and for MIDI routed in from another track.++### Changed+- **Notes played on the count-in are recorded:** a pickup played during the count-in, or a+ key already held when recording starts, now lands in the take where it actually started.+ The take's clip begins earlier to include it. If the take starts at 1.1, the clip still+ starts there, and the part of the note before 1.1 is kept: extend the clip's left edge+ after moving it to hear it.## [0.55.1] — 2026-10-15diff --git a/FEATURES.md b/FEATURES.mdindex 6e2d54d0..a5390ec4 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -81,7 +81,7 @@ JUCE module; the engine core is JUCE-free.- **Tap tempo**: a TAP cell beside the BPM (and *Tap Tempo* in the command palette) sets thetempo from tapped beats — mean of the last eight gaps, restarts on a pace change or a 3 s pause.- **Loop region** (on/off and range; Cmd/Ctrl+L loops the selection).-- **Metronome** and **count-in** before recording.+- **Metronome** and **count-in** before recording (notes played on the count-in are recorded).- **Transport shortcuts** (Space play/stop, Enter stop, R/M/A, clip copy-paste, typingnotes, undo/redo) work in detached windows too.@@ -266,6 +266,12 @@ track count and closes with Escape.- **Input**: MIDI keyboard (live play and recording), and the **computer keyboard** playsMIDI (the S–K row, sharps on W E T Y U) — including while a hosted plugin window hasfocus.+- **MIDI recording**: a note appears in the take as soon as its key goes down and grows+ with the playhead while held, settling in from the accent colour — in the arrangement, in a+ recording Session slot and in the piano roll showing the take, for keyboard, MIDI and+ routed ("MIDI In") input. Notes played on the count-in and keys already held when+ recording starts are recorded where they started: the take's clip begins earlier to hold+ them (at 1.1 the part before the song start is kept beyond the clip's left edge).- **MPE (per-note expression)** — an MPE controller's notes each carry their own pitchbend, pressure and slide (CC74): channels 2–16 are per-note (lower zone, ±48 semitones bydefault; the controller's MPE Configuration and bend-range messages are honoured), channel 1diff --git a/specs/017-live-midi-record-notes/checklists/requirements.md b/specs/017-live-midi-record-notes/checklists/requirements.mdnew file mode 100644index 00000000..638b2e43--- /dev/null+++ b/specs/017-live-midi-record-notes/checklists/requirements.md@@ -0,0 +1,35 @@+# Specification Quality Checklist: Live MIDI notes while recording++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-16+**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++- Code references (engine capture arrays, view files) live only in the Nota Context section, which the project's spec template asks for to drive the plan. FR-009 / FR-011 state the project's binding constraints (real-time safety, public engine interface, smoke test) as requirements, not as a design.+- Items marked incomplete require spec updates before `/speckit-clarify` or `/speckit-plan`diff --git a/specs/017-live-midi-record-notes/contracts/c-abi.md b/specs/017-live-midi-record-notes/contracts/c-abi.mdnew file mode 100644index 00000000..e9e7a524--- /dev/null+++ b/specs/017-live-midi-record-notes/contracts/c-abi.md@@ -0,0 +1,57 @@+# Contract: C ABI for held recorded notes++Added to `src/native/nota.engine/include/nota/nota_engine.h`, next to the audio take+geometry (`nota_engine_audio_record_*`). Pure C, POD only (AR-7).++```c+/* One note held into the in-progress MIDI take (live-recording preview, #56). */+typedef struct NotaRecordHeldNote {+ int32_t pitch; /* 0..127 */+ int32_t source; /* 0 live input (keyboard, MIDI, Remote), 1 routed MIDI ("MIDI In") */+ double start_beat; /* arrangement: absolute timeline beat, may precede the take's clip+ and be < 0 (played on the count-in before 1.1);+ Session: slot-local beat */+ float velocity; /* 0..1 */+} NotaRecordHeldNote;++/* Notes currently held into the in-progress MIDI take — keys down that will be written+ * into the take on release — for drawing them growing. Copies up to max_n entries and+ * returns the count (0 when no MIDI take is recording or nothing is held). Optional+ * outputs: *track_id the take's track (0 = none), *session_scene the Session scene being+ * recorded (-1 = arrangement take), *now_beat the capture clock (the held notes' right+ * edge; runs during the count-in too, in the same coordinates as start_beat).+ * Lock-free; safe from any non-audio thread. */+NOTA_API int32_t nota_engine_record_held_notes(const NotaEngine* engine,+ NotaRecordHeldNote* out, int32_t max_n,+ int32_t* track_id, int32_t* session_scene,+ double* now_beat);+```++## Guarantees++- Every returned note is one the engine will store on release if recording continues+ (FR-007); a note dropped by a recording/transport stop disappears from the next read.+- After a note-off is processed, the note is absent from the snapshot and present in the+ `recorded_` queue in the same block — after the next `nota_engine_poll` it is in the clip,+ so a reader that polls first and then reads the snapshot never sees it twice or not at all.+- `start_beat` equals the start the stored note will have (before the clip left move+ is applied; the stored clip-relative start is `start_beat − clip start`).+- No allocation or lock on any thread; a reader racing the writer retries a bounded number+ of times and otherwise returns 0 for that call.+- `out == NULL` or `max_n <= 0` returns the count without copying.++## Behaviour changes behind the same ABI (no new calls)++- Notes started during the count-in and keys held when recording starts are recorded+ (FR-012); the take's clip may move its start earlier during recording (FR-013) —+ readers of `nota_clip_*` see the new start after `nota_engine_poll`.+- Notes with negative clip-relative `start_beat` (via `nota_clip_get_notes`) are legal and+ render from the clip start when they reach into the clip.++## Managed mapping++- `NativeMethods.RecordHeldNotes(IntPtr, [Out] NotaRecordHeldNote[], int, out int, out int, out double)`+ with a `[StructLayout(LayoutKind.Sequential)]` struct (int, int, double, float — natural+ alignment, matches C).+- `IAudioEngine.RecordHeldNotes(NotaRecordHeldNote[] buffer, out int trackId,+ out int sessionScene, out double nowBeat) : int`.diff --git a/specs/017-live-midi-record-notes/contracts/ui-preview.md b/specs/017-live-midi-record-notes/contracts/ui-preview.mdnew file mode 100644index 00000000..763c43b2--- /dev/null+++ b/specs/017-live-midi-record-notes/contracts/ui-preview.md@@ -0,0 +1,60 @@+# Contract: UI preview of held recorded notes++What each view draws, when, and how it animates. Follows `DESIGN.md` (Studio) and the+`nota-design` skill.++## Data flow++1. `MainWindowViewModel.OnTick` (33 ms) calls `Engine.Poll()`, then raises+ `RecordingTick` while `Engine.IsRecording` (unchanged).+2. On `RecordingTick`, `RecordPreview.Update()` reads the snapshot once+ (`RecordHeldNotes`), and the set of notes in the take's clip/slot, and updates the+ appear-animation tracker. Then the existing `Timeline.Refresh(rebuildHeaders: false)`+ and `ReloadEditorNotes()` run, and the Session grid refresh as today.+3. Views draw from `RecordPreview` during their normal render; they never call the engine+ for the preview themselves.+4. When recording stops, `RecordPreview` clears; the final refresh draws stored notes only.++## Arrangement take (`ArrangementView.LaneControl`)++- On the take's track row only, if visible (`rLo..rHi`).+- Each held note: x from `BeatToX(startBeat)` to `BeatToX(max(startBeat, nowBeat))`,+ min 2 px; y from the same pitch mapping the take's clip uses (its pitch range extended+ to include held pitches).+- Held notes before the clip's start (count-in) draw left of the clip, over a faint+ extension of the take box from the earliest held start to the clip start, so they are+ not floating on the empty lane.+- Colour: the track's note colour, as stored notes are drawn; animated as below.++## Session slot (`SessionView.Grid`)++- The recording cell draws the slot's notes stored so far (it showed none while recording+ before), so the held notes sit among the take rather than on an empty cell; an open-ended+ take scales to the whole bars recorded so far.+- In the slot being recorded (`session_scene ≥ 0`), slot-local: x by `startBeat / slotLen`;+ a note crossing the loop end draws as two pieces (tail at the end, wrap from 0 to+ `nowBeat`).++## Piano roll (`PianoRollView`)++- Only when it shows the take's clip (`_editorTrackId == trackId` and the clip index is+ the record clip; arrangement takes). Clip-relative x: `startBeat − clipStart`.+- Held notes are an overlay, not editable, not selectable, not part of `SetNotes`.+- Notes left of the clip start (count-in) draw in the area before beat 0 if the roll shows+ it, else are clipped at the left edge.++## Appear animation++- Duration 150 ms (within 120–200 ms, FR-008), ease-out.+- Progress `p = clamp((now − firstSeen) / 150 ms, 0, 1)`; opacity `0.35 + 0.65·e(p)`;+ fill = blend(accent, note colour, e(p)).+- Starts on the first tick a note is seen held, or newly present in the take's stored+ notes if it was never seen held (staccato between ticks). Growth, release and the clip+ left move never restart it (key = pitch + absolute start beat).++## Repaint rules++- No preview work and no extra invalidation while not recording (FR-010, SC-004).+- While recording, the preview rides the existing `RecordingTick` repaint; no new timer.+ If the quickstart shows the animation is choppy at 30 Hz, a 60 Hz timer may run only+ while an animation entry is younger than 150 ms.diff --git a/specs/017-live-midi-record-notes/data-model.md b/specs/017-live-midi-record-notes/data-model.mdnew file mode 100644index 00000000..fac4ed2c--- /dev/null+++ b/specs/017-live-midi-record-notes/data-model.md@@ -0,0 +1,80 @@+# Data Model: Live MIDI notes while recording++Phase 1 of [plan.md](plan.md). Nothing here is persisted except the clip's notes.++## Capture clock (engine, audio thread)++The beat the capture code stamps events with. Derived from `Transport` (AR-9) and the+count-in counters; never stored.++| State | Value |+|-------|-------|+| Transport rolling (arrangement) | block start beat (`playheadSamples / spb`) |+| Count-in running | `takeStartBeat − (countInTotal − countInPos)` — below `takeStartBeat`, may be < 0 |+| Session slot take | slot-local beat, `fmod(localBeats, slotLen)` |+| Stopped, no count-in | not capturing |++## Held live key (engine, audio thread)++One per pitch per source (live input, routed MIDI). Tracked while the transport is rolling+or a count-in runs, whether or not recording is on; used to seed the take on the record+rising edge (research R3).++| Field | Type | Notes |+|-------|------|-------|+| down | bool | key currently held |+| pressBeat | double | capture clock at note-on |+| velocity | float | 0..1 |+| trackId | int32 | Remote-addressed track, −1 = ordinary live input |++## Held recorded note (engine → UI)++An entry of the take's held set: a note that will be written into the take on release.+Exists from note-on (or from the record edge, when seeded) until note-off, recording+stop or transport stop.++| Field | Type | Rule |+|-------|------|------|+| pitch | int32 | 0..127 |+| source | int32 | 0 live input, 1 routed MIDI |+| startBeat | double | capture clock at start. Arrangement: absolute timeline beat, may be before the take's clip start and below 0 (count-in before 1.1). Session: slot-local |+| velocity | float | 0..1 |++Lifecycle: `none → held` (note-on while capturing, or seeded at record edge) →+`stored` (note-off: becomes a `RecordedNote`, leaves the held set in the same block) or+`dropped` (recording/transport stops first — as today, not stored).++Invariant: a pitch/source pair is held at most once; a re-trigger closes the previous+note first (today's `pendingActive_` semantics).++## Held-note snapshot (engine → UI, published per block)++| Field | Type | Notes |+|-------|------|-------|+| seq | atomic uint32 | odd while writing; readers retry on odd or changed |+| trackId | int32 | take's track; 0 when no MIDI take |+| sessionScene | int32 | −1 for arrangement takes |+| nowBeat | double | capture clock at the end of the block (right edge of held notes) |+| count | int32 | 0..256 |+| entries | Held recorded note × 256 | live (128) + routed (128) |++## Stored early note (clip data)++Ordinary `Note` in the take's `MidiClip`; `startBeat` is clip-relative.++| Case | Clip start | Note startBeat |+|------|-----------|----------------|+| Early note after beat 0 | moved back to the note's start | 0 (or ≥ 0 for later notes; existing notes shifted by the delta) |+| Early note before beat 0 (take at 1.1) | 0 | negative; the part `[0, start+length)` sounds from the clip start |++Render rule: a note with `startBeat < 0` and `startBeat + lengthBeats > 0` sounds from+the clip start for the remaining length; notes with `startBeat ≥ lengthBeats` stay muted.++## Appear-animation entry (UI only)++| Field | Type | Notes |+|-------|------|-------|+| key | (pitch, startBeat rounded to 1e-6) | absolute beat for arrangement, slot-local for Session |+| firstSeen | timestamp | first tick the note was held or newly stored |++Dropped 150 ms after `firstSeen`. A key already present never restarts the animation.diff --git a/specs/017-live-midi-record-notes/plan.md b/specs/017-live-midi-record-notes/plan.mdnew file mode 100644index 00000000..7a20627b--- /dev/null+++ b/specs/017-live-midi-record-notes/plan.md@@ -0,0 +1,134 @@+# Implementation Plan: Live MIDI notes while recording++**Branch**: `feat/live-midi-record-notes` | **Date**: 2026-10-16 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `/specs/017-live-midi-record-notes/spec.md`++## Summary++While a MIDI take records, held notes show in the take from their start to the+capture clock and grow tick by tick. New notes fade in with an accent flash over+about 150 ms. Notes played during the count-in, and keys already held when Record is+pressed, are recorded at their real start. The take's clip moves its left edge back to+include them. Before 1.1 the note keeps a head past the clip's left edge, and the part+inside the clip sounds from the clip start.++Engine: a capture clock that also runs during the count-in, seeding of held keys on the+record edge, a seqlock snapshot of held captured notes, a new C ABI read, the clip+left-move in `poll`, and the negative-start render rule. UI: one snapshot read per+recording tick, drawn in the arrangement take, the Session slot and the piano roll, plus+a shared appear-animation tracker. Details and rationale: [research.md](research.md).++## Nota: Read Before Planning++Consult the matching source of truth before designing:++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): the AR rules table is binding (AR-4 lock-free queue, AR-5 immutable snapshots, AR-6 audio-thread restrictions, AR-7 pure C ABI, AR-9 `Transport` is the only source of musical time).+- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Studio design language) and the `nota-design` skill.+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md): licensing, dependency policy, PR expectations.++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 (managed app, Avalonia UI)++**Primary Dependencies**: None new. The engine uses only `<atomic>`, and the UI uses Avalonia drawing.++**Storage**: No new storage. Early notes are stored as ordinary clip notes, and a note can have a negative `startBeat` when it starts before 1.1. The project format is unchanged: a note's start is already a double.++**Audio-Thread Impact**:+- Capture now also runs during the count-in.+- Held keys are tracked while the transport rolls or a count-in runs.+- Each block publishes up to 256 snapshot entries (128 per source) through relaxed atomics and a sequence counter.+- There are no allocations, locks or I/O. The fixed arrays are sized at 128 pitches × 2 sources and live in `Engine` (AR-6).+- Note gating in the render accepts a note that starts before the clip and ends inside it. This is a branch on data already read.+- AR-9 holds: the capture clock is derived from `Transport` and the count-in counters.++**Testing**: `tests/Nota.SmokeTest` (offline engine through the C ABI), `scripts/build.sh`. Visual check of the animation via the headless and in-app capture recipe ([quickstart.md](quickstart.md)).++**Target Platform**: macOS, Linux, Windows desktop.++**Project Type**: desktop app (native engine + managed UI).++**Performance Goals**:+- A held note shows up by the next recording tick (≤ 33 ms plus audio latency).+- The animation runs about 150 ms, which is 5 frames at 30 Hz.++**Constraints**:+- No new repaints while idle.+- The preview piggybacks on the existing `RecordingTick` refresh.+- No new timer unless the quickstart shows the animation is choppy.++**Scale/Scope**:+- Up to 128 held pitches per source.+- Three views: arrangement lanes, Session grid and piano roll.+- About 6 engine files, 1 header, 3 interop/app layers and 1 smoke-test file.++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*++| Principle | Status | Notes |+|-----------|--------|-------|+| I. Real-time audio safety | ✅ | The seqlock writer is wait-free and uses fixed arrays. No alloc, lock or I/O. Commands still enter through the queue. Clip edits happen on the message thread in `poll` (AR-5 republish). |+| II. Boundary discipline | ✅ | One new C ABI function and a POD struct in `nota_engine.h`. No C++ types cross the boundary, and JUCE is not involved. |+| III. Licensing hygiene | ✅ | No new dependency. New files (`LiveRecordTests.cs`, possibly a small UI helper) carry the SPDX header. |+| IV. Verification gate | ✅ | Smoke tests cover the new read, count-in capture, held-key seeding, clip left move and negative-head render (R8). |+| V. One logical change | ✅ | Everything here makes "what you play while recording is what you see" true. It is still one PR, but tasks keep engine and UI separable. |+| VI. Docs in sync | ✅ | Planned: a CHANGELOG `[Unreleased]` entry, `nota-features` (FEATURES.md) and `nota-docs` (recording page: live notes and count-in pickup). No shortcuts change. |+| VII. Spec-first | ✅ | spec → clarify (2 Q) → this plan. |+| VIII. Rules not weakened | ✅ | Nothing bends I–III. |++Post-design re-check: the design artifacts introduce nothing beyond the table above, so the check still passes.++## Project Structure++### Documentation (this feature)++```text+specs/017-live-midi-record-notes/+├── plan.md # this file+├── research.md # Phase 0: decisions R1–R8+├── data-model.md # Phase 1: held note, snapshot, capture clock, animation entry+├── quickstart.md # Phase 1: how to validate end-to-end+├── contracts/+│ ├── c-abi.md # nota_engine_record_held_notes + NotaRecordHeldNote+│ └── ui-preview.md # what each view draws, animation timing, repaint rules+└── tasks.md # Phase 2 (/speckit-tasks)+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # + NotaRecordHeldNote, nota_engine_record_held_notes+└── src/+ ├── Engine.h # capture clock helper, held-key arrays, snapshot (seq + slots)+ ├── Engine_Render.cpp # drainLiveMidi / captureRoutedNotes gating + clock,+ │ # record-edge seeding, snapshot publish, poll() clip left move,+ │ # negative-start note rule (computeBlockMidi + session paths)+ ├── Engine_Recording.cpp # recordHeldNotes() reader; take start beat for count-in clock+ ├── Engine_Tracks.cpp # negative-start rule in the offline/bounce note path (:1807)+ └── nota_engine_track.cpp # C ABI shim++src/managed/+├── Nota.Application/Engine/IAudioEngine.cs # + RecordHeldNotes(...)+├── Nota.Infrastructure/Interop/NativeMethods.cs # + P/Invoke, struct+├── Nota.Infrastructure/Interop/NotaEngine.cs # + wrapper+├── Nota.Presentation/ViewModels/MainWindowViewModel.cs # RecordingTick unchanged (already 30 Hz while recording)+└── Nota.App/+ ├── RecordPreview.cs # NEW: per-tick snapshot + appear-animation tracker shared by views+ ├── MainWindow.axaml.cs # RecordingTick → RecordPreview.Update, then refreshes as today+ ├── ArrangementView.LaneControl.cs # draw held notes in the take row (incl. left of the clip)+ ├── SessionView.Grid.cs # draw held notes in the recording slot+ └── PianoRollView.cs # held-note overlay when it shows the record clip++tests/Nota.SmokeTest/+├── LiveRecordTests.cs # NEW (R8)+└── Program.cs # register the suite+```++**Structure Decision**: The existing engine split stays: capture lives in `Engine_Render.cpp` and the take lifecycle in `Engine_Recording.cpp`. The C ABI shim sits next to `nota_engine_live_held_notes` in `nota_engine_track.cpp`. On the UI side, one small `RecordPreview` class owns the snapshot and the animation clock, so the three views draw from the same data in the same frame.++## Complexity Tracking++No constitution violations, nothing to justify.diff --git a/specs/017-live-midi-record-notes/quickstart.md b/specs/017-live-midi-record-notes/quickstart.mdnew file mode 100644index 00000000..bef5bf77--- /dev/null+++ b/specs/017-live-midi-record-notes/quickstart.md@@ -0,0 +1,48 @@+# Quickstart: validating live MIDI notes while recording++How to prove the feature end-to-end. Contracts: [c-abi.md](contracts/c-abi.md),+[ui-preview.md](contracts/ui-preview.md). Entities: [data-model.md](data-model.md).++## 1. Build and smoke test (gate)++```bash+scripts/build.sh+```++Must exit green. The new `LiveRecordTests` suite checks, offline through the C ABI:++| Check | Expected |+|-------|----------|+| note-on while recording | snapshot has the pitch, `start_beat` = press beat, `now_beat` advances with rendering |+| note-off | pitch leaves the snapshot; after `Poll` the clip holds a note with the same start / length / pitch |+| pickup on the count-in (take at bar 5, 1-bar count-in, note on the last count-in beat, released before bar 5) | stored note starts one beat before bar 5; the clip starts there; offline render sounds it |+| key held across Record (transport rolling) | stored from its press beat, not the record start |+| take at 1.1, key pressed one beat before | clip starts at 0; note `startBeat ≈ −1`; render has the note sounding from 0 |+| routed MIDI into the armed track | snapshot entry with `source = 1` |+| Session slot take | snapshot `session_scene ≥ 0`, slot-local `start_beat` |+| stop recording with a key held | snapshot empty, nothing stored for that key (as today) |++## 2. In the app (manual or via the UI verify harness)++1. New project, one instrument track, arm it, 1-bar count-in, press Record.+2. On the count-in's last beat play a short note, then hold a chord into bar 1.+3. Expected: the pickup and chord appear the moment the keys go down (the pickup left of+ 1.1 over the faint take extension), the chord grows with the playhead; each note fades+ in with an orange flash for about 150 ms; on release nothing jumps.+4. Stop. The clip starts at 1.1; the pickup's in-clip part plays from 1.1. Move the clip+ right one bar and drag its left edge out: the pickup's head appears and plays.+5. Open the clip in the piano roll and record again (overdub): held notes grow on the grid.+6. Record into a Session slot and hold a note across the loop end: it wraps as stored.++Headless capture (no GUI launch needed): the harness pattern in the project memory+(`Avalonia.Headless` + `CaptureRenderedFrame`), injecting held notes through a stub+`IAudioEngine.RecordHeldNotes` to shoot the take at animation progress 0, 0.5 and 1.++## 3. Performance++- Stopped, nothing held: repaint/CPU unchanged vs `develop` (Preferences CPU meter and+ `ProcessCpuTests` baseline).+- Record a 2-minute take with continuous playing: dropout counter stays at 0 (status bar+ / `XrunCount`), UI CPU within 10% of an audio take of the same length (SC-005).+- If the flash looks stepped at 30 Hz, enable the animation-only 60 Hz timer+ (ui-preview.md § Repaint rules) and re-measure.diff --git a/specs/017-live-midi-record-notes/research.md b/specs/017-live-midi-record-notes/research.mdnew file mode 100644index 00000000..42dc38c5--- /dev/null+++ b/specs/017-live-midi-record-notes/research.md@@ -0,0 +1,144 @@+# Research: Live MIDI notes while recording++Phase 0 of [plan.md](plan.md). Each section records a decision, why, and what else was+considered. File references are to the state of `develop` at 0.55.1.++## R1 — How the held notes leave the audio thread++**Decision**: The audio thread publishes a compact snapshot of the held captured notes+once per block behind a sequence counter (a seqlock: one writer, readers retry). Each+slot is made of relaxed `std::atomic` fields so the read is not a data race. The snapshot+holds the take's track id, the capture clock's "now" beat and up to 256 entries (128 pitches × live and routed)+(pitch, source, start beat, velocity). A new C ABI call copies it out+(see [contracts/c-abi.md](contracts/c-abi.md)).++**Rationale**: The capture state (`pendingActive_` / `pendingStart_` / `pendingVel_` and+`recRoutedActive_` / … in `Engine.h`) is plain audio-thread memory; the UI must not read+it directly. The writer never waits, allocates or locks (AR-6); at most 256 small stores+per block. Readers are the UI tick at ~30 Hz; a torn read is retried a few times and+otherwise returns the previous count of 0 — a dropped frame of preview, never a stall.+The "now" beat travels in the same snapshot so the note's right edge and its start come+from one consistent instant, including during the count-in, when the transport playhead+does not move.++**Alternatives considered**:+- *Per-pitch atomics only* (like `liveHeld_` bitmask, `Engine.h:1520`): a bitmask works for+ "which keys are down" but not for a start beat + velocity per note without tearing.+- *SPSC ring of on/off events to the UI* (like `recorded_`): the UI would have to rebuild+ state and resynchronise after a missed event or a stop; the snapshot is self-healing.+- *Reading `recorded_` earlier / writing open notes into the clip*: would turn the preview+ into stored data and churn undo/republish every tick; rejected.++## R2 — Capturing notes during the count-in (FR-012)++**Decision**: Give the capture code a *capture clock* instead of the transport beat:+- transport rolling → the block's start beat (today's `blockStartBeat`);+- count-in running → `takeStartBeat − (countInTotal_ − countInPos_)`, i.e. negative+ offsets before the take start (beats before 1.1 when the take starts at 1.1);+- Session slot → the slot's loop-local clock (unchanged).++`drainLiveMidi` and `captureRoutedNotes` capture when `recording && (playing ||+countInActive_)` (today only `playing`, `Engine_Render.cpp:459` and `:682`).++**Rationale**: During the count-in the transport is stopped (`Transport::advanceBy`+only moves when playing) and `drainLiveMidi` gates on `playing`, which is why count-in+notes are lost today. `recording_` is already true from the moment Record is pressed+(`Engine_Recording.cpp`, `setRecording`), so only the gate and the clock change.++**Alternatives considered**: A dedicated pre-roll buffer replayed at take start — more+state, same result.++## R3 — Keys already held when recording starts (FR-012)++**Decision**: Track every live (and routed-into-the-record-track) note-on with its press+beat on the capture clock *whenever the transport is rolling or a count-in runs*, in+audio-thread arrays separate from the record pending state. On the record rising edge+(`prevRecording_` flip, `Engine_Render.cpp:417`), instead of only clearing the pending+arrays, seed them from the keys still down for the take's track:+- pressed while rolling → their real press beat;+- pressed while stopped, then Record with count-in → the count-in's first beat;+- pressed while stopped, Record without count-in → the take start beat.++Notes pressed and released before Record while rolling are not captured (clarified).++**Rationale**: Today the rising edge wipes `pendingActive_`, dropping those keys. The press+beat is only knowable on the audio thread, where events are timed.++## R4 — Storing early notes: moving the clip's left edge (FR-013)++**Decision**: In `Engine::poll` (`Engine_Render.cpp:276–292`), when a materialised note's+absolute start is before `clip.startBeat`, move the clip's start back to+`max(0, noteStart)` and shift the clip's existing notes and length by the same delta+(as `trimClip` does, `Engine_Tracks.cpp:1903`). A note still starting before the new+clip start (only possible before 1.1) is stored with a negative `startBeat`.++Render change: a note whose `startBeat < 0` but whose end is inside the clip sounds from+the clip start with the remaining length. Today every gating site skips it+(`Engine_Render.cpp:524`, `:749`, `:765`, `Engine_Tracks.cpp:1807`); each gets the same+rule. Notes starting at or after the clip end stay skipped.++The take's undo step is unchanged: the left move is part of the live take+(`republishWithTrackRaw`, no extra undo step).++**Rationale**: Matches the clarification; `trimClip` already keeps notes in place when the+left edge moves, so a stored negative head becomes audible and visible as soon as the+left edge is extended — after moving the clip right if it sits at 1.1. Clips cannot start+before beat 0 (`trimClip` clamps), so negative note starts are the only way to keep the+head.++**Alternatives considered**: Clamping the note to the clip start (rejected by the user);+allowing negative clip starts (touches every timeline consumer, export, ruler).++## R5 — Session slots++**Decision**: Session slots keep today's behaviour for early notes: `std::fmod(r.startBeat+< 0 ? 0 : …)` (`Engine_Render.cpp:266`) — an early note starts at the slot start. The held+preview is slot-local and is drawn in the slot being recorded. Notes crossing the loop+end are previewed wrapped, the same way `drainLiveMidi` computes `len += slotLen`.++**Rationale**: Clarified in the spec's assumptions; a slot has no timeline before its+start.++## R6 — Where and how often the UI redraws++**Decision**: Draw the preview from the existing recording tick: `MainWindowViewModel.OnTick`+(33 ms) raises `RecordingTick` while `Engine.IsRecording`, which already calls+`Timeline.Refresh(rebuildHeaders: false)` and `ReloadEditorNotes()`+(`MainWindow.axaml.cs:318`). The tick reads the snapshot once and hands it to the+arrangement lanes, the Session grid and the piano roll. No new timer; the 30 Hz rate stays.++**Rationale**: The lane surface already repaints on every recording tick (full clip-model+refresh), so the preview adds only a few rectangles to work that already happens.+`RecordingTick` fires only while recording (count-in included, since `recording_` is set+at Record), so the idle repaint rate is untouched (FR-010, SC-004). Limiting the lane+redraw to the take's rectangle would be an improvement to the *existing* recording+refresh as well; it is not needed for this feature and is left as a follow-up.++**Alternatives considered**: A separate 60 Hz animation timer — only if 30 Hz looks choppy+in the quickstart check (5 frames over 150 ms with ease-out is expected to be smooth).++## R7 — The appear animation++**Decision**: A UI-side tracker, shared by the views, maps each recorded note in the take —+held (from the snapshot) or just materialised (new in the record clip since the last+tick) — keyed by (pitch, absolute start beat), to the time it was first seen. Draw+progress `p = clamp((now − firstSeen) / 150 ms)`: opacity `0.35 → 1` and a blend from the+accent colour to the track's note colour, ease-out. Entries older than 150 ms are dropped+from the tracker; growth and release keep the key, so they never re-animate. Notes that+were pressed and released between two ticks (never held in a snapshot) still animate,+because they appear as new materialised notes.++**Rationale**: Covers FR-008 and SC-006 including staccato; the colour use follows the+Studio rule that the orange accent marks what is live (`DESIGN.md`).++## R8 — Smoke test++**Decision**: Extend `tests/Nota.SmokeTest` (a new `LiveRecordTests.cs`, registered in+`Program.cs`) driving the engine offline like `MpeTests.Recording`:+held snapshot appears on note-on and grows with the clock; disappears on note-off and the+stored note matches; count-in pickup note stored before the take start; key held across+Record seeded at its press beat; take at 1.1 keeps a negative head and the in-clip part+renders; routed MIDI previewed; Session slot preview is slot-local.++**Rationale**: Constitution IV and FR-011: engine behaviour changes and a new C ABI read+need smoke coverage.diff --git a/specs/017-live-midi-record-notes/spec.md b/specs/017-live-midi-record-notes/spec.mdnew file mode 100644index 00000000..f7dc4766--- /dev/null+++ b/specs/017-live-midi-record-notes/spec.md@@ -0,0 +1,197 @@+# Feature Specification: Live MIDI notes while recording++**Feature Branch**: `feat/live-midi-record-notes`++**Created**: 2026-10-16++**Status**: Draft++**Input**: User description: "MIDI recording: show notes in the clip while keys are held, not only on release (GitHub issue nota-daw/nota#56). Today a recorded MIDI note appears on the grid only after the key is released. Notes should appear the moment a key is pressed and grow to the right up to the playhead while held, as in most DAWs; on release the note gets its final length. Applies to arrangement recording and the clip editor/piano roll, to live keyboard input and routed MIDI ("MIDI In") capture, and to Session slot recording (loop wrap). A newly appearing note plays a short appear animation (fade/accent flash ~120–200 ms). Constraints: no audio-thread allocation or locking — the engine publishes a snapshot of held captured notes (pitch, start beat, velocity) via a new C ABI read; the UI must not raise idle repaint cost (redraw only while notes are held or animating, prefer redrawing only the take region, stay on the existing ~30 Hz tick unless animation looks choppy)."++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [ ] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++Today the engine keeps a held recorded note only in audio-thread capture state+(`pendingActive_` / `pendingStart_` / `pendingVel_` for live input, `recRoutedActive_` /+`recRoutedStart_` / `recRoutedVel_` for routed MIDI, in `Engine.h`) and hands it to the+message thread as a finished note on note-off (`Engine_Render.cpp`, `drainLiveMidi` and+`captureRoutedNotes`; `nota_engine_poll` materialises it into the clip). Audio recording+already exposes its growing take to the UI (`nota_engine_audio_record_*`); MIDI has no+equivalent. The UI side is the arrangement lanes (`ArrangementView.LaneControl.cs`), the+Session grid (`SessionView.Grid.cs`) and the piano roll (`PianoRollView.cs`). The+arrangement deliberately repaints only its overlay on the playhead tick, not the lane+surface (see #55) — this feature must not undo that.++**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).++## Clarifications++### Session 2026-10-16++- Q: Which notes played before recording starts go into the take — only keys still held at the start, or also notes played and released during the count-in? → A: Keys still held at the start plus every note started during the count-in, even if released before the start (e.g. a pickup).+- Q: How is a note that starts before the clip's start stored and played? → A: The clip's left edge moves back to the earliest note's start; before 1.1 (the song start) the clip starts at 1.1 and the note's head is kept past the clip's left edge, to reappear and sound once the clip's left edge is extended (after moving the clip right, if it sits at 1.1).++## User Scenarios & Testing *(mandatory)*++### User Story 1 - See held notes grow in the arrangement (Priority: P1)++A player arms an instrument track, starts recording and plays a slow chord, holding it+for two bars. The moment the keys go down, three notes appear in the take at the+playhead's position and stretch to the right with the playhead for as long as the chord+is held. When the keys are released, the notes stop growing and keep exactly the length+they had — nothing jumps or reappears.++**Why this priority**: This is the issue itself. Without it the player records blind+during long notes and pads and cannot tell whether the keyboard is reaching the track.++**Independent Test**: Record onto a MIDI track in the arrangement, hold a key for several+beats and watch the take; release and compare the drawn note with the note stored in the+clip afterwards.++**Acceptance Scenarios**:++1. **Given** an armed instrument track and recording running, **When** the player presses a key, **Then** a note at that pitch appears in the take within one screen refresh of the playhead tick, starting at the beat where the key went down.+2. **Given** a key held while recording, **When** the playhead moves on, **Then** the drawn note's right edge follows the playhead.+3. **Given** a held note being drawn, **When** the key is released, **Then** the note stops at the release position and its drawn start, length and pitch equal the note saved in the clip.+4. **Given** several keys pressed and released at different times, **When** they overlap, **Then** each held note grows independently and each finishes at its own release.+5. **Given** a key held while recording, **When** recording is stopped (or transport stops) before the key is released, **Then** the in-progress note disappears or is finalised exactly as today's recording behaviour finalises it — the preview never leaves a note behind that the clip does not contain.+6. **Given** recording with a count-in starting at bar 5, **When** the player plays a pickup note on the count-in's last beat and releases it before bar 5, **Then** the note is recorded and shown on that beat before bar 5, the take's clip starts at that note, and playback sounds it.+7. **Given** recording with a count-in starting at 1.1, **When** the player presses a key one beat before 1.1 and holds it into the take, **Then** the clip starts at 1.1, the note sounds from 1.1, and its first beat is kept before the clip's left edge (it appears and sounds once the clip is moved right and its left edge extended).++---++### User Story 2 - Short appear animation (Priority: P2)++When a held note first shows up it fades in with a brief accent flash, so the player's eye+catches each new note even in a busy take.++**Why this priority**: Requested together with the feature and cheap on its own, but the+feature is fully usable without it.++**Independent Test**: Record a few staccato notes and a held note; each new note visibly+fades or flashes in once, over roughly 150 ms, then settles to the normal note colour.++**Acceptance Scenarios**:++1. **Given** recording is running, **When** a new note appears, **Then** it animates in over 120–200 ms and then draws like any other recorded note.+2. **Given** a note that is already shown, **When** it keeps growing or is released, **Then** it does not animate again.+3. **Given** very fast playing (many notes per second), **When** notes appear, **Then** each animates independently and the take stays readable — no lingering flashes.++---++### User Story 3 - Held notes in the piano roll while recording (Priority: P2)++A player has the recording take open in the clip editor (piano roll) and records; held+notes appear and grow on the piano-roll grid the same way they do in the arrangement.++**Why this priority**: The issue names both the arrangement and the clip editor; the+arrangement is where most recording happens, so the editor follows.++**Independent Test**: Open the clip being recorded into in the piano roll, record, hold a+key, and confirm the note grows on the grid and matches the saved note on release.++**Acceptance Scenarios**:++1. **Given** the piano roll shows the clip being recorded into, **When** a key is held, **Then** the note is drawn on the grid from its start to the playhead and grows with it.+2. **Given** the piano roll shows a different clip, **When** recording runs elsewhere, **Then** the piano roll draws no preview notes.++---++### User Story 4 - Routed MIDI and Session slots (Priority: P3)++A user records an instrument track fed from another track through "MIDI In", or records+into a Session slot; held notes preview the same way. In a Session slot, a note held across+the slot's loop end is drawn continuing from the loop start, the way it will be stored.++**Why this priority**: Same feature on less common record paths; without it the behaviour+would be inconsistent, but the main path already delivers the value.++**Independent Test**: (a) Route a MIDI source into an armed track, record, hold a note on+the source; (b) record into a Session slot and hold a note across the loop boundary.++**Acceptance Scenarios**:++1. **Given** an armed track fed by routed MIDI, **When** the source plays a held note, **Then** the note appears and grows in the take as in Story 1.+2. **Given** recording into a Session slot, **When** a key is held, **Then** the slot's take shows the growing note.+3. **Given** a note held across the Session slot's loop end, **When** the loop wraps, **Then** the preview matches how the note is stored on release (no note drawn outside the slot's length).++---++### Edge Cases++- The same key is pressed again before its previous press was recorded as released (re-trigger): the preview follows what the engine stores — one note per press, never a stuck preview note.+- More keys held than any reasonable limit (e.g. a sustain-pedal-free glissando over all 128 pitches): every held pitch previews; nothing is dropped silently.+- Recording starts while keys are already held: they are recorded and previewed from where they actually started (FR-012), not from the record start.+- A note played and released entirely within the count-in (a pickup): recorded and shown at its real position before the record start (FR-012).+- Notes played before pressing Record while the transport was already rolling and released before the start: not recorded (only keys still held at the start are captured).+- Playback loops in the arrangement while a key is held: the preview behaves like the stored note does in the same situation.+- Track-addressed notes (Nota Remote) for a different track than the take's: no preview, matching what is recorded.+- The take or its track is scrolled out of view: no drawing work for it; when scrolled back the held notes are right.+- Recording stopped by the punch/record length or count-in ending: no preview note outlives the recording.+- Idle (stopped, nothing held, no animation): the app repaints no more than it does today.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: While recording MIDI, every key currently held that will be recorded into the take MUST be visible in the take, drawn from its start beat to the current playhead.+- **FR-002**: A held note MUST appear no later than the next UI playhead refresh after the key is pressed.+- **FR-003**: On release, the drawn note MUST end at the release position, and the stored note MUST replace the preview with no visible jump, gap or duplicate.+- **FR-004**: The preview MUST cover live input (computer keyboard, MIDI controllers, Nota Remote addressed to the take's track) and routed MIDI ("MIDI In") capture, in arrangement recording and Session slot recording.+- **FR-005**: In Session slot recording, a held note crossing the slot's loop end MUST be drawn the way it will be stored when released.+- **FR-006**: The preview MUST show in the arrangement take, in the Session slot being recorded, and in the piano roll when it shows the clip being recorded into.+- **FR-007**: The preview MUST show exactly the notes the engine will record — no preview for notes that will not be recorded, and no preview left after recording stops.+- **FR-008**: A newly appearing note MUST play a single appear animation (fade-in with a brief accent flash) lasting 120–200 ms; growth and release MUST NOT re-trigger it.+- **FR-009**: Reading the held notes MUST NOT allocate, lock or do I/O on the audio thread, and MUST NOT affect recorded timing.+- **FR-010**: The app MUST NOT repaint more while idle than it does today; extra repainting is allowed only while notes are held or an animation is running, and SHOULD be limited to the take's area rather than the whole track surface.+- **FR-011**: The engine MUST expose the held captured notes (pitch, start beat, velocity) through the public engine interface so any front-end can draw them, and this read MUST be covered by the engine smoke test.+- **FR-012**: Notes played before the record start MUST be recorded into the take and previewed at the position where they actually started sounding — never moved to the record start. This covers keys still held when recording starts (pressed during the count-in, or before Record was pressed while the transport was rolling) and every note started during the count-in, including ones released before the record start.+- **FR-013**: When an early note (FR-012) starts before the take's clip, the clip's left edge MUST move back to that note's start so the whole note is inside the clip and sounds on playback. The clip never starts before the song start (1.1); a note starting earlier keeps its head stored before the clip's left edge, the part inside the clip sounds from the clip start, and the head reappears and sounds once the clip's left edge is extended (after moving the clip right, if it sits at 1.1).++### Key Entities++- **Held recorded note**: a note whose key is down during recording and that will be written into the take on release — pitch, start beat (in the take's timeline; loop-relative for Session slots), velocity, and which take it belongs to. Exists only while held.+- **Recording take**: the clip (arrangement) or slot (Session) being recorded into; owns the held notes' position on screen. An arrangement take's start can move left during recording to include early notes (FR-013).++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: A pressed key shows as a note in the take within 50 ms of the press at the default refresh rate (plus audio buffer latency), in 100% of presses in a 2-minute test take.+- **SC-002**: After release, the drawn note and the stored note match in start, length and pitch to within one screen pixel at the current zoom, for every note in the test take.+- **SC-003**: Recording a 2-minute take with continuous playing causes no new audio dropouts compared with the same take recorded before the change.+- **SC-004**: With the transport stopped and nothing held, the app's repaint rate and CPU use are unchanged from before the change.+- **SC-005**: While holding notes during recording, UI CPU use stays within 10% of recording audio with its live waveform today.+- **SC-006**: Every new note visibly animates in once; no note keeps animating longer than 200 ms.++## Assumptions++- The animation is always on; no Preferences toggle is added. It respects the Studio design language: the accent (orange) flash fades to the track's normal note colour.+- Velocity is carried in the held-note data for parity with stored notes and possible velocity shading; the preview draws notes the same way the take draws stored notes.+- Recorded MPE expression curves are not drawn during the hold; they attach to the note on release as today.+- The existing ~30 Hz playhead tick drives the growth and animation; a faster rate is used only if the animation looks choppy in practice (decided in the plan).+- The audio take's live waveform path is the model for how the take region is redrawn during recording; the plan confirms whether the MIDI preview can share it.+- Apart from early notes (FR-012, FR-013), what gets recorded and when is unchanged; the rest of the feature is display only.+- Session slots have a fixed loop and no timeline before their start, so an early note recorded into a slot starts at the slot's start (as today); FR-013's clip extension applies to arrangement takes.++## 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)+- [ ] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [ ] 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/017-live-midi-record-notes/tasks.md b/specs/017-live-midi-record-notes/tasks.mdnew file mode 100644index 00000000..34b586a8--- /dev/null+++ b/specs/017-live-midi-record-notes/tasks.md@@ -0,0 +1,283 @@+---++description: "Task list for live MIDI notes while recording (#56)"+---++# Tasks: Live MIDI notes while recording++**Input**: Design documents from `/specs/017-live-midi-record-notes/`++**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 constitution (IV) and FR-011 require smoke coverage for the engine changes and the new C ABI read. Visual checks use the headless capture recipe in quickstart.md.++**Organization**: Tasks are grouped by user story so each one can be implemented and tested on its own.++## Format: `[ID] [P?] [Story] Description`++- **[P]**: Can run in parallel (different files, no dependencies)+- **[Story]**: Which user story this task belongs to (US1–US4)++## Path Conventions++- Engine: `src/native/nota.engine/src/`, C ABI `src/native/nota.engine/include/nota/nota_engine.h`+- Managed: `src/managed/Nota.Application/`, `src/managed/Nota.Infrastructure/`, `src/managed/Nota.App/`+- Smoke tests: `tests/Nota.SmokeTest/`++---++## Phase 1: Setup++**Purpose**: Test scaffolding the stories add to++- [X] T001 Create `tests/Nota.SmokeTest/LiveRecordTests.cs` with the two-line AGPL SPDX header, a `static class LiveRecordTests` exposing `IEnumerable<(bool, string)> Run()` and a `Render(NotaEngine, int blocks)` helper modelled on `MpeTests.Recording` (`tests/Nota.SmokeTest/MpeTests.cs:184`). Register it in `tests/Nota.SmokeTest/Program.cs` the same way `MpeTests` is registered++---++## Phase 2: Foundational (Blocking Prerequisites)++**Purpose**: The held-note snapshot, its C ABI read and the UI plumbing that every story draws from++**⚠️ CRITICAL**: No user story work can begin until this phase is complete++- [X] T002 In `src/native/nota.engine/src/Engine.h`:+ - add the snapshot state: `std::atomic<uint32_t> heldSeq_`, `std::atomic<int32_t> heldTrack_`, `heldScene_` and `heldCount_`, `std::atomic<double> heldNow_`, and 256 slots of relaxed atomics (pitch, source, startBeat, velocity);+ - add a private `publishHeldSnapshot(double nowBeat)` and a public `int32_t recordHeldNotes(NotaRecordHeldNote* out, int32_t maxN, int32_t* trackId, int32_t* scene, double* nowBeat) const`.++ Rules: "count 0..256", "live (128) + routed (128)", "seq odd while writing; readers retry on odd or changed" (data-model.md § Held-note snapshot).+- [X] T003 Implement `publishHeldSnapshot` in `src/native/nota.engine/src/Engine_Render.cpp`:+ - bump the seq to odd, write the compacted entries from `pendingActive_`/`pendingStart_`/`pendingVel_` (source 0) and `recRoutedActive_`/`recRoutedStart_`/`recRoutedVel_` (source 1), then the track id (`recordTrackRt_`, or `recordSessionTrackId_` for slot takes), the scene (`recordSessionScene_`, else −1), the count and `nowBeat`, then bump the seq to even;+ - with no MIDI take, write count 0 and track 0;+ - call it once at the end of `processBlock`, after capture.++ No allocation or locks (AR-6).+- [X] T004 Implement `Engine::recordHeldNotes` in `src/native/nota.engine/src/Engine_Recording.cpp` (next to `liveHeldNotes`, `:196`):+ - read with up to 4 retries on an odd or changed seq, else return 0;+ - `out == NULL` or `maxN <= 0` returns the count without copying (contracts/c-abi.md § Guarantees).+- [X] T005 Add `NotaRecordHeldNote` and `nota_engine_record_held_notes` to `src/native/nota.engine/include/nota/nota_engine.h` after `nota_engine_audio_record_peaks`, exactly as in contracts/c-abi.md. Add the shim to `src/native/nota.engine/src/nota_engine_track.cpp` next to `nota_engine_live_held_notes` (`:654`)+- [X] T006 [P] Add the managed mapping:+ - the `[StructLayout(LayoutKind.Sequential)] NotaRecordHeldNote` struct (int pitch, int source, double startBeat, float velocity) and the P/Invoke `RecordHeldNotes` in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs`;+ - the wrapper in `src/managed/Nota.Infrastructure/Interop/NotaEngine.cs`;+ - `int RecordHeldNotes(NotaRecordHeldNote[] buffer, out int trackId, out int sessionScene, out double nowBeat)` in `src/managed/Nota.Application/Engine/IAudioEngine.cs`, implemented by every `IAudioEngine` implementation and test stub (search for `AudioRecordPeaks` implementations).+- [X] T007 Create `src/managed/Nota.App/RecordPreview.cs` (SPDX header): one instance owned by `MainWindow`.+ - `Update(IAudioEngine)` reads the snapshot once into a reused 256-entry buffer and exposes `TrackId`, `SessionScene`, `NowBeat` and `ReadOnlySpan<NotaRecordHeldNote> Held`;+ - `Clear()` empties it.++ No per-tick allocation.+- [X] T008 Wire `RecordPreview` in `src/managed/Nota.App/MainWindow.axaml.cs:318`:+ - call `_recordPreview.Update(Engine)` at the start of the `RecordingTick` handler, before `Timeline.Refresh(rebuildHeaders: false)`;+ - clear it when recording stops (the first tick where `Engine.IsRecording` is false, from `PlayheadUpdated`) and refresh once;+ - pass the instance to `ArrangementView`, `SessionView` and the piano-roll creation sites (`MainWindow.Detail.cs:430`, `:615`).+- [X] T009 Smoke tests in `tests/Nota.SmokeTest/LiveRecordTests.cs`, using a 120 BPM, armed built-in instrument track, recording:+ - after `TrackNoteOn(t, 60, 0.8f)` and rendering, the read returns pitch 60, source 0 and the take's track id;+ - `start_beat` equals the note-on beat;+ - `now_beat` increases across renders;+ - `out == null` returns the count;+ - with no take, the read returns 0 and track 0.++**Checkpoint**: The engine publishes held notes and the UI receives them every recording tick++---++## Phase 3: User Story 1 — See held notes grow in the arrangement (Priority: P1) 🎯 MVP++**Goal**: Held notes appear on key-down and grow with the playhead in the arrangement take. On release, the stored note replaces them without a jump. Notes from the count-in and keys held across Record are kept at their real start, and the clip grows left to include them (FR-001–FR-003, FR-007, FR-012, FR-013).++**Independent Test**: Record in the arrangement, hold a key for several beats, release, and compare with the stored note. Repeat with a pickup on the count-in, and with a take at 1.1 and a key pressed one beat early (quickstart.md §1–2).++### Tests for User Story 1++- [X] T010 [P] [US1] Smoke tests in `tests/Nota.SmokeTest/LiveRecordTests.cs`:+ - (a) note-off removes the pitch from the next read, and after `Poll` the clip has the note with the same start, length and pitch (contracts/c-abi.md: never seen twice or missing);+ - (b) `SetRecording(false)` with a key held empties the snapshot and stores nothing for that key.+- [X] T011 [P] [US1] Smoke tests in `tests/Nota.SmokeTest/LiveRecordTests.cs`, using `SetCountIn(1)` with Record from stop at bar 5 (beat 16):+ - (a) a note on during the count-in's last beat and off before beat 16 is stored at beat 15, the take's clip starts at 15, and an offline render has energy at beat 15;+ - (b) from 1.1, a key pressed 1 beat before 1.1 and held to beat 2 gives clip start 0 and the note's `startBeat ≈ −1`, length ≈ 3, and the render sounds the note from 0;+ - (c) with the transport rolling and a key down at beat 3, Record at beat 4 and release at beat 6 store the note from beat 3.++### Implementation for User Story 1++- [X] T012 [US1] Add a capture clock in `src/native/nota.engine/src/Engine_Render.cpp` / `Engine.h`. `captureBeat(blockStartBeat)` returns:+ - the block start beat while rolling;+ - `takeStartBeat − (countInTotal_ − countInPos_)` while `countInActive_`, where `takeStartBeat` is the transport playhead beat (it does not move during the count-in).++ Source of truth: research R2 and data-model.md § Capture clock. In `drainLiveMidi` (`:413`), capture when `rec && (playing || countInActive_)` instead of `rec && playing` (`:459`), and use the clock for `nowBeat` when no Session slot is active.+- [X] T013 [US1] Seed held keys at the record edge in `src/native/nota.engine/src/Engine_Render.cpp` / `Engine.h` (research R3):+ - add audio-thread arrays `liveDown_[128]`, `livePressBeat_[128]`, `livePressVel_[128]` and `livePressTrack_[128]`, updated on every live note-on/off in `drainLiveMidi`, whether or not recording;+ - set `livePressBeat_` from the capture clock when rolling or in a count-in, else mark it "pressed while stopped";+ - on the `rec != prevRecording_` rising edge (`:417`), seed `pendingActive_`/`pendingStart_`/`pendingVel_` from keys still down whose track matches (`livePressTrack_ < 0 || == recordTrackRt_`);+ - start beat: the press beat if pressed while rolling; the count-in's first beat (`takeStartBeat − countInTotal_`) if pressed while stopped and a count-in starts; else the take start beat;+ - on the falling edge, clear as today.+- [X] T014 [US1] Move the clip's left edge in `Engine::poll` in `src/native/nota.engine/src/Engine_Render.cpp` (`:276–292`), arrangement branch (research R4):+ - before appending each `RecordedNote`, if `r.startBeat < clip.startBeat`, set `newStart = max(0.0, r.startBeat)` and `delta = clip.startBeat − newStart`;+ - shift every existing note's `startBeat += delta`, then `clip.lengthBeats += delta` and `clip.startBeat = newStart`;+ - then compute `n.startBeat = r.startBeat − clip.startBeat`, which may stay negative only when `r.startBeat < 0`.++ Keep `republishWithTrackRaw`, with no new undo step.+- [X] T015 [US1] Negative-start render rule: a note with `startBeat < 0` and `startBeat + lengthBeats > 0` sounds from the clip start with length `startBeat + lengthBeats`. Notes with `startBeat ≥ lengthBeats` stay skipped (data-model.md § Stored early note). Apply it at:+ - `src/native/nota.engine/src/Engine_Render.cpp:524` (computeBlockMidi);+ - `:749` and `:765` (the session/expression paths; read each site and keep its semantics otherwise);+ - `src/native/nota.engine/src/Engine_Tracks.cpp:1807`.++ The expression lookup for such a note starts at beat offset `−startBeat`.+- [X] T016 [US1] Draw held notes in the arrangement take in `src/managed/Nota.App/ArrangementView.LaneControl.cs`, after the clip loop and near the audio take block (`:1349`):+ - for the row whose track id equals `RecordPreview.TrackId` with `SessionScene < 0`, and only if visible, draw each held note from `BeatToX(startBeat)` to `BeatToX(max(startBeat, NowBeat))`, at least 2 px wide;+ - use the pitch mapping of the take's clip (`DrawClipBody`'s pitch range), extended to include held pitches, and the track's note colour;+ - when the earliest held start is before the clip start, draw a faint take extension box from it to the clip start first (contracts/ui-preview.md § Arrangement take).++ Allocate no new geometry when `Held` is empty.++**Checkpoint**: US1 works: held notes grow, early notes are kept, and the smoke tests pass++---++## Phase 4: User Story 2 — Short appear animation (Priority: P2)++**Goal**: Each new note fades in from the accent colour once, over 150 ms (FR-008, SC-006)++**Independent Test**: Record staccato notes and a held note; each animates once and none re-animates on growth or release (quickstart.md §2.3)++- [X] T017 [US2] Add the appear tracker to `src/managed/Nota.App/RecordPreview.cs` (research R7, data-model.md § Appear-animation entry):+ - a `Dictionary<(int pitch, long startKey), long firstSeenTicks>` keyed by pitch and `Math.Round(startBeat * 1e6)` (absolute beat for the arrangement, slot-local for Session);+ - `Update` adds held notes not yet present, and adds notes newly present in the take's stored notes (compare against the previous tick's key set; the caller passes the take clip's notes in absolute beats) that were never seen held;+ - drop entries older than 150 ms;+ - `double Progress(int pitch, double startBeat)` returns 1 when the note is absent.++ Reuse collections; no per-tick allocation in steady state.+- [X] T018 [US2] Apply the animation when drawing held and stored take notes in `src/managed/Nota.App/ArrangementView.LaneControl.cs`. For notes with `Progress < 1`:+ - draw separately from the batched `StreamGeometry` with opacity `0.35 + 0.65·e(p)`;+ - fill = blend(accent, note colour, e(p)), with ease-out `e(p) = 1 − (1 − p)²`;+ - take the accent from the theme tokens via the `nota-design` skill and never hard-code it.++ Notes at `Progress == 1` stay in the batched geometry.+- [X] T019 [US2] Visual check with the headless harness (quickstart.md §2): a stub `IAudioEngine.RecordHeldNotes`, the take shot at progress 0, 0.5 and 1 in Studio Dark and Studio Light. Keep the harness in /tmp, not in the repo. If 30 Hz looks stepped in the app, add the animation-only 60 Hz timer in `src/managed/Nota.App/MainWindow.axaml.cs`; it runs only while an entry is younger than 150 ms (contracts/ui-preview.md § Repaint rules)++**Checkpoint**: US1 + US2: notes grow and animate in++---++## Phase 5: User Story 3 — Held notes in the piano roll (Priority: P2)++**Goal**: The piano roll showing the take's clip draws held notes growing (FR-006)++**Independent Test**: Open the record clip in the piano roll, record, hold a key; the note grows on the grid. With another clip open, nothing is drawn (spec US3)++- [X] T020 [US3] In `src/managed/Nota.App/PianoRollView.cs`, add a held-note overlay:+ - a `RecordPreview` reference plus the take's clip start beat and a flag "this roll shows the record clip", set from `MainWindow.Detail.cs` when `_editorTrackId == RecordPreview.TrackId` and `_editorClipIndex` is the take clip;+ - draw on the grid control after the notes: x from `startBeat − clipStart` to `NowBeat − clipStart`, at the note's pitch row;+ - it is not hit-testable, not selectable and not part of `SetNotes`;+ - apply the `Progress` animation as in T018;+ - notes left of beat 0 are clipped at the left edge unless the roll shows negative beats.+- [X] T021 [US3] In `src/managed/Nota.App/MainWindow.Detail.cs` (`ReloadEditorNotes`, `:500`), find the take clip with `Engine.TryGetClipInfo` (its start may move left during recording, T014), pass the current clip start to the roll each recording tick, and invalidate the overlay. Clear the flag when recording stops++**Checkpoint**: The piano roll mirrors the arrangement preview++---++## Phase 6: User Story 4 — Routed MIDI and Session slots (Priority: P3)++**Goal**: The same preview for "MIDI In" capture and Session slot takes, including loop wrap (FR-004, FR-005)++**Independent Test**: (a) Record a track fed by routed MIDI and hold a note on the source. (b) Record into a Session slot and hold a note across the loop end (quickstart.md §1 table, §2.6)++### Tests for User Story 4++- [X] T022 [P] [US4] Smoke tests in `tests/Nota.SmokeTest/LiveRecordTests.cs`:+ - (a) a destination armed with `midiFromTrackId` set to a source track; a note held on the source shows in the read with `source = 1`, and on release is stored once;+ - (b) Session slot recording (`nota_session_record_slot`) with a key held: the read gives `session_scene` equal to the scene and a slot-local `start_beat` (0 ≤ start < slot length);+ - (c) N/A: a Session slot take launches without a count-in (`launchSlot`), so no pickup can precede it (research R5).++### Implementation for User Story 4++- [X] T023 [US4] In `src/native/nota.engine/src/Engine_Render.cpp`, `captureRoutedNotes` (`:495`) and its gate (`:682`), capture when `playing || countInActive_`, using the capture clock (T012) instead of `(blockStart + off) / spb` during the count-in. Routed notes already populate `recRoutedActive_`, so they enter the snapshot through T003+- [X] T024 [US4] Draw held notes in the recording Session slot in `src/managed/Nota.App/SessionView.Grid.cs`, near the take drawing at `:569`:+ - when `RecordPreview.SessionScene` equals the slot's scene and `TrackId` its track, draw notes at `x = startBeat / slotLen`;+ - draw a note whose `NowBeat < startBeat` (wrapped) as two pieces: start → slot end, and 0 → `NowBeat`;+ - use the slot's mini-note pitch mapping and the `Progress` animation (contracts/ui-preview.md § Session slot).++**Checkpoint**: All stories work++---++## Phase 7: Polish & Cross-Cutting Concerns++- [ ] T025 Performance check (quickstart.md §3):+ - stopped and idle, the repaint rate and CPU are unchanged versus `develop`;+ - over a 2-minute continuous MIDI take, `XrunCount` stays at 0 and UI CPU is within 10% of an audio take of equal length.++ Record the numbers in the PR description.+- [ ] T026 Run quickstart.md §2 end-to-end in the app or the UI verify harness, including the 1.1 head-reveal (move the clip right one bar, extend its left edge, and hear the pickup)+- [X] T027 [P] `CHANGELOG.md` `[Unreleased]`, Added: held notes show and grow while recording MIDI, with an appear animation. Changed: notes played on the count-in and keys held when recording starts are now recorded at their real position (#56)+- [X] T028 [P] Update FEATURES.md via the `nota-features` skill (live MIDI recording preview; count-in pickups recorded)+- [X] T029 [P] Update the user docs via the `nota-docs` skill: the recording page (EN + RU) gets live notes and count-in pickups, with a re-shot screenshot of a take with growing notes+- [X] T030 Shortcuts via `nota-shortcuts`: N/A, no bindings change++### Nota closing tasks *(PR gates)*++- [X] T031 Run `scripts/build.sh` until native, managed and the smoke test (including `LiveRecordTests`) are green+- [X] T032 AGPL-3.0-only two-line SPDX header on the new files (`tests/Nota.SmokeTest/LiveRecordTests.cs`, `src/managed/Nota.App/RecordPreview.cs`)+- [X] T033 New dependency: N/A (none added)+- [X] T034 Engine behaviour change is covered by `tests/Nota.SmokeTest/LiveRecordTests.cs` (T009, T010, T011, T022)++---++## Dependencies & Execution Order++### Phase Dependencies++- **Setup (T001)** → **Foundational (T002–T009)** → user stories → **Polish**.+- In Foundational, T002 → T003 → T004 → T005 → T006, then T007 → T008. T009 needs T005 and T006.++### User Story Dependencies++- **US1 (P1)**: after Foundational. T012 → T013 (the seeding uses the clock); T014 and T015 can follow in either order; T016 needs T007 and T008.+- **US2 (P2)**: needs US1's arrangement drawing (T016) to animate it. T017 → T018 → T019.+- **US3 (P2)**: after Foundational, independent of US1's engine work for live input. T020 → T021. It shares the `Progress` API from T017; without US2 it draws unanimated.+- **US4 (P3)**: T023 needs T012 (the capture clock). T024 needs T007.++### Parallel Opportunities++- T006 (managed interop) runs alongside T007 once T005's signature is fixed.+- The test tasks T010, T011 and T022 can be written together because they are independent sections of one new file. Merge them carefully.+- After Foundational: engine work (T012–T015, T023) and UI work (T016, T020, T024) touch different files and can run in parallel.+- T027, T028 and T029 are independent.++---++## Parallel Example: User Story 1++```bash+# Engine and UI halves of US1 side by side:+Task: "T012–T015 capture clock, seeding, clip left move, negative-start render in src/native/nota.engine/src/"+Task: "T016 draw held notes in src/managed/Nota.App/ArrangementView.LaneControl.cs"+# Tests together:+Task: "T010 + T011 in tests/Nota.SmokeTest/LiveRecordTests.cs"+```++---++## Implementation Strategy++### MVP First (User Story 1 Only)++1. T001, then T002–T009.+2. T010–T016. Then run `scripts/build.sh` and quickstart §2 steps 1–4 without the animation.+3. Stop and validate: held notes grow and early notes are kept.++### Incremental Delivery++1. Add US2 (animation), then US3 (piano roll), then US4 (routed and Session), validating each at its checkpoint.+2. Finish with Polish and the closing gates.++---++## Notes++- Keep every audio-thread change allocation-free and lock-free (AR-6). The snapshot writer never waits.+- Don't commit. The user reviews and commits (project memory).++## Phase 8: Convergence++- [X] T035 Return no held notes (track 0) from `Engine::recordHeldNotes` in `src/native/nota.engine/src/Engine_Recording.cpp` while an audio take records into a Session slot (`recordSessionAudio_`), and publish nothing for it in `publishHeldSnapshot` — today `recordTrackId_` from an earlier MIDI take is never reset, so live keys played during a Session audio take preview on that stale arrangement track; cover it in `tests/Nota.SmokeTest/LiveRecordTests.cs` per FR-007 (contradicts)+- [X] T036 Seed routed-MIDI notes still held on the source when recording starts (`recRoutedActive_` from the source's held notes, start at their press beat or the take's first moment) in `src/native/nota.engine/src/Engine_Render.cpp`, as research R3 plans for routed input, with a smoke check in `tests/Nota.SmokeTest/LiveRecordTests.cs` per FR-012 / plan: research R3 (partial)+- [X] T037 Review the Session recording cell drawing the slot's already-stored notes in `src/managed/Nota.App/SessionView.Grid.cs` (`DrawRecordingNotes`) — contracts/ui-preview.md only asks for the held notes there; keep it (and note it in the contract) or draw held notes only per FR-006 (unrequested)diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex c4e40c50..f72c9d6f 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -1328,6 +1328,11 @@ public sealed partial class ArrangementView// One pitch scale for the whole track, so a clip an octave up reads higher// than its neighbour instead of every clip auto-fitting to its own notes.var pitches = TrackPitchRange(_o._tracks[i].Clips);+ // The recording take's row (#56): the scale includes the keys being held, so a+ // stored note doesn't jump when the held one lands; new notes animate in.+ var rp = _o.RecordPreview;+ bool take = rp is { Active: true, SessionScene: < 0 } && rp.TrackId == tid;+ if (take) pitches = WithHeld(pitches, rp!.Held);// A track still being filled by a background import reads as translucent.using (ctx.PushOpacity(_o.IsProcessingTrack(tid) ? 0.5 : 1.0))foreach (var c in _o._tracks[i].Clips)@@ -1337,8 +1342,10 @@ public sealed partial class ArrangementViewvar edgeHi = Drag.None;if (_hoverEdge != Drag.None && _hoverEdgeTrack == tid && _hoverEdgeClip == c.ClipIndex) edgeHi = _hoverEdge;else if ((_drag == Drag.TrimL || _drag == Drag.TrimR) && _dragTrackId == tid && _dragClipIndex == c.ClipIndex) edgeHi = _drag;- DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, _o.IsSelected(tid, c.ClipIndex), edgeHi, pitches, tid, i);+ DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, _o.IsSelected(tid, c.ClipIndex), edgeHi, pitches, tid, i,+ take ? rp : null);}+ if (take) DrawHeldNotes(ctx, rp!, _o._tracks[i].ColorIndex, y, rh, w, pitches);// Imports still decoding: a translucent placeholder whose waveform fills in.using (ctx.PushOpacity(0.5))foreach (var c in _o.PendingClipsFor(tid))@@ -1484,7 +1491,62 @@ public sealed partial class ArrangementViewreturn lo <= hi ? (lo, hi) : null;}- private void DrawNotes(DrawingContext ctx, ClipVM c, Rect r, IBrush brush, (int lo, int hi)? pitches = null)+ // A track's pitch range widened to the keys held into its recording take.+ private static (int lo, int hi)? WithHeld((int lo, int hi)? range, ReadOnlySpan<NotaRecordHeldNote> held)+ {+ if (held.IsEmpty) return range;+ int lo = range?.lo ?? int.MaxValue, hi = range?.hi ?? int.MinValue;+ foreach (var h in held) { lo = Math.Min(lo, h.Pitch); hi = Math.Max(hi, h.Pitch); }+ return (lo, hi);+ }++ // A note settling in (#56): the accent fading into the note's own ink, ease-out.+ private static IBrush AppearBrush(IBrush ink, double p)+ => RecordPreview.AppearBrush((ink as ISolidColorBrush)?.Color ?? NotaPalette.Accent.Color, p);++ // Notes still animating in, drawn one by one after the clip's batched geometry.+ private readonly List<(Rect r, double p)> _appearing = new();++ // The recording take's held notes (#56): from where each key went down to the capture+ // clock, on the take row's content area and pitch scale. Keys held since before the+ // take's clip (the count-in) sit on a faint extension of the take, not on bare lane.+ private void DrawHeldNotes(DrawingContext ctx, RecordPreview rp, int colorIndex, double y, double rowH,+ double w, (int lo, int hi)? pitches)+ {+ var held = rp.Held;+ if (held.IsEmpty || pitches is not { } pr) return;+ var content = new Rect(0, y + 2 + BandH, w, Math.Max(0, rowH - 4 - BandH));+ if (content.Height <= 0) return;+ double first = double.MaxValue;+ foreach (var h in held) first = Math.Min(first, h.StartBeat);+ double clipStart = rp.TakeClipIndex >= 0 ? rp.TakeClipStart : rp.NowBeat;+ if (first < clipStart)+ {+ double ex0 = _o.BeatToX(first), ex1 = _o.BeatToX(clipStart);+ var (_, _, _, body) = ClipColors(colorIndex);+ using (ctx.PushClip(new Rect(0, y + 2, w, Math.Max(0, rowH - 4))))+ using (ctx.PushOpacity(0.45))+ ctx.DrawRectangle(body, null, new Rect(ex0, y + 2, Math.Max(2, ex1 - ex0), rowH - 4), NotaRadius.ClipValue, NotaRadius.ClipValue);+ }+ // Under the take's title band, as the stored notes are (the band covers them there).+ double top = y + 2 + (rowH - 4 > TitleBandH * 2.5 ? TitleBandH : BandH);+ using var _ = ctx.PushClip(new Rect(0, top, w, Math.Max(0, y + rowH - 2 - top)));+ int span = Math.Max(1, pr.hi - pr.lo + 1);+ double step = Math.Min(content.Height / span, 4), noteH = Math.Max(1, step);+ var ink = ClipInk(colorIndex);+ foreach (var h in held)+ {+ double x0 = _o.BeatToX(h.StartBeat), x1 = _o.BeatToX(Math.Max(h.StartBeat, rp.NowBeat));+ if (x1 < 0 || x0 > w) continue;+ double ny = Math.Max(content.Y, content.Bottom - (h.Pitch - pr.lo + 1) * step);+ var nr = new Rect(x0, ny, Math.Max(2, x1 - x0), noteH);+ double p = rp.Progress(h.Pitch, h.StartBeat);+ ctx.FillRectangle(p < 1 ? AppearBrush(ink, p) : ink, nr);+ }+ }++ private void DrawNotes(DrawingContext ctx, ClipVM c, Rect r, IBrush brush, (int lo, int hi)? pitches = null,+ RecordPreview? appear = null){if (c.Notes is null || c.Notes.Length == 0 || c.LengthBeats <= 0 || r.Height <= 0) return;// Auto-range to the pitches actually present on the track (all its clips share@@ -1505,9 +1567,14 @@ public sealed partial class ArrangementViewdouble nw = Math.Max(2, (n.LengthBeats / c.LengthBeats) * r.Width);double ny = Math.Max(r.Y, r.Bottom - (n.Pitch - lo + 1) * step);double ww = Math.Min(nw, r.Right - nx);- if (ww > 0) AddRect(g, nx, ny, ww, noteH);+ if (ww <= 0) continue;+ double p = appear?.Progress(n.Pitch, c.StartBeat + n.StartBeat) ?? 1;+ if (p < 1) _appearing.Add((new Rect(nx, ny, ww, noteH), p));+ else AddRect(g, nx, ny, ww, noteH);}ctx.DrawGeometry(brush, null, geo);+ foreach (var (ar, p) in _appearing) ctx.FillRectangle(AppearBrush(brush, p), ar);+ _appearing.Clear();}// Scratch buffer for live capture peaks — reused each frame (no per-render alloc).@@ -1578,7 +1645,7 @@ public sealed partial class ArrangementViewprivate void DrawClipBody(DrawingContext ctx, int colorIndex, string label, ClipVM c, double y,double rowH, bool selected, Drag edgeHi = Drag.None, (int lo, int hi)? pitches = null,- int trackId = -1, int row = -1)+ int trackId = -1, int row = -1, RecordPreview? appear = null){double w = Bounds.Width;double x0 = _o.BeatToX(c.StartBeat);@@ -1602,7 +1669,7 @@ public sealed partial class ArrangementView// height. Content first, then the band and the name over it. Both DrawNotes and// DrawWaveform already clip themselves to the rect they are handed.var contentRect = new Rect(rect.X, rect.Y + BandH, rect.Width, Math.Max(0, rect.Height - BandH));- if (c.IsMidi) DrawNotes(ctx, c, contentRect, content, pitches);+ if (c.IsMidi) DrawNotes(ctx, c, contentRect, content, pitches, appear);else DrawWaveform(ctx, c, contentRect, content);// The title band: the track colour mixed 30% toward black across the top, thediff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex c24aa458..7eeda67e 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -771,6 +771,10 @@ public sealed partial class ArrangementView : UserControl/// <paramref name="rebuildHeaders"/>=false to refresh only the clip data + lane drawing/// (used during recording, so the header controls — the input combobox — and any open/// context menu survive the 60 Hz tick instead of being torn down each frame).</summary>+ /// <summary>The recording MIDI take's held notes and appear animation (#56), drawn on the+ /// take's row. Owned and updated by the window on its recording tick.</summary>+ internal RecordPreview? RecordPreview { get; set; }+public void Refresh(bool rebuildHeaders = true){if (rebuildHeaders) RefreshStarting?.Invoke();diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.csindex fc1ecfd5..3133d721 100644--- a/src/managed/Nota.App/MainWindow.Detail.cs+++ b/src/managed/Nota.App/MainWindow.Detail.cs@@ -501,8 +501,13 @@ public partial class MainWindow{_patternView?.Reload(); // the step grid is a second view of the same notesif (_vm is null || _editorRoll is null || _editorTrackId < 0) return;- double len = Engine.TryGetClipInfo(_editorTrackId, _editorClipIndex, out var ci) && ci.LengthBeats > 0 ? ci.LengthBeats : _editorRoll.LengthBeats;+ bool hasInfo = Engine.TryGetClipInfo(_editorTrackId, _editorClipIndex, out var ci);+ double len = hasInfo && ci.LengthBeats > 0 ? ci.LengthBeats : _editorRoll.LengthBeats;_editorRoll.SetNotes(Engine.GetClipNotes(_editorTrackId, _editorClipIndex), len);+ // The roll shows the recording take: draw its held notes too (#56).+ bool take = _recordPreview is { Active: true, SessionScene: < 0 } rp+ && rp.TrackId == _editorTrackId && rp.TakeClipIndex == _editorClipIndex;+ _editorRoll.SetRecordTake(take ? _recordPreview : null, hasInfo ? ci.StartBeat : 0);}// Tab (when the detail panel was last used) flips between Devices and Clip.diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 0d1fd6bd..b2045e98 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -44,6 +44,7 @@ public partial class MainWindow : Windowprivate IAudioExporter _exporter = default!;private SessionView? _session;+ private readonly RecordPreview _recordPreview = new(); // held notes of a recording MIDI take (#56)private MeterBar? _masterMeter;private MidiLearnService? _learn;/// <summary>The MIDI-learn service, so secondary windows can host their own learn glass.</summary>@@ -315,7 +316,23 @@ public partial class MainWindow : Window// Recording tick fires ~60 Hz: refresh clip data + lane drawing only, WITHOUT// rebuilding the header cards — otherwise the input combobox and any open track/// clip context menu are torn down every frame and can't be used while recording.- vm.RecordingTick += () => { Timeline.Refresh(rebuildHeaders: false); ReloadEditorNotes(); };+ // The live-recording preview (#56) reads the held notes first, so the lanes, the piano+ // roll and the Session slot all draw the same frame of the growing take.+ Timeline.RecordPreview = _recordPreview;+ vm.RecordingTick += () =>+ {+ _recordPreview.Update(vm.Engine);+ Timeline.Refresh(rebuildHeaders: false);+ ReloadEditorNotes();+ };+ // The take ended: drop the preview and redraw once so no growing note lingers.+ vm.PlayheadUpdated += _ =>+ {+ if (!_recordPreview.Active || vm.Engine.IsRecording) return;+ _recordPreview.Clear();+ Timeline.Refresh(rebuildHeaders: false);+ ReloadEditorNotes();+ };// Hit Record with nothing armed → auto-arm the selected/last track (M-fix).vm.Transport.RecordArmTarget = () => Timeline.RecordArmTarget();vm.Transport.SelectionLoopRange = () => Timeline.SelectionLoopRange();@@ -366,6 +383,7 @@ public partial class MainWindow : WindowGetMasterVolume = () => (float)vm.Transport.MasterVolume,SetMasterVolume = v => vm.Transport.MasterVolume = v,GetTempo = () => ((double)vm.Transport.Bpm, vm.Transport.TimeSigNumerator, vm.Transport.TimeSigDenominator),+ RecordPreview = _recordPreview,};_session.SlotEditRequested += OpenSessionClipEditor;_session.ItemDropped += OnSessionDrop; // browser drag & drop (M7-5)diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex 64afb4e4..a7aaae55 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -35,6 +35,20 @@ public sealed partial class PianoRollView : UserControl/// <summary>Polls the engine for currently-pressed live-input pitches (keyboard + MIDI) into/// the buffer, returning the count — used to light up the played key. Set by the host.</summary>public Func<int[], int>? PollHeldNotes { get; set; }++ // The recording take shown in this roll (#56): its held notes grow on the grid and new+ // notes settle in. Null when the roll shows any other clip.+ private RecordPreview? _recPreview;+ private double _recClipStart;+ /// <summary>Show (or, with null, hide) the recording take's held notes; clipStart is the+ /// take clip's timeline start — it moves left while early notes land.</summary>+ internal void SetRecordTake(RecordPreview? preview, double clipStart)+ {+ if (preview is null && _recPreview is null) return;+ _recPreview = preview;+ _recClipStart = clipStart;+ _gridControl.InvalidateVisual();+ }/// <summary>A note's recorded MPE by <see cref="NotaNote.ExprId"/>, drawn over the note./// Curves never change under an id, so they are fetched once. Set by the host.</summary>public Func<int, NotaExprPoint[]>? ExpressionOf { get; set; }@@ -1143,7 +1157,10 @@ public sealed partial class PianoRollView : UserControl// (or all of it, when it goes) reads faint behind a dashed track-colour edge.var fate = _o._placementPending && _o._selection.Count > 0? NoteOverwrite.Fate(i, notes, _o.PlacedForRender()) : default;- if (fate.Kind == NoteFateKind.Kept)+ double appear = _o._recPreview?.Progress(n.Pitch, _o._recClipStart + n.StartBeat) ?? 1;+ if (fate.Kind == NoteFateKind.Kept && appear < 1)+ ctx.FillRectangle(RecordPreview.AppearBrush(c, appear), r, 2);+ else if (fate.Kind == NoteFateKind.Kept)ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a), c.R, c.G, c.B)), r, 2);else{@@ -1172,6 +1189,21 @@ public sealed partial class PianoRollView : UserControlforeach (var d in _doomed) ctx.DrawRectangle(null, pen, d.Deflate(0.5), 2, 2);_doomed.Clear();}+ // Keys held into the recording take (#56): from the key-down to the capture clock,+ // not editable — they become ordinary notes when released.+ if (_o._recPreview is { } rp)+ foreach (var hn in rp.Held)+ {+ if (hn.Pitch < MinPitch || hn.Pitch > MaxPitch) continue;+ double s = hn.StartBeat - _o._recClipStart, e = Math.Max(hn.StartBeat, rp.NowBeat) - _o._recClipStart;+ double hx = BeatToX(s), hw = Math.Max(3, (e - s) * ppb);+ if (hx + hw < 0 || hx > w) continue;+ var c = _o._trackColor;+ double p = rp.Progress(hn.Pitch, hn.StartBeat);+ var hr = new Rect(hx, PitchToY(hn.Pitch), Math.Max(2, hw - 1), RowH - 1);+ ctx.FillRectangle(p < 1 ? RecordPreview.AppearBrush(c, p)+ : new SolidColorBrush(Color.FromArgb((byte)(255 * (0.45 + 0.55 * Math.Clamp(hn.Velocity, 0, 1))), c.R, c.G, c.B)), hr, 2);+ }_o.DrawOutsideClip(ctx, w, h);if (_o._playheadBeat >= 0){diff --git a/src/managed/Nota.App/RecordPreview.cs b/src/managed/Nota.App/RecordPreview.csnew file mode 100644index 00000000..48ed541f--- /dev/null+++ b/src/managed/Nota.App/RecordPreview.cs@@ -0,0 +1,138 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// RecordPreview — what a MIDI take looks like while it records (#56, specs/017): the notes+// held into it (read from the engine once per recording tick, so the arrangement, the Session+// grid and the piano roll draw the same frame) and the appear animation each new note plays.++using System;+using System.Collections.Generic;+using System.Diagnostics;+using Nota.Application;++namespace Nota.App;++internal sealed class RecordPreview+{+ /// <summary>How long a new note takes to settle from the accent into its own colour.</summary>+ public const double AppearMs = 150;++ private readonly NotaRecordHeldNote[] _buf = new NotaRecordHeldNote[256];+ private int _count;+ // Appear animation: when each take note was first seen (held, or newly stored), keyed by+ // pitch + start (absolute beat for an arrangement take, slot-local for Session).+ private readonly Dictionary<(int pitch, long start), long> _appear = new();+ private readonly List<(int, long)> _expired = new();+ // Every take note seen so far — held or stored — so a note animates once: not again when+ // its key is still down after the animation, nor when it lands in the clip on release.+ // A note pressed and released between two ticks (never held in a snapshot) is first seen+ // stored, and animates then. The take's notes from before the first tick don't animate.+ private readonly HashSet<(int, long)> _seen = new();+ private bool _primed;++ public int TrackId { get; private set; }+ /// <summary>Session scene being recorded, or -1 for an arrangement take.</summary>+ public int SessionScene { get; private set; } = -1;+ /// <summary>The capture clock: the held notes' right edge (runs through the count-in).</summary>+ public double NowBeat { get; private set; }+ /// <summary>The arrangement take's clip (-1 when unknown or a Session take) and its start.</summary>+ public int TakeClipIndex { get; private set; } = -1;+ public double TakeClipStart { get; private set; }+ public bool Active => TrackId > 0;+ public ReadOnlySpan<NotaRecordHeldNote> Held => _buf.AsSpan(0, _count);+ /// <summary>True while any note is still animating (drives the optional fast repaint).</summary>+ public bool Animating => _appear.Count > 0;++ public static long Key(double beat) => (long)Math.Round(beat * 1e4);++ /// <summary>Read the engine's held notes and advance the appear animation. Call once per+ /// recording tick, after Engine.Poll (so a released note is already in its clip).</summary>+ public void Update(IAudioEngine eng)+ {+ int n = eng.RecordHeldNotes(_buf, out int track, out int scene, out double now);+ if (track != TrackId || scene != SessionScene) { _primed = false; _seen.Clear(); _appear.Clear(); }+ _count = Math.Clamp(n, 0, _buf.Length);+ TrackId = track;+ SessionScene = scene;+ NowBeat = now;+ if (track <= 0) { Clear(); return; }++ long t = Stopwatch.GetTimestamp();+ for (int i = 0; i < _count; i++)+ {+ var k = (_buf[i].Pitch, Key(_buf[i].StartBeat));+ if (_seen.Add(k)) _appear[k] = t; // a key down is always new to the take+ }++ // The take's stored notes: ones never seen before (staccato between two ticks) animate.+ TakeClipIndex = -1;+ if (scene >= 0)+ {+ foreach (var x in eng.GetSessionNotes(track, scene)) Saw((x.Pitch, Key(x.StartBeat)), t);+ }+ else+ {+ // The take is the clip under the capture clock — or, during the count-in, the+ // first clip after it (the one the take opened at the record start).+ double bestStart = double.MaxValue;+ for (int c = 0; c < 4096 && eng.TryGetClipInfo(track, c, out var ci); c++)+ {+ if (!ci.IsMidi) continue;+ if (now >= ci.StartBeat && now < ci.StartBeat + ci.LengthBeats) { TakeClipIndex = c; TakeClipStart = ci.StartBeat; break; }+ if (ci.StartBeat > now && ci.StartBeat < bestStart) { bestStart = ci.StartBeat; TakeClipIndex = c; TakeClipStart = ci.StartBeat; }+ }+ if (TakeClipIndex >= 0)+ foreach (var x in eng.GetClipNotes(track, TakeClipIndex))+ Saw((x.Pitch, Key(TakeClipStart + x.StartBeat)), t);+ }+ _primed = true;++ Expire(t);+ }++ private void Saw((int, long) key, long t)+ {+ if (_seen.Add(key) && _primed) _appear[key] = t;+ }++ public void Clear()+ {+ _count = 0;+ TrackId = 0;+ SessionScene = -1;+ TakeClipIndex = -1;+ _appear.Clear();+ _seen.Clear();+ _primed = false;+ }++ /// <summary>Appear progress of a take note, 0 → 1 (1 = settled, or not a new note).</summary>+ public double Progress(int pitch, double startBeat)+ {+ if (_appear.Count == 0 || !_appear.TryGetValue((pitch, Key(startBeat)), out long t0)) return 1;+ double ms = Stopwatch.GetElapsedTime(t0).TotalMilliseconds;+ return Math.Clamp(ms / AppearMs, 0, 1);+ }++ /// <summary>Ease-out of a progress value: fast start, soft landing.</summary>+ public static double Ease(double p) => 1 - (1 - p) * (1 - p);++ /// <summary>A settling note's fill: the accent fading into the note's own ink (and from+ /// translucent to opaque) as the appear animation runs.</summary>+ public static Avalonia.Media.IBrush AppearBrush(Avalonia.Media.Color ink, double p)+ {+ double e = Ease(p);+ var a = NotaPalette.Accent.Color;+ byte L(byte x, byte y) => (byte)Math.Round(x + (y - x) * e);+ return new Avalonia.Media.Immutable.ImmutableSolidColorBrush(+ Avalonia.Media.Color.FromRgb(L(a.R, ink.R), L(a.G, ink.G), L(a.B, ink.B)), 0.35 + 0.65 * e);+ }++ private void Expire(long now)+ {+ _expired.Clear();+ foreach (var (k, t0) in _appear)+ if (Stopwatch.GetElapsedTime(t0, now).TotalMilliseconds >= AppearMs) _expired.Add(k);+ foreach (var k in _expired) _appear.Remove(k);+ }+}diff --git a/src/managed/Nota.App/SessionView.Grid.cs b/src/managed/Nota.App/SessionView.Grid.csindex 2795a68e..3212291f 100644--- a/src/managed/Nota.App/SessionView.Grid.cs+++ b/src/managed/Nota.App/SessionView.Grid.cs@@ -26,6 +26,8 @@ public sealed partial class SessionViewprivate readonly HashSet<int> _armed = new();private int _recTrack, _recScene = -1;+ /// <summary>The recording MIDI take's held notes and appear animation (#56).</summary>+ internal RecordPreview? RecordPreview { get; init; }private double _recElapsed;// Clip drag between slots: the cell the pointer is over while a clip is dragged.@@ -569,6 +571,45 @@ public sealed partial class SessionViewint n = _o._engine.AudioRecordPeaks(buf, 44);DrawPeaks(ctx, new Rect(7, 25, r.Width - 14, r.Height - 31), buf, n, NotaPalette.DangerBright);}+ else DrawRecordingNotes(ctx, new Rect(7, 25, r.Width - 14, r.Height - 31));+ }++ // A MIDI slot being recorded (#56): the notes stored so far plus the keys held into it,+ // growing to the slot's clock; a held note that wrapped past the loop end draws as its+ // tail plus the part from the loop start. New notes settle in from the accent.+ private void DrawRecordingNotes(DrawingContext ctx, Rect area)+ {+ var rp = _o.RecordPreview;+ var stored = _o._engine.GetSessionNotes(_c.TrackId, _scene);+ ReadOnlySpan<NotaRecordHeldNote> held = rp is { } p0 && p0.TrackId == _c.TrackId && p0.SessionScene == _scene+ ? p0.Held : ReadOnlySpan<NotaRecordHeldNote>.Empty;+ if ((stored.Length == 0 && held.IsEmpty) || area.Width <= 0 || area.Height <= 3) return;+ double slotLen = _o._engine.SessionSlotLength(_c.TrackId, _scene);+ // An open-ended take shows whole bars recorded so far, not its provisional length.+ double len = Math.Min(slotLen > 0 ? slotLen : 4, Math.Max(4, Math.Ceiling((_o._recElapsed + 1e-6) / 4) * 4));+ int lo = 127, hi = 0;+ foreach (var n in stored) { lo = Math.Min(lo, n.Pitch); hi = Math.Max(hi, n.Pitch); }+ foreach (var h in held) { lo = Math.Min(lo, h.Pitch); hi = Math.Max(hi, h.Pitch); }+ int range = Math.Max(1, hi - lo);+ var ink = NotaPalette.DangerBright;+ using var _ = ctx.PushClip(area);+ void Bar(int pitch, double start, double length, double prog)+ {+ double x = area.X + start / len * area.Width;+ double wd = Math.Max(1.5, Math.Min(length, len - start) / len * area.Width);+ double y = area.Y + (hi - pitch) / (double)range * (area.Height - 3);+ var b = prog < 1 ? RecordPreview.AppearBrush(ink.Color, prog) : ink;+ ctx.DrawRectangle(b, null, new Rect(x, y, wd, 3), 1, 1);+ }+ foreach (var n in stored)+ if (n.StartBeat < len) Bar(n.Pitch, n.StartBeat, n.LengthBeats, rp?.Progress(n.Pitch, n.StartBeat) ?? 1);+ double now = rp?.NowBeat ?? 0;+ foreach (var h in held)+ {+ double prog = rp!.Progress(h.Pitch, h.StartBeat);+ if (now >= h.StartBeat) Bar(h.Pitch, h.StartBeat, now - h.StartBeat, prog);+ else { Bar(h.Pitch, h.StartBeat, len - h.StartBeat, prog); Bar(h.Pitch, 0, now, prog); } // wrapped+ }}}diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 1e2e26e8..952789d8 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -35,6 +35,18 @@ public struct NotaExprPoint(NoteExpressionDim dim, float beat, float value)public float Value = value;}+/// <summary>A note held into the in-progress MIDI take (live-recording preview). Matches native+/// NotaRecordHeldNote. StartBeat is an absolute timeline beat for an arrangement take (it may+/// precede the take's clip and be negative — played on the count-in), slot-local for Session.</summary>+[StructLayout(LayoutKind.Sequential)]+public struct NotaRecordHeldNote+{+ public int Pitch;+ public int Source; // 0 live input, 1 routed MIDI ("MIDI In")+ public double StartBeat;+ public float Velocity;+}+/// <summary>Track summary for the Arrangement View. Matches native NotaTrackInfo.</summary>[StructLayout(LayoutKind.Sequential)]public struct NotaTrackInfodiff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 47e92c08..af4bf649 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -812,6 +812,11 @@ public interface IAudioEngine : IDisposableint MasterTrackId { get; }/// <summary>Live min/max peaks over the in-progress capture buffer (growing-take waveform). Returns buckets written.</summary>int AudioRecordPeaks(float[] outMinMax, int maxPoints);+ /// <summary>Notes held into the in-progress MIDI take, for drawing them growing. Fills+ /// <paramref name="buffer"/> and returns the count (0 when no MIDI take records); trackId is+ /// the take's track (0 = none), sessionScene the Session scene (-1 = arrangement take),+ /// nowBeat the capture clock — the held notes' right edge, running through the count-in.</summary>+ int RecordHeldNotes(NotaRecordHeldNote[] buffer, out int trackId, out int sessionScene, out double nowBeat);void Poll();// --- Undo / redo (M6-6) ------------------------------------------------diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex 61b65d7f..5659516c 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -156,6 +156,10 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_audio_record_peaks")]internal static partial int AudioRecordPeaks(IntPtr engine, [Out] float[] outMinMax, int maxPoints);+ [LibraryImport(Lib, EntryPoint = "nota_engine_record_held_notes")]+ internal static partial int RecordHeldNotes(IntPtr engine, [Out] NotaRecordHeldNote[] outNotes, int maxN,+ out int trackId, out int sessionScene, out double nowBeat);+[LibraryImport(Lib, EntryPoint = "nota_engine_poll")]internal static partial NotaResult Poll(IntPtr engine);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex 18a9c8de..cb4bb3af 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -142,6 +142,8 @@ public sealed partial class NotaEngine : IAudioEnginepublic int MasterTrackId { get { ThrowIfDisposed(); return NativeMethods.MasterTrackId(_handle); } }/// <summary>Live min/max peaks over the in-progress capture buffer (growing-take waveform). Returns buckets written.</summary>public int AudioRecordPeaks(float[] outMinMax, int maxPoints) { ThrowIfDisposed(); return NativeMethods.AudioRecordPeaks(_handle, outMinMax, maxPoints); }+ public int RecordHeldNotes(NotaRecordHeldNote[] buffer, out int trackId, out int sessionScene, out double nowBeat)+ { ThrowIfDisposed(); return NativeMethods.RecordHeldNotes(_handle, buffer, buffer.Length, out trackId, out sessionScene, out nowBeat); }/// <summary>Message-thread pump: materialises recorded notes into clips. Call from the UI timer.</summary>public void Poll() { ThrowIfDisposed(); NativeMethods.Poll(_handle); }diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 2c7f9e56..fa23e51b 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -786,6 +786,26 @@ NOTA_API int32_t nota_engine_master_track_id(const NotaEngine* engine);/* Live min/max peaks (interleaved, out_min_max[2*max_points]) over the in-progress* capture buffer so the take draws a growing waveform. Returns buckets written. */NOTA_API int32_t nota_engine_audio_record_peaks(const NotaEngine* engine, float* out_min_max, int32_t max_points);+/* One note held into the in-progress MIDI take (live-recording preview). */+typedef struct NotaRecordHeldNote {+ int32_t pitch; /* 0..127 */+ int32_t source; /* 0 live input (keyboard, MIDI, Remote), 1 routed MIDI ("MIDI In") */+ double start_beat; /* arrangement: absolute timeline beat, may precede the take's clip+ and be < 0 (played on the count-in before 1.1);+ Session: slot-local beat */+ float velocity; /* 0..1 */+} NotaRecordHeldNote;+/* Notes currently held into the in-progress MIDI take — keys down that will be written+ * into the take on release — for drawing them growing. Copies up to max_n entries and+ * returns the count (0 when no MIDI take is recording or nothing is held; out may be NULL+ * to query it). Optional outputs: *track_id the take's track (0 = none), *session_scene+ * the Session scene being recorded (-1 = arrangement take), *now_beat the capture clock+ * (the held notes' right edge; runs during the count-in too, in start_beat's coordinates).+ * Lock-free; call from the UI thread. */+NOTA_API int32_t nota_engine_record_held_notes(const NotaEngine* engine,+ NotaRecordHeldNote* out, int32_t max_n,+ int32_t* track_id, int32_t* session_scene,+ double* now_beat);/* Message-thread pump: materialises recorded notes into clips and drains engine* events. Call periodically from the UI (e.g. the position timer). */NOTA_API NotaResult nota_engine_poll(NotaEngine* engine);diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex 436b9b2a..a000a23e 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -1001,6 +1001,10 @@ public:// a growing waveform (not just a flat box). 0 when not capturing. UI-thread// only — serialised with poll()'s drain, which is the sole writer.int32_t audioRecordPeaks(float* outMinMax, int32_t maxPoints) const;+ // Notes held into the in-progress MIDI take (live-recording preview, #56). Lock-free+ // read of the audio thread's per-block snapshot; take geometry from the message thread.+ int32_t recordHeldNotes(NotaRecordHeldNote* out, int32_t maxN, int32_t* trackId,+ int32_t* sessionScene, double* nowBeat) const;void pushInputFramesForTest(const float* interleavedStereo, int32_t frames); // feed the ring without a devicebool audioRecordSelfTest(); // ring -> accumulate -> clip, no devicebool sessionAudioRecordSelfTest(); // ring -> slot.audio -> looped playback, no device (M5-4)@@ -1462,8 +1466,42 @@ private:bool recRoutedActive_[128] = {};double recRoutedStart_[128] = {};float recRoutedVel_[128] = {};- void captureRoutedNotes(const MidiEv* evs, int n, double blockStart, double spb);+ void captureRoutedNotes(const MidiEv* evs, int n, double blockStart, double spb, double clockOffset);void captureLiveExpr(double nowBeat, double slotLen); // recorded MPE (drainLiveMidi)+ // Live keys down, tracked whether or not a take records, so keys already held when+ // Record is pressed join the take from where they started (#56). pressBeat is NaN for a+ // key pressed while stopped (no timeline position).+ bool liveDown_[128] = {};+ double livePressBeat_[128] = {};+ float livePressVel_[128] = {};+ int32_t livePressTrack_[128] = {};+ // Routed MIDI ("MIDI In") sounding into an armed destination, tracked whether or not a take+ // records, so notes already held on the source when Record is pressed join the take too.+ // routedOwner_ is the destination the arrays describe.+ bool routedDown_[128] = {};+ double routedPressBeat_[128] = {};+ float routedPressVel_[128] = {};+ int32_t routedOwner_ = -1;+ bool routedSeedPending_ = false; // a take just started: seed after this block's routed events+ void trackRoutedDown(int32_t ownerId, const MidiEv* evs, int n, double blockStart, double spb, bool timed);+ // Capture clock: during a count-in the transport holds still, so notes are timed back+ // from the take start (negative offsets — before 1.1 when the take starts there).+ double countInClockOffset() const { return countInActive_ ? -(countInTotal_ - countInPos_) : 0.0; }+ // Held-note snapshot for the live-recording preview: written once per block by the+ // audio thread behind a sequence counter (odd while writing), read by the UI.+ static constexpr int kMaxHeldSnap = 256; // 128 pitches × live + routed+ struct HeldSnapSlot {+ std::atomic<int32_t> pitch{0};+ std::atomic<int32_t> source{0};+ std::atomic<double> startBeat{0.0};+ std::atomic<float> velocity{0.0f};+ };+ std::atomic<uint32_t> heldSeq_{0};+ std::atomic<int32_t> heldCount_{0};+ std::atomic<double> heldNow_{0.0};+ HeldSnapSlot heldSnap_[kMaxHeldSnap];+ double captureNow_ = 0.0; // capture clock at this block's start (drainLiveMidi)+ void publishHeldSnapshot(double nowBeat);// Clip-note expression replayed per block (computeBlockMidi fills, the render pass merges),// per track position like blockMidi_.diff --git a/src/native/nota.engine/src/Engine_Recording.cpp b/src/native/nota.engine/src/Engine_Recording.cppindex a1b7a893..311fcaf1 100644--- a/src/native/nota.engine/src/Engine_Recording.cpp+++ b/src/native/nota.engine/src/Engine_Recording.cpp@@ -207,6 +207,41 @@ int32_t Engine::liveHeldNotes(int32_t* out, int32_t maxN) const {return n;}+// The live-recording preview (#56): the audio thread's held-note snapshot, retried while a+// block is writing it. Take geometry comes from the message-thread record state (this+// runs on the UI thread, which owns it). A read that keeps racing returns 0 — one+// frame without preview, never a wait.+int32_t Engine::recordHeldNotes(NotaRecordHeldNote* out, int32_t maxN, int32_t* trackId,+ int32_t* sessionScene, double* nowBeat) const {+ // An audio take into a Session slot records no MIDI: recordTrackId_ may still name the+ // last MIDI take's track (it isn't reset on stop), so it must not light up here.+ const bool rec = recording_.load(std::memory_order_relaxed) && !recordSessionAudio_;+ const bool slot = rec && recordSessionScene_ >= 0 && recordSessionTrackId_ > 0;+ const int32_t tid = !rec ? 0 : slot ? recordSessionTrackId_ : (recordTrackId_ > 0 ? recordTrackId_ : 0);+ if (trackId) *trackId = tid;+ if (sessionScene) *sessionScene = slot ? recordSessionScene_ : -1;+ if (nowBeat) *nowBeat = 0.0;+ if (tid <= 0) return 0;+ for (int attempt = 0; attempt < 4; ++attempt) {+ const uint32_t s0 = heldSeq_.load(std::memory_order_acquire);+ if (s0 & 1u) continue;+ const int32_t n = std::clamp(heldCount_.load(std::memory_order_relaxed), 0, kMaxHeldSnap);+ const double now = heldNow_.load(std::memory_order_relaxed);+ const int32_t m = (out && maxN > 0) ? std::min(n, maxN) : 0;+ for (int32_t i = 0; i < m; ++i) {+ out[i].pitch = heldSnap_[i].pitch.load(std::memory_order_relaxed);+ out[i].source = heldSnap_[i].source.load(std::memory_order_relaxed);+ out[i].start_beat = heldSnap_[i].startBeat.load(std::memory_order_relaxed);+ out[i].velocity = heldSnap_[i].velocity.load(std::memory_order_relaxed);+ }+ std::atomic_thread_fence(std::memory_order_acquire);+ if (heldSeq_.load(std::memory_order_relaxed) != s0) continue;+ if (nowBeat) *nowBeat = now;+ return n;+ }+ return 0;+}+void Engine::setRecording(bool on) {// The record button is also the automation-record switch (M9-C): while it is// engaged, moving any control writes that parameter's lane. This is set evendiff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cppindex fed9ae02..8824b787 100644--- a/src/native/nota.engine/src/Engine_Render.cpp+++ b/src/native/nota.engine/src/Engine_Render.cpp@@ -21,6 +21,7 @@#include <chrono>#include <cmath>#include <cstdint>+#include <limits>#if defined(__SSE__) || defined(_M_X64) || defined(_M_IX86)#include <xmmintrin.h>#endif@@ -279,6 +280,19 @@ void Engine::poll() {auto nt = cloneTrack(*t);MidiClip& clip = nt->midiClips[recordClipIndex_];for (auto& r : batch) {+ // A note that began before the take's clip (played on the count-in, or a key held+ // when Record was pressed, #56) moves the clip's left edge back to it, keeping every+ // note where it is. Clips can't start before 1.1, so a note older than that keeps+ // its head before the clip's start (it sounds from the clip start).+ if (r.startBeat < clip.startBeat) {+ const double newStart = std::max(0.0, r.startBeat);+ const double delta = clip.startBeat - newStart;+ if (delta > 0.0) {+ for (auto& o : clip.notes) o.startBeat += delta;+ clip.lengthBeats += delta;+ clip.startBeat = newStart;+ }+ }Note n; n.pitch = r.pitch;n.startBeat = r.startBeat - clip.startBeat;n.lengthBeats = r.lengthBeats > 0.0 ? r.lengthBeats : 0.1;@@ -410,25 +424,56 @@ void Engine::drainCommands() {}}+// The live-recording preview (#56): copy the notes being held into the take (live input,+// then routed MIDI) behind the sequence counter — odd while writing, so a reader that sees an+// odd or changed value retries. Wait-free and fixed-size; an idle engine with an empty snapshot writes nothing.+void Engine::publishHeldSnapshot(double nowBeat) {+ const bool rec = recording_.load(std::memory_order_relaxed);+ if (!rec && heldCount_.load(std::memory_order_relaxed) == 0) return; // idle: already empty+ const uint32_t s = heldSeq_.load(std::memory_order_relaxed);+ heldSeq_.store(s + 1, std::memory_order_relaxed);+ std::atomic_thread_fence(std::memory_order_release);+ int32_t n = 0;+ if (rec) {+ auto put = [&](int32_t pitch, int32_t source, double start, float vel) {+ HeldSnapSlot& h = heldSnap_[n++];+ h.pitch.store(pitch, std::memory_order_relaxed);+ h.source.store(source, std::memory_order_relaxed);+ h.startBeat.store(start, std::memory_order_relaxed);+ h.velocity.store(vel, std::memory_order_relaxed);+ };+ for (int p = 0; p < 128; ++p) if (pendingActive_[p]) put(p, 0, pendingStart_[p], pendingVel_[p]);+ for (int p = 0; p < 128; ++p) if (recRoutedActive_[p]) put(p, 1, recRoutedStart_[p], recRoutedVel_[p]);+ }+ heldCount_.store(n, std::memory_order_relaxed);+ heldNow_.store(nowBeat, std::memory_order_relaxed);+ heldSeq_.store(s + 2, std::memory_order_release);+}+void Engine::drainLiveMidi(double blockStartBeat, bool playing) {liveCount_ = 0;liveExprCount_ = 0;const bool rec = recording_.load(std::memory_order_relaxed);- if (rec != prevRecording_)- for (int i = 0; i < 128; ++i) { pendingActive_[i] = false; recRoutedActive_[i] = false; }- prevRecording_ = rec;// When recording into a Session slot, time notes against the slot's own loop// clock (localBeats holds this block's start position) instead of the global- // transport, so overdubs land at the right spot in the loop.+ // transport, so overdubs land at the right spot in the loop. During a count-in the+ // transport holds still and notes are timed back from the take start (#56).SessionPlayer* slot = recordSlotPlayer_.load(std::memory_order_acquire);const double slotLen = recordSlotLen_.load(std::memory_order_relaxed);+ const bool timed = playing || countInActive_; // the timeline has a position for an eventconst double nowBeat = slot ? (slotLen > 0.0 ? std::fmod(slot->localBeats, slotLen) : slot->localBeats)- : blockStartBeat;+ : blockStartBeat + countInClockOffset();+ captureNow_ = nowBeat;// Track-addressed notes (Nota Remote) are recorded only when they play the take's// track; ordinary live input records onto it whatever it is.const int32_t recTrack = recordTrackRt_.load(std::memory_order_relaxed);+ const bool takeStarted = rec && !prevRecording_;+ routedSeedPending_ = takeStarted && !slot; // routed notes held now join the take (captureRoutedNotes)+ if (rec != prevRecording_)+ for (int i = 0; i < 128; ++i) { pendingActive_[i] = false; recRoutedActive_[i] = false; }+ prevRecording_ = rec;// Every live event plays at offset 0 and the render sorts offs ahead of ons at one// offset, so a pitch's on and off landing in the same block (a quick tap, a finger// sliding over pads, a phone's notes arriving in one Wi-Fi burst) would play@@ -456,7 +501,15 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {}if (valid) seen[e.pitch >> 5] |= bit;liveEvents_[liveCount_++] = e;- if (rec && playing && e.pitch >= 0 && e.pitch < 128 && (e.trackId < 0 || e.trackId == recTrack)) {+ if (valid) { // keys down, recording or not (seeds a take started while they're held)+ liveDown_[e.pitch] = e.on;+ if (e.on) {+ livePressBeat_[e.pitch] = timed ? nowBeat : std::numeric_limits<double>::quiet_NaN();+ livePressVel_[e.pitch] = e.velocity;+ livePressTrack_[e.pitch] = e.trackId;+ }+ }+ if (rec && timed && valid && (e.trackId < 0 || e.trackId == recTrack)) {if (e.on) {pendingActive_[e.pitch] = true;pendingStart_[e.pitch] = nowBeat;@@ -470,7 +523,19 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {}}}- if (rec && playing && liveExprCount_ > 0) captureLiveExpr(nowBeat, slot ? slotLen : 0.0);+ // Keys still down once this block's events are in join a take that starts here, from+ // where they started: their press beat if the transport was rolling (or counting in),+ // else the take's first moment — the count-in's first beat, or the record start. A slot+ // take starts them at the slot's current position. Seeding after the drain keeps out a+ // key whose release was already queued when Record was pressed.+ if (takeStarted)+ for (int p = 0; p < 128; ++p) {+ if (!liveDown_[p] || pendingActive_[p] || (livePressTrack_[p] >= 0 && livePressTrack_[p] != recTrack)) continue;+ pendingActive_[p] = true;+ pendingStart_[p] = (slot || std::isnan(livePressBeat_[p])) ? nowBeat : livePressBeat_[p];+ pendingVel_[p] = livePressVel_[p];+ }+ if (rec && timed && liveExprCount_ > 0) captureLiveExpr(nowBeat, slot ? slotLen : 0.0);}// Recorded MPE: the block's (coalesced) live expression for a note being recorded becomes a@@ -492,11 +557,30 @@ void Engine::captureLiveExpr(double nowBeat, double slotLen) {// Print routed-in MIDI (a source's post-FX note events) into the record track's take, pairing// note-on/off across blocks into RecordedNotes at absolute beats. Audio thread; recorded_ has a// single producer (this + drainLiveMidi both run in processBlock).-void Engine::captureRoutedNotes(const MidiEv* evs, int n, double blockStart, double spb) {+// Keeps the routed notes sounding into an armed destination (on/off pairs from its source's+// post-FX MIDI), timed on the capture clock, for seeding a take started while they're held.+void Engine::trackRoutedDown(int32_t ownerId, const MidiEv* evs, int n, double blockStart, double spb, bool timed) {+ if (routedOwner_ != ownerId) {+ for (int p = 0; p < 128; ++p) routedDown_[p] = false;+ routedOwner_ = ownerId;+ }+ for (int k = 0; k < n; ++k) {+ const int p = evs[k].pitch;+ if (p < 0 || p >= 128) continue;+ routedDown_[p] = evs[k].on;+ if (evs[k].on) {+ routedPressBeat_[p] = timed && spb > 0.0 ? (blockStart + evs[k].off) / spb + countInClockOffset()+ : std::numeric_limits<double>::quiet_NaN();+ routedPressVel_[p] = evs[k].vel;+ }+ }+}++void Engine::captureRoutedNotes(const MidiEv* evs, int n, double blockStart, double spb, double clockOffset) {for (int k = 0; k < n; ++k) {const int p = evs[k].pitch;if (p < 0 || p >= 128) continue;- const double beat = (blockStart + evs[k].off) / spb;+ const double beat = (blockStart + evs[k].off) / spb + clockOffset; // count-in: before the take startif (evs[k].on) {recRoutedActive_[p] = true;recRoutedStart_[p] = beat;@@ -506,6 +590,20 @@ void Engine::captureRoutedNotes(const MidiEv* evs, int n, double blockStart, dourecRoutedActive_[p] = false;}}+ // A take that starts this block takes in the routed notes still sounding after its events:+ // from their press beat if the transport was rolling (or counting in), else from now.+ if (routedSeedPending_) {+ routedSeedPending_ = false;+ const int32_t recTrack = recordTrackRt_.load(std::memory_order_relaxed);+ const double now = blockStart / spb + clockOffset;+ if (routedOwner_ == recTrack)+ for (int p = 0; p < 128; ++p) {+ if (!routedDown_[p] || recRoutedActive_[p]) continue;+ recRoutedActive_[p] = true;+ recRoutedStart_[p] = std::isnan(routedPressBeat_[p]) ? now : routedPressBeat_[p];+ recRoutedVel_[p] = routedPressVel_[p];+ }+ }}// Append a track's own note events (clips while playing + live input when armed/auditioned).@@ -520,12 +618,14 @@ int Engine::gatherInstrumentNotes(Track& t, MidiEv* evs, int n, int32_t frames,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.- if (note.startBeat < 0.0 || note.startBeat >= clip.lengthBeats) continue;- const double onS = clipStart + note.startBeat * spb;+ // 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 = onS + note.lengthBeats * spb;+ 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.@@ -540,7 +640,8 @@ int Engine::gatherInstrumentNotes(Track& t, MidiEv* evs, int n, int32_t frames,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, onS - blockStart, offS - blockStart, frames, spb, xev, *xn, kMaxBlockExpr);+ noteExprEvents(note, clipStart + note.startBeat * spb - blockStart, offS - blockStart,+ frames, spb, xev, *xn, kMaxBlockExpr); // curve timed from the true start}}}@@ -679,7 +780,7 @@ void Engine::renderInstrumentRaw(Graph* g, Track& t, float* dst, int32_t frames,if (g) {const int32_t srcId = t.midiFromTrackId(); // "MIDI In": the track we receive from (-1 = none)// Recording the destination prints the routed MIDI into its take (arm the destination).- const bool captureRouted = srcId >= 0 && t.id() == recordTrackId_ && playing+ const bool captureRouted = srcId >= 0 && t.id() == recordTrackId_ && (playing || countInActive_)&& recording_.load(std::memory_order_relaxed) && spb > 0.0;const size_t nt = std::min(g->tracks.size(), blockMidiN_.size());for (size_t j = 0; j < nt; ++j) {@@ -695,7 +796,8 @@ void Engine::renderInstrumentRaw(Graph* g, Track& t, float* dst, int32_t frames,for (int k = 0; k < m && n < 1024; ++k) evs[n++] = srcEvs[k];if (j < blockExprN_.size())for (int k = 0; k < blockExprN_[j] && xn < kMaxBlockExpr; ++k) xev[xn++] = blockExpr_[j][k];- if (routed && captureRouted) captureRoutedNotes(srcEvs, m, blockStart, spb);+ if (routed && t.armed()) trackRoutedDown(t.id(), srcEvs, m, blockStart, spb, playing || countInActive_);+ if (routed && captureRouted) captureRoutedNotes(srcEvs, m, blockStart, spb, countInClockOffset());}} else {n = computeInstrumentMidi(t, evs, frames, blockStart, spb, playing,@@ -1055,6 +1157,8 @@ void Engine::processBlock(float* out, int32_t numFrames) {}}+ publishHeldSnapshot(captureNow_); // live + routed capture for this block done (#56)+renderTone(out, numFrames);renderPreview(out, numFrames); // audition voice (M7-4a), pre-masterdiff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cppindex 5ab24293..9e6dd718 100644--- a/src/native/nota.engine/src/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/Engine_Tracks.cpp@@ -1804,12 +1804,13 @@ MidiClip consolidateMidiClips(const std::vector<MidiClip>& clips, double s, doubspans.push_back({std::max(cs, s), ce, cs, &c->volumeEnvelope});const bool hasVel = !c->velocityEnvelope.points.empty();for (const Note& n : c->notes) {- if (n.startBeat < 0.0 || n.startBeat >= c->lengthBeats) continue;- const double on = cs + n.startBeat;+ // A note starting before its clip (#56) sounds from the clip start, as in playback.+ if (n.startBeat >= c->lengthBeats || n.startBeat + n.lengthBeats <= 0.0) continue;+ const double on = cs + std::max(0.0, n.startBeat);if (on < s - eps || on >= e - eps) continue;Note m = n;m.startBeat = std::max(0.0, on - s);- m.lengthBeats = std::min(on + n.lengthBeats, ce) - on;+ m.lengthBeats = std::min(cs + n.startBeat + n.lengthBeats, ce) - on;if (m.lengthBeats <= 0.0) continue;if (hasVel) m.velocity = n.velocity * std::clamp(c->velocityEnvelope.valueAt(n.startBeat), 0.0f, 1.0f);out.notes.push_back(m);diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cppindex 3113143a..01f973cf 100644--- a/src/native/nota.engine/src/nota_engine_track.cpp+++ b/src/native/nota.engine/src/nota_engine_track.cpp@@ -653,6 +653,16 @@ NotaResult nota_clip_set_notes_live(NotaEngine* e, int32_t track_id, int32_t cliint32_t nota_engine_live_held_notes(const NotaEngine* e, int32_t* out, int32_t max_n) {return e ? CENG(e)->liveHeldNotes(out, max_n) : 0;}+int32_t nota_engine_record_held_notes(const NotaEngine* e, NotaRecordHeldNote* out, int32_t max_n,+ int32_t* track_id, int32_t* session_scene, double* now_beat) {+ if (!e) {+ if (track_id) *track_id = 0;+ if (session_scene) *session_scene = -1;+ if (now_beat) *now_beat = 0.0;+ return 0;+ }+ return CENG(e)->recordHeldNotes(out, max_n, track_id, session_scene, now_beat);+}int32_t nota_clip_get_notes(const NotaEngine* e, int32_t track_id, int32_t clip_index,NotaNoteData* out, int32_t max_notes) {if (!e || !out || max_notes <= 0) return 0;diff --git a/tests/Nota.SmokeTest/LiveRecordTests.cs b/tests/Nota.SmokeTest/LiveRecordTests.csnew file mode 100644index 00000000..f81092c9--- /dev/null+++ b/tests/Nota.SmokeTest/LiveRecordTests.cs@@ -0,0 +1,364 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Live MIDI recording (#56, specs/017): notes held into a take are readable while held (the+// growing-note preview) and match what is stored on release; notes played on the count-in and+// keys already down when Record is pressed are recorded where they started — the take's clip+// moves its left edge back, and before 1.1 a note keeps its head and sounds from the clip start.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class LiveRecordTests+{+ private const double Sr = 48000.0;+ private const double Spb = Sr * 60.0 / 120.0; // frames per beat at 120 BPM+ private const int Chunk = 256;++ public static IEnumerable<(bool, string)> Run()+ {+ foreach (var r in Snapshot()) yield return r;+ foreach (var r in Release()) yield return r;+ foreach (var r in CountIn()) yield return r;+ foreach (var r in HeldAcrossRecord()) yield return r;+ foreach (var r in Routed()) yield return r;+ foreach (var r in SessionSlot()) yield return r;+ foreach (var r in RoutedHeldAcrossRecord()) yield return r;+ foreach (var r in SessionAudioTake()) yield return r;+ }++ // Render about `beats` beats in small chunks (events are timed per block).+ private static float Beats(NotaEngine e, double beats)+ {+ var b = new float[Chunk * 2];+ int frames = (int)Math.Round(beats * Spb);+ double sq = 0; int n = 0;+ for (int done = 0; done < frames; done += Chunk)+ {+ e.RenderOffline(b, Chunk, Sr);+ foreach (var v in b) { sq += v * (double)v; n++; }+ }+ return n > 0 ? (float)Math.Sqrt(sq / n) : 0f;+ }++ private static NotaEngine Armed(out int track)+ {+ var e = new NotaEngine();+ e.SetBpm(120);+ e.SetMetronome(false);+ track = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(track, 0);+ e.SetTrackArmed(track, true);+ e.StopTransport();+ e.RenderOffline(new float[Chunk * 2], Chunk, Sr);+ return e;+ }++ private static int Held(NotaEngine e, NotaRecordHeldNote[] buf, out int track, out int scene, out double now)+ => e.RecordHeldNotes(buf, out track, out scene, out now);++ private static List<(NotaClipInfo Info, NotaNote[] Notes)> Clips(NotaEngine e, int track)+ {+ var all = new List<(NotaClipInfo, NotaNote[])>();+ for (int c = 0; c < 64 && e.TryGetClipInfo(track, c, out var ci); c++) all.Add((ci, e.GetClipNotes(track, c)));+ return all;+ }++ private static bool Near(double a, double b, double tol = 0.05) => Math.Abs(a - b) <= tol;++ // A held note is readable while held: the take's track, its pitch and start, a clock that runs.+ private static IEnumerable<(bool, string)> Snapshot()+ {+ using var e = Armed(out int t);+ var buf = new NotaRecordHeldNote[256];+ yield return (Held(e, buf, out int t0, out int s0, out _) == 0 && t0 == 0 && s0 == -1,+ "held notes: nothing to read while not recording");+ e.SetCountIn(0);+ e.SetRecording(true);+ Beats(e, 1.0);+ e.NoteOn(60, 0.8f);+ double pressed = e.PositionBeats;+ Beats(e, 0.5);+ int n = Held(e, buf, out int tr, out int sc, out double now1);+ yield return (n == 1 && buf[0].Pitch == 60 && buf[0].Source == 0 && tr == t && sc == -1,+ $"held notes: a held key reads back on the take's track (n={n}, pitch={(n > 0 ? buf[0].Pitch : -1)}, track={tr}/{t})");+ yield return (n == 1 && Near(buf[0].StartBeat, pressed) && Math.Abs(buf[0].Velocity - 0.8f) < 1e-3,+ $"held notes: the start is the note-on beat ({(n > 0 ? buf[0].StartBeat : -1):F3} vs {pressed:F3})");+ Beats(e, 1.0);+ Held(e, buf, out _, out _, out double now2);+ yield return (now2 > now1 + 0.9 && now1 > pressed, $"held notes: the clock runs with the playhead ({now1:F2} → {now2:F2})");+ yield return (e.RecordHeldNotes(Array.Empty<NotaRecordHeldNote>(), out _, out _, out _) == 1,+ "held notes: an empty buffer still returns the count");+ e.NoteOff(60);+ e.SetRecording(false);+ }++ // On release the note leaves the held set and is stored as it was drawn; stopping with a key+ // down stores nothing for it.+ private static IEnumerable<(bool, string)> Release()+ {+ using var e = Armed(out int t);+ var buf = new NotaRecordHeldNote[256];+ e.SetCountIn(0);+ e.SetRecording(true);+ Beats(e, 0.5);+ e.NoteOn(64, 0.7f);+ Beats(e, 1.5);+ Held(e, buf, out _, out _, out _);+ double heldStart = buf[0].StartBeat;+ e.NoteOff(64);+ double released = e.PositionBeats;+ Beats(e, 0.1);+ int n = Held(e, buf, out _, out _, out _);+ e.Poll();+ var stored = Clips(e, t).SelectMany(c => c.Notes.Select(x => (c.Info.StartBeat + x.StartBeat, x))).Where(p => p.x.Pitch == 64).ToList();+ yield return (n == 0, "release: the note leaves the held set");+ yield return (stored.Count == 1 && Near(stored[0].Item1, heldStart, 1e-6) && Near(stored[0].Item1 + stored[0].x.LengthBeats, released),+ $"release: stored once, from the held start to the release (n={stored.Count})");++ e.NoteOn(67, 0.7f);+ Beats(e, 0.5);+ e.SetRecording(false);+ Beats(e, 0.1);+ e.Poll();+ int after = Held(e, buf, out int tr, out _, out _);+ bool none67 = !Clips(e, t).Any(c => c.Notes.Any(x => x.Pitch == 67));+ yield return (after == 0 && tr == 0 && none67, "release: stopping with a key down leaves no held note and stores none");+ e.NoteOff(67);+ }++ // Notes on the count-in: a pickup before bar 5 is stored before it and the clip moves back+ // to it; a take at 1.1 keeps the head before the clip and sounds the rest from 1.1.+ private static IEnumerable<(bool, string)> CountIn()+ {+ var buf = new NotaRecordHeldNote[256];+ using (var e = Armed(out int t))+ {+ e.Seek(16.0);+ Beats(e, 0.01);+ e.SetCountIn(1);+ e.SetRecording(true); // from stop: 1 bar of count-in, then the take at beat 16+ Beats(e, 3.25);+ e.NoteOn(60, 0.8f);+ Beats(e, 0.1);+ int n = Held(e, buf, out _, out _, out double now);+ yield return (n == 1 && Near(buf[0].StartBeat, 15.25) && now < 16.0,+ $"count-in: a pickup reads back before the take start ({(n > 0 ? buf[0].StartBeat : -1):F2}, clock {now:F2})");+ Beats(e, 0.4);+ e.NoteOff(60); // released before bar 5+ Beats(e, 1.0);+ e.Poll();+ e.SetRecording(false);+ e.Poll();+ var clips = Clips(e, t);+ var take = clips.FirstOrDefault(c => c.Notes.Any(x => x.Pitch == 60));+ double abs = take.Notes is null ? -1 : take.Info.StartBeat + take.Notes.First(x => x.Pitch == 60).StartBeat;+ yield return (take.Notes is not null && Near(abs, 15.25) && Near(take.Info.StartBeat, 15.25),+ $"count-in: the pickup is stored where it was played and the clip starts there (note {abs:F2}, clip {(take.Notes is null ? -1 : take.Info.StartBeat):F2})");+ e.StopTransport();+ e.Seek(15.0);+ Beats(e, 0.01);+ e.Play();+ float silent = Beats(e, 0.2), pickup = Beats(e, 0.5);+ yield return (pickup > 1e-3 && pickup > silent * 3, $"count-in: playback sounds the pickup (rms {silent:F4} → {pickup:F4})");+ e.StopTransport();+ }++ using (var e = Armed(out int t))+ {+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetCountIn(1);+ e.SetRecording(true);+ Beats(e, 3.0);+ e.NoteOn(62, 0.8f); // one beat before 1.1+ Beats(e, 3.0); // held into the take, to beat 2+ e.NoteOff(62);+ Beats(e, 0.2);+ e.SetRecording(false);+ e.Poll();+ var take = Clips(e, t).FirstOrDefault(c => c.Notes.Any(x => x.Pitch == 62));+ var note = take.Notes?.First(x => x.Pitch == 62) ?? default;+ yield return (take.Notes is not null && take.Info.StartBeat == 0.0 && Near(note.StartBeat, -1.0) && Near(note.LengthBeats, 3.0),+ $"count-in at 1.1: the clip starts at 1.1, the note keeps its head (start {note.StartBeat:F2}, length {note.LengthBeats:F2})");+ e.StopTransport();+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ float head = Beats(e, 0.5);+ yield return (head > 1e-3, $"count-in at 1.1: the note sounds from the clip start (rms {head:F4})");+ e.StopTransport();+ }+ }++ // Keys already down when Record is pressed join the take: from their press beat while the+ // transport rolls, from the count-in's first beat when pressed while stopped.+ private static IEnumerable<(bool, string)> HeldAcrossRecord()+ {+ using (var e = Armed(out int t))+ {+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 3.0);+ e.NoteOn(65, 0.8f);+ double pressed = e.PositionBeats;+ Beats(e, 1.0);+ e.SetRecording(true); // rolling: no count-in, the take opens at ~beat 4+ Beats(e, 2.0);+ e.NoteOff(65);+ Beats(e, 0.2);+ e.Poll();+ e.SetRecording(false);+ e.Poll();+ var take = Clips(e, t).FirstOrDefault(c => c.Notes.Any(x => x.Pitch == 65));+ double abs = take.Notes is null ? -1 : take.Info.StartBeat + take.Notes.First(x => x.Pitch == 65).StartBeat;+ yield return (take.Notes is not null && Near(abs, pressed) && Near(take.Info.StartBeat, pressed),+ $"held across Record: stored from the press beat ({abs:F2} vs {pressed:F2}), the clip moved back to it");+ e.StopTransport();+ }++ using (var e = Armed(out int t))+ {+ var buf = new NotaRecordHeldNote[256];+ e.Seek(8.0);+ Beats(e, 0.01);+ e.NoteOn(69, 0.8f); // pressed while stopped+ Beats(e, 0.2);+ e.SetCountIn(1);+ e.SetRecording(true);+ Beats(e, 0.2);+ int n = Held(e, buf, out _, out _, out _);+ yield return (n == 1 && buf[0].Pitch == 69 && Near(buf[0].StartBeat, 4.0),+ $"held across Record: a key pressed while stopped starts at the count-in's first beat ({(n > 0 ? buf[0].StartBeat : -1):F2})");+ e.NoteOff(69);+ Beats(e, 0.1);+ e.SetRecording(false);+ }+ }++ // MIDI routed into the armed track ("MIDI In") is held and previewed as source 1.+ private static IEnumerable<(bool, string)> Routed()+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ e.SetMetronome(false);+ int dst = e.AddInstrumentTrack();+ int src = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(dst, 0);+ e.SetTrackBuiltinInstrument(src, 0);+ e.SetTrackMidiSource(dst, src);+ e.SetTrackArmed(dst, true);+ e.StopTransport();+ e.SetCountIn(0);+ e.SetRecording(true);+ Beats(e, 0.5);+ e.TrackNoteOn(src, 71, 0.8f);+ Beats(e, 0.5);+ var buf = new NotaRecordHeldNote[256];+ int n = Held(e, buf, out int tr, out _, out _);+ bool seen = Enumerable.Range(0, Math.Min(n, buf.Length)).Any(i => buf[i].Pitch == 71 && buf[i].Source == 1);+ yield return (seen && tr == dst, $"routed: a note held on the source reads back as routed MIDI (n={n})");+ e.TrackNoteOff(src, 71);+ Beats(e, 0.2);+ e.Poll();+ e.SetRecording(false);+ e.Poll();+ int stored = Clips(e, dst).Sum(c => c.Notes.Count(x => x.Pitch == 71));+ yield return (stored == 1, $"routed: on release it is stored once (n={stored})");+ }++ // A note already sounding on the routed source when Record is pressed joins the take from+ // where it started (convergence T036).+ private static IEnumerable<(bool, string)> RoutedHeldAcrossRecord()+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ e.SetMetronome(false);+ int dst = e.AddInstrumentTrack();+ int src = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(dst, 0);+ e.SetTrackBuiltinInstrument(src, 0);+ e.SetTrackMidiSource(dst, src);+ e.SetTrackArmed(dst, true);+ e.SetCountIn(0);+ e.StopTransport();+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 2.0);+ e.TrackNoteOn(src, 74, 0.8f);+ double pressed = e.PositionBeats;+ Beats(e, 1.0);+ e.SetRecording(true); // rolling: the take opens at ~beat 3, the note is down since ~2+ Beats(e, 1.0);+ e.TrackNoteOff(src, 74);+ Beats(e, 0.2);+ e.Poll();+ e.SetRecording(false);+ e.Poll();+ var take = Clips(e, dst).FirstOrDefault(c => c.Notes.Any(x => x.Pitch == 74));+ double abs = take.Notes is null ? -1 : take.Info.StartBeat + take.Notes.First(x => x.Pitch == 74).StartBeat;+ int count = Clips(e, dst).Sum(c => c.Notes.Count(x => x.Pitch == 74));+ yield return (take.Notes is not null && count == 1 && Near(abs, pressed),+ $"routed held across Record: stored once from the source's press beat ({abs:F2} vs {pressed:F2}, n={count})");+ e.StopTransport();+ }++ // An audio take into a Session slot shows no MIDI held notes, even right after a MIDI take+ // (convergence T035). Needs a capture device; without one the slot can't record audio.+ private static IEnumerable<(bool, string)> SessionAudioTake()+ {+ using var e = Armed(out int t);+ e.SetCountIn(0);+ e.SetRecording(true); // a MIDI take first, so the engine remembers its track+ Beats(e, 0.5);+ e.SetRecording(false);+ e.SetTrackArmed(t, false);+ int a = e.AddAudioTrack();+ e.SetLaunchQuant(0.0);+ e.RecordSessionSlot(a, 0);+ if (!e.IsRecording)+ {+ yield return (true, "session audio take: no MIDI preview (skipped — no capture device here)");+ yield break;+ }+ e.NoteOn(60, 0.8f);+ Beats(e, 0.5);+ int n = e.RecordHeldNotes(new NotaRecordHeldNote[256], out int tr, out _, out _);+ yield return (n == 0 && tr == 0, $"session audio take: no MIDI preview (n={n}, track={tr})");+ e.NoteOff(60);+ Beats(e, 0.1);+ e.StopSessionRecord();+ e.StopAllSession();+ e.StopTransport();+ }++ // A Session slot take reports its scene and slot-local starts.+ private static IEnumerable<(bool, string)> SessionSlot()+ {+ using var e = Armed(out int t);+ e.SetLaunchQuant(0.0);+ e.Seek(0);+ Beats(e, 0.01);+ e.RecordSessionSlot(t, 0);+ Beats(e, 1.5);+ e.NoteOn(72, 0.9f);+ Beats(e, 0.5);+ var buf = new NotaRecordHeldNote[256];+ int n = Held(e, buf, out int tr, out int sc, out double now);+ double len = e.SessionSlotLength(t, 0);+ yield return (n == 1 && tr == t && sc == 0 && buf[0].StartBeat >= 0 && buf[0].StartBeat < Math.Max(len, 1e9) && now >= 0,+ $"session: a held key reads back on the recording slot (n={n}, scene={sc}, start={(n > 0 ? buf[0].StartBeat : -1):F2})");+ e.NoteOff(72);+ Beats(e, 0.2);+ e.Poll();+ e.StopSessionRecord();+ yield return (e.GetSessionNotes(t, 0).Any(x => x.Pitch == 72), "session: the note is stored into the slot on release");+ e.StopAllSession();+ e.StopTransport();+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 9621b577..4c4c80fd 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -360,6 +360,14 @@ if (args.Length >= 1 && args[0] == "--keys")Console.WriteLine(failures == 0 ? "KEYS PASSED" : $"KEYS FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Live MIDI recording alone (fast iteration): `--live-record`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--live-record")+{+ Console.WriteLine("-- live midi recording --");+ foreach (var (ok, label) in LiveRecordTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "LIVE RECORD PASSED" : $"LIVE RECORD FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// MPE alone (fast iteration): `--mpe`. Also part of the full run.if (args.Length >= 1 && args[0] == "--mpe"){@@ -14633,6 +14641,8 @@ Console.WriteLine("-- nota remote --");foreach (var (ok, label) in RemoteTests.Run()) Check(ok, label);Console.WriteLine("-- mpe: per-note expression --");foreach (var (ok, label) in MpeTests.Run()) Check(ok, label);+Console.WriteLine("-- live midi recording --");+foreach (var (ok, label) in LiveRecordTests.Run()) Check(ok, label);Console.WriteLine("-- nota keys --");foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);Console.WriteLine("-- nota mosaic --");