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) Take lanes and comping for audio loop recording (#187) (#403)
Chris Laupama2f49e3de3990
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7143ec4c..fe711a6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,17 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Take lanes for audio loop recording** (#187): an Arrangement audio recording that comes+ back around the loop keeps every pass as a take (Take 1, Take 2, …) instead of overwriting+ the earlier ones. The comp — what plays, on the track's own row — starts as the newest pass+ at every point, which is what audio loop recording used to leave. The track header shows a+ disclosure and the take count; the lanes start folded, and opening them draws one row per+ take with its waveform and the sections the comp uses highlighted. Drag across a take to+ use that section (the arrangement snap grid, ⌥ / Alt to bypass); right-click a lane for+ **Use whole take**, **Delete take** (the sound stays) or **Flatten takes** (one clip, the+ takes of that recording go). Each of those is one undo step, and takes are saved with the+ project. A tempo change moves the comp's sections with their takes, so they still meet+ sample to sample. One pass, the loop off, MIDI and Session slots are unchanged.- **Sample rate and buffer size in the status bar** (#373): the lower right corner now reads"48 kHz · 256". Click it to pick another buffer size — Device default or 64 to 2048 frames,each with its latency — or to open Settings → Audio. Playback carries on across the change.diff --git a/FEATURES.md b/FEATURES.mdindex 4fbc61b7..e361acdd 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -499,6 +499,14 @@ docks as a panel under any of the three, or floats in its own window — see- **Recording** from an input (microphone, line, interface) onto an audio track, withmonitoring (in/auto/off). The input is **Ext 1** or **Ext 2** (mono, centred) or **Ext 1/2**(stereo pair); new tracks take Ext 1. MCP `set_input_channels`.+- **Take lanes**: an Arrangement audio recording with the loop on keeps every pass. The+ header shows a disclosure and the take count; open it for one row per take (**Take 1**,+ **Take 2**, …), folded until you do. What plays is the comp, the track's own row — after+ recording, the newest pass at every point. Drag across a take to use that section (the+ snap grid; ⌥ bypasses it). Right-click a lane for **Use whole take**, **Delete take**+ (what plays stays) or **Flatten takes** (the comp becomes one clip and those takes go).+ Each is one undo step. Takes are saved with the project. One pass, the loop off, MIDI+ and Session slots stay a single clip.- **Audio clips as samples** — drag an arrangement clip onto a track with a Sampler, NotaGrain, Drum Rack (next free pad) or Instrument Rack, or anywhere a sample goes (a pad, aRhythm voice, a Session slot); hovering an instrument track opens its devices. The samplediff --git a/specs/067-take-lanes-comping/checklists/requirements.md b/specs/067-take-lanes-comping/checklists/requirements.mdnew file mode 100644index 00000000..47a309cc--- /dev/null+++ b/specs/067-take-lanes-comping/checklists/requirements.md@@ -0,0 +1,35 @@+# Specification Quality Checklist: Take lanes and comping++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-31+**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++- The seven scope questions were answered by the maintainer on 2026-10-31 (spec § Clarifications).+- Crossfades at comp boundaries were not asked about; the spec assumes none in this version and points at #286.diff --git a/specs/067-take-lanes-comping/contracts/c-abi.md b/specs/067-take-lanes-comping/contracts/c-abi.mdnew file mode 100644index 00000000..a2052790--- /dev/null+++ b/specs/067-take-lanes-comping/contracts/c-abi.md@@ -0,0 +1,43 @@+# C ABI: take lanes (specs/067)++All functions are message-thread only.++```c+typedef struct NotaTakeInfo {+ int32_t id; /* engine-unique; comp clips carry it */+ int32_t number; /* "Take N" on its track */+ int32_t group; /* the loop recording it came from */+ int32_t reserved;+ double origin_beat; /* timeline beat of the take audio's frame 0 */+ double start_beat; /* recorded range on the timeline (current tempo) */+ double length_beats;+ double source_offset_frames; /* recorded range inside the take audio */+ int64_t length_frames;+ int64_t sample_id; /* the take audio (nota_sample_read) */+} NotaTakeInfo;++int32_t nota_track_take_count(const NotaEngine*, int32_t track_id);+int32_t nota_track_take_info(const NotaEngine*, int32_t track_id, int32_t index, NotaTakeInfo* out); /* 1/0 */+int32_t nota_track_take_peaks(const NotaEngine*, int32_t track_id, int32_t index,+ float* out_min_max, int32_t max_points); /* buckets written */+/* Comp: the take plays over [start_beat, end_beat) (clamped to its range). One undo step. */+NotaResult nota_track_take_comp(NotaEngine*, int32_t track_id, int32_t take_id, double start_beat, double end_beat);+/* Delete a take; its comp sections keep playing. One undo step. */+NotaResult nota_track_take_delete(NotaEngine*, int32_t track_id, int32_t take_id);+/* Flatten every recording's takes on the track into one clip each. One undo step. */+NotaResult nota_track_takes_flatten(NotaEngine*, int32_t track_id);+/* The take a clip plays (0 = none). */+int32_t nota_clip_take_id(const NotaEngine*, int32_t track_id, int32_t clip_index);++/* Project load (no undo entry). restore returns the new take id or -1; set_take_id tags a+ * restored clip and shares the take's audio with it when they match. */+int32_t nota_track_restore_take(NotaEngine*, int32_t track_id, const char* path_utf8, int32_t number,+ int32_t group, double origin_beat, double source_offset_frames,+ int64_t length_frames);+NotaResult nota_clip_set_take_id(NotaEngine*, int32_t track_id, int32_t clip_index, int32_t take_id);++/* Smoke-test hook: record `frames` of interleaved stereo into track_id as a loop take started at+ * start_beat, through the real capture path (ring → drain → stop), without a device. 1 = ok. */+int32_t nota_take_record_test(NotaEngine*, int32_t track_id, const float* interleaved_stereo,+ int32_t frames, double start_beat);+```diff --git a/specs/067-take-lanes-comping/data-model.md b/specs/067-take-lanes-comping/data-model.mdnew file mode 100644index 00000000..0a3a03a8--- /dev/null+++ b/specs/067-take-lanes-comping/data-model.md@@ -0,0 +1,44 @@+# Data model: Take lanes and comping++## Engine (`Track.h`)++```cpp+struct AudioTake {+ std::shared_ptr<SampleBuffer> sample; // loop-length buffer; frame 0 = originBeat+ int32_t id = 0; // engine-unique; comp clips name it+ int32_t number = 0; // "Take N" on its track, recording order+ int32_t group = 0; // the loop recording it came from (flatten works per group)+ double originBeat = 0.0; // timeline beat of sample frame 0 (the loop start)+ double sourceOffsetFrames = 0.0; // the range the pass recorded…+ int64_t lengthFrames = 0; // …inside the buffer+};+// Track: std::vector<AudioTake> takes; (recording order)+// AudioClip: int32_t takeId = 0; (0 = not a comp section)+```++Timeline range of a take: `[originBeat + offset·bpf, originBeat + (offset+length)·bpf)` with+`bpf = deviceRate / sampleRate / samplesPerBeat` (the same mapping recorded clips use).++Rules:++- A comp section of take *t*: `sample == t.sample`, `startBeat == originBeat + sourceOffsetFrames·bpf`, `takeId == t.id`.+- Deleting *t* clears `takeId` on its sections (they keep playing).+- Flatten (per group) merges sections that are still aligned, active, unwarped, unreversed,+ unpitched and without envelopes/ADSR into one clip over a new buffer; the rest stay as+ untagged clips; the group's takes are removed.++## Project file (format v29)++```json+"tracks": [{+ "audioClips": [{ "sample": "samples/<hash>.wav", "startBeat": 0, "takeId": 7, … }],+ "takes": [{ "id": 7, "number": 3, "group": 1, "sample": "samples/<hash>.wav",+ "originBeat": 0, "sourceOffsetFrames": 0, "lengthFrames": 96000 }]+}]+```++`takes` and `takeId` are omitted when empty / 0. Older files have neither and load unchanged.++## View state (not saved)++- `ArrangementView._takesOpen`: track ids whose take lanes are open (folded by default).diff --git a/specs/067-take-lanes-comping/plan.md b/specs/067-take-lanes-comping/plan.mdnew file mode 100644index 00000000..17b60220--- /dev/null+++ b/specs/067-take-lanes-comping/plan.md@@ -0,0 +1,143 @@+# Implementation Plan: Take lanes and comping (audio loop recording)++**Branch**: `cursor/take-lanes-comping-3af4` | **Date**: 2026-10-31 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `/specs/067-take-lanes-comping/spec.md`++## Summary++Audio loop recording keeps every pass as a **take** on the track instead of overwriting the+loop-region buffer in place. Takes are structural track data in the engine graph (so undo/redo+come from the snapshot history, AR-5). The **comp** is the track's ordinary clips: a comp section+is a clip that plays a slice of a take's sample and carries that take's id. Comping a range,+deleting a take and flattening are message-thread graph edits, one undo step each. The audio+thread plays nothing new — only ordinary clips — so the render path is untouched. The managed+side saves takes in the bundle (format v29), and the arrangement draws foldable take lanes under+the track and turns a horizontal drag on a lane into a comp edit.++## Nota: Read Before Planning++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-5 (takes live on the+ immutable `Track` snapshot, every edit republishes), AR-6 (pass buffers are copied by the+ message-thread drain, never the audio thread), AR-7 (new `nota_track_take_*` C functions).+- **UI work** → [`DESIGN.md`](../../DESIGN.md): take lanes reuse the lane palette, the track+ colour for in-use sections, the group disclosure chevron for open/close.++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 (managed app)++**Primary Dependencies**: none new++**Storage**: `.nota` bundle — `project.json` gains `takes` per track and `takeId` per audio clip+(format v29); take audio is content-addressed in `samples/` like clip audio (shared with the+comp sections that use it).++**Audio-Thread Impact**: None. The capture ring and its drain are unchanged; the drain (message+thread, `drainInputQueue`) copies a completed pass when the loop cursor wraps. Comp sections are+ordinary `AudioClip`s; no per-block take logic.++**Testing**: `tests/Nota.SmokeTest/TakeLaneTests.cs` drives a device-free multi-pass loop take+through a new test entry point (`nota_take_record_test`) and checks takes, the default comp+(sample-exact against today's single-buffer result), comp/undo/redo, delete, flatten+(sample-exact) and save/reopen.++**Target Platform**: macOS, Windows, Linux (no platform code)++**Project Type**: desktop app++**Performance Goals**: no change to render cost; one extra loop-length buffer copy per pass on+the message thread.++**Constraints**: AR-5/6/7; takes must not change the result of recordings that make one pass.++**Scale/Scope**: tens of takes per track; a loop of minutes.++## Constitution Check++- I. Real-time safety — pass. No audio-thread change; allocations happen in the message-thread drain and graph edits.+- II. Boundary discipline — pass. Plain C functions and one POD struct (`NotaTakeInfo`).+- III. Licensing — pass. New files carry the SPDX header; no dependency.+- IV. Verification gate — pass. Smoke test extended (engine behaviour change).+- V. One logical change — pass. One feature (#187).+- VI. Docs in sync — CHANGELOG, FEATURES.md, user manual page (nota-docs), no new shortcut.+- VII. Spec first — this spec + plan + tasks.+- VIII. — n/a.++## Design++### Engine (`src/native/nota.engine`)++- `Track.h`: `struct AudioTake { sample, id, number, group, originBeat, sourceOffsetFrames,+ lengthFrames }`, `std::vector<AudioTake> takes` on `Track`; `int32_t takeId` on `AudioClip`+ (0 = not from a take). `cloneTrack` copies `takes`.+- `Engine_Recording.cpp`: loop punch keeps a list of completed passes. When the write cursor+ wraps, the pass `[passFrom, loopFrames)` is copied into a zeroed loop-length buffer. On stop,+ the open pass `[passFrom, reached)` is added; with two or more passes the take path runs:+ every pass becomes a take (new group, numbers continuing on the track) and the default comp is+ built newest-first (each frame from the latest pass that recorded it) as integer-frame clips+ tagged with their take id, carving the loop region exactly as today. One pass → today's path.+- `Engine_Takes.cpp` (new): `takeCount/takeInfo/takePeaks`, `compTake` (clamp the beat range to+ the take, round to whole frames, carve, add the section), `deleteTake` (clips keep playing,+ their take id is cleared), `flattenTakes` (per group: aligned plain sections are summed into+ one new buffer → one clip; others keep playing untagged; the group's takes go),+ `restoreTake`/`setClipTakeId` (load; the latter re-points a matching clip at the take's buffer+ so a reopened comp shares its audio), and `takeRecordTest` (device-free multi-pass take).+- `findSampleById` also searches takes (project save registers their audio).++### C ABI — see [contracts/c-abi.md](contracts/c-abi.md)++### Managed++- `EngineContracts.cs`: `NotaTakeInfo`. `IAudioEngine` + `NotaEngine.Takes.cs` + `NativeMethods`.+- Persistence: `TrackDto.Takes` (`AudioTakeDto`), `AudioClipDto.TakeId`; save registers each+ take's sample; load restores takes first (old id → new id map), then the clips, then tags+ them. Format v29 (additive, no migration).+- Arrangement (`ArrangementView.Takes.cs`, new): open/closed set (view state), take lane height,+ geometry (`RowHeightAt` = clip area + open lanes; clip drawing and hit tests use the clip area),+ take lane drawing (waveform, "Take N", in-use highlight from clips' take ids), the swipe gesture+ (snap like other drags, Alt bypasses), and a lane context menu (Use whole take, Delete take,+ Flatten takes). Header: a chevron + count on audio tracks with takes.++## Project Structure++### Documentation (this feature)++```text+specs/067-take-lanes-comping/+├── spec.md+├── plan.md+├── research.md+├── data-model.md+├── quickstart.md+├── contracts/c-abi.md+├── checklists/requirements.md+└── tasks.md+```++### Source Code++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # NotaTakeInfo + nota_track_take_* / nota_clip_*take_id+├── src/engine/Track.h # AudioTake, Track::takes, AudioClip::takeId+├── src/engine/Engine.h / Engine.cpp # declarations, cloneTrack+├── src/engine/Engine_Recording.cpp # passes → takes + default comp+├── src/engine/Engine_Takes.cpp # new: take edits, peaks, load, test hook+├── src/engine/Engine_Tracks.cpp # findSampleById searches takes+├── src/abi/nota_engine_track.cpp # C wrappers+└── CMakeLists.txt # Engine_Takes.cpp+src/managed/+├── Nota.Application/Engine/{EngineContracts,IAudioEngine}.cs+├── Nota.Infrastructure/Interop/{NativeMethods.Tracks,NotaEngine.Takes}.cs+├── Nota.Infrastructure/Persistence/{ProjectModel,ProjectService}.cs+└── Nota.App/ArrangementView{,.LaneControl,.Takes}.cs+tests/Nota.SmokeTest/{TakeLaneTests,Program}.cs+```++**Structure Decision**: engine owns take data (undo for free), managed owns persistence and UI,+per the existing split.++## Complexity Tracking++None.diff --git a/specs/067-take-lanes-comping/quickstart.md b/specs/067-take-lanes-comping/quickstart.mdnew file mode 100644index 00000000..ea99d281--- /dev/null+++ b/specs/067-take-lanes-comping/quickstart.md@@ -0,0 +1,15 @@+# Quickstart: Take lanes and comping++1. New project, add an audio track, arm it, pick an input.+2. Turn the loop on over 1 bar (drag in the ruler) and press Record.+3. Play/sing three passes, then Stop. The track plays the third pass; its header shows a takes+ chevron with **3**.+4. Click the chevron: lanes **Take 1**, **Take 2**, **Take 3** open under the track. Take 3 is+ highlighted over the whole bar.+5. Drag across beats 1–2 on Take 1. Playback now plays Take 1 there; Take 1's lane highlights+ that section and Take 3's dims it. Undo restores Take 3 there.+6. Right-click a lane: **Delete take** (what plays doesn't change), **Flatten takes** (the comp+ becomes one clip, the lanes go away).+7. Save, close, reopen: the same takes and comp.++Automated: `dotnet run --project tests/Nota.SmokeTest -c Release -- --takes`.diff --git a/specs/067-take-lanes-comping/research.md b/specs/067-take-lanes-comping/research.mdnew file mode 100644index 00000000..62b32ed4--- /dev/null+++ b/specs/067-take-lanes-comping/research.md@@ -0,0 +1,52 @@+# Research: Take lanes and comping++## R1 — Where takes live++**Decision**: On the engine `Track` (graph snapshot), next to `clips`.++**Rationale**: Undo/redo restore graph snapshots (AR-5), so a comp edit, a delete and a flatten+are one undo step each with no extra machinery, and the take buffers are shared across+snapshots by `shared_ptr`. Keeping takes in the managed app would need a second undo history in+lock-step with the engine's.++**Alternatives**: managed-side take store (rejected: two histories); a special "comp clip" type+the audio thread resolves per block (rejected: new render-path work, AR-6 risk, perf gate).++## R2 — What the comp is++**Decision**: Ordinary audio clips, each tagged with the id of the take it plays (`takeId`).++**Rationale**: Playback, editing, clipboard, export, freeze and the clip editor all work+unchanged. The tag only drives the lane highlight and flatten. A section edited away from its+take keeps playing; flatten simply leaves it alone.++## R3 — Capturing passes++**Decision**: Keep today's loop-region write cursor. When it wraps, the drain copies the finished+pass `[passFrom, loopFrames)` into a fresh zeroed loop-length buffer. On stop the open pass is+added. Every take buffer starts at the loop start, so a position inside a take is a position in+the loop.++**Rationale**: The drain already runs on the message thread and already allocates; the audio+thread is untouched. Aligned buffers make the default comp, comp edits and flatten pure frame+arithmetic.++## R4 — Default comp++**Decision**: Newest-first coverage: every frame of the loop comes from the latest pass that+recorded it. This is exactly what today's in-place buffer holds at stop, so SC-002 is+sample-exact. A recording with a single pass keeps today's code path and creates no takes.++## R5 — Persistence identity++**Decision**: Save the take id with each take and with each comp clip; on load restore takes+first, map old ids to the fresh ones, tag the clips, and re-point each tagged clip at its take's+decoded buffer (same frames and rate) so a reopened comp shares memory like a fresh one.++**Rationale**: `SampleBuffer` ids are not persisted and the engine has no decode cache, so+sample identity can't link clips to takes across a save.++## R6 — Crossfades at comp boundaries++**Decision**: None in this version (spec assumption); sections are cut on whole frames of the+same loop-aligned recording. #286 (automatic crossfades at splits) is the follow-up.diff --git a/specs/067-take-lanes-comping/spec.md b/specs/067-take-lanes-comping/spec.mdnew file mode 100644index 00000000..9fac299b--- /dev/null+++ b/specs/067-take-lanes-comping/spec.md@@ -0,0 +1,203 @@+# Feature Specification: Take lanes and comping (audio loop recording)++**Feature Branch**: `cursor/take-lanes-comping-3af4`++**Created**: 2026-10-31++**Status**: Clarified++**Input**: User description: "Takes to Layers / Comping (nota-daw/nota#187). Today Nota replaces+existing clips when recording over them. Record multiple takes without overwriting the previous+ones, each take stored on its own layer, and comp the best sections from different takes into one+performance, rather than having to choose a single take or risk losing a great moment from an+earlier recording."++## 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+- [x] 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++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Every loop pass is kept as a take (Priority: P1)++A singer loops four bars on an audio track and sings the verse five times in a row. Today only+the last pass survives. With take lanes, when they stop, each pass is kept as its own take. The+track plays the latest pass, exactly as before, and the earlier passes are there to go back to.++**Why this priority**: This is the core of the request. Without it a great earlier pass is lost+the moment the loop comes round again, and nothing else in the feature has material to work on.++**Independent Test**: Loop 1 bar on an armed audio track, record three full passes with a+different signal on each, and stop. The track holds three takes, and playback sounds like the+third pass.++**Acceptance Scenarios**:++1. **Given** an armed audio track and the transport loop on, **When** the player records three full passes and stops, **Then** the track holds three takes, numbered in recording order, and the track plays the third pass over the loop.+2. **Given** a recording that started mid-loop and stopped mid-loop, **When** it stops, **Then** the first and last takes hold only the part of the loop they actually recorded, and the track plays, at every point of the loop, the most recent pass that covered it (the same audio as today).+3. **Given** a loop recording that never completed a pass (stopped before the loop came round), **When** it stops, **Then** it makes one ordinary clip and no takes, as today.+4. **Given** loop recording with the loop off (linear recording), **When** it stops, **Then** behaviour is unchanged: one clip, overwriting what it lands on, no takes.++---++### User Story 2 - See the takes in lanes under the track (Priority: P1)++The takes show as lanes under the track, one lane per take, with its waveform. The track's own+row stays on top and is the comp: what actually plays. The lanes are folded away by default and+open with a disclosure control on the track header. On each take lane, the sections the comp+uses are highlighted so it's clear where each part of the performance comes from.++**Why this priority**: Comping is impossible without seeing the takes.++**Independent Test**: After recording three passes, the track header shows a closed takes+disclosure. Opening it shows three lanes, Take 1 to Take 3, under the track; the third is+highlighted over the whole loop.++**Acceptance Scenarios**:++1. **Given** a track with takes, **When** the arrangement is shown, **Then** the take lanes are folded and the track header shows a takes disclosure with the take count.+2. **Given** folded take lanes, **When** the player opens the disclosure, **Then** one lane per take appears under the track's row, named "Take N", each showing its waveform over the range it recorded.+3. **Given** open take lanes, **When** a section of the comp comes from a take, **Then** that section of that take's lane is highlighted; sections not in use are dimmed.+4. **Given** a track without takes, **Then** it shows no disclosure and no lanes.++---++### User Story 3 - Comp by swiping a range on a take lane (Priority: P1)++The player drags across a section of a take lane. That section of the comp is replaced by the+same section of that take, so playback switches to it there and only there. Doing it again on+other lanes builds the final performance out of the best parts.++**Why this priority**: This is the comping the issue asks for.++**Independent Test**: With three takes, swipe beats 1–2 on Take 1. Playback plays Take 1 over+beats 1–2 and Take 3 elsewhere. Undo puts Take 3 back over beats 1–2.++**Acceptance Scenarios**:++1. **Given** open take lanes, **When** the player drags across a range on a take lane, **Then** the comp plays that take over the range (clamped to what the take recorded), and the rest of the comp is unchanged.+2. **Given** a swipe, **When** the player drags, **Then** the range follows the arrangement's snap grid (a modifier bypasses snapping, as for other arrangement drags) and shows a live preview on the lane.+3. **Given** a comp edit, **When** the player presses Undo, **Then** exactly that comp edit is undone; Redo puts it back.+4. **Given** a click on a take lane without a drag, **Then** the comp is not changed.++---++### User Story 4 - Delete takes and flatten (Priority: P2)++Once the comp is right the player either deletes takes they don't want, or flattens the takes:+the comp becomes one ordinary clip and the takes go away.++**Why this priority**: Without it, takes pile up in the project and in the arrangement forever.++**Independent Test**: Delete Take 2: it disappears and playback is unchanged. Flatten: the take+lanes disappear, the comp region holds one clip that sounds identical to the comp before.++**Acceptance Scenarios**:++1. **Given** a track with takes, **When** the player deletes a take, **Then** its lane goes away and what plays is unchanged (sections of the comp that came from it keep playing). One undo step.+2. **Given** a track with takes and a comp built from several of them, **When** the player chooses Flatten takes, **Then** the comp over the takes' range becomes one clip with the same audio, and every take of that recording is removed. One undo step.+3. **Given** a flatten or delete, **When** the player presses Undo, **Then** the takes and the comp are back exactly as before.++---++### User Story 5 - Takes survive save and reopen (Priority: P1)++Every take is saved with the project. Reopening the project shows the same takes, the same comp,+and the same highlighted sections.++**Why this priority**: Takes the user can't keep are worse than no takes.++**Independent Test**: Record three passes, comp two sections, save, reopen. Three takes, same+comp, same audio.++**Acceptance Scenarios**:++1. **Given** a project with takes and a comp, **When** it is saved and reopened, **Then** the takes (audio, range, number) and the comp (which sections come from which take) are restored.+2. **Given** a project saved by an older Nota, **When** it is opened, **Then** it opens as before with no takes.++### Edge Cases++- Recording again over the same loop adds new takes after the existing ones (numbering carries on) and the comp switches to the newest pass, as recording does today.+- A take lane is shown only over the range its take recorded; swiping outside it does nothing.+- Comp sections are ordinary clips: they can be moved, trimmed, split, faded or deleted like any clip. A section that was edited away from where its take sits stops counting as that take's for flatten (it stays as a clip of its own) — and keeps playing.+- Flatten only merges comp sections that still sit where their take recorded them, unwarped, unreversed and unpitched, with no clip envelope; any other section is kept as a separate clip.+- Deleting the last take of a track removes the disclosure.+- Changing the loop length mid-take, or turning the loop on mid-take, follows today's loop punch rules; passes are counted from where loop punch starts.+- Recording into a Session slot is unchanged (no takes).+- MIDI recording is unchanged (Overdub / Replace, specs/018).++## Clarifications++### Session 2026-10-31++- Q: Audio only, or audio and MIDI? → A: Audio only. MIDI keeps Overdub / Replace (specs/018).+- Q: What creates a new take? → A: Each loop pass. Linear recording (loop off) is unchanged.+- Q: How is it switched on? → A: Always on — no mode, no preference.+- Q: Lane UI? → A: Expandable lanes under the track, one row per take, with the comp (what plays) on top as the track's own row; collapsed by default.+- Q: How do you comp? → A: Swipe a range on a take lane to use that section.+- Q: Storage and undo? → A: All takes are saved in the project; takes can be deleted or flattened into one clip; one undo step is a single comp edit.+- Q: Session view? → A: Out of scope; slot recording is unchanged.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: An Arrangement audio loop recording that completes at least one pass MUST keep every pass as a separate take on the track, in recording order, instead of overwriting earlier passes.+- **FR-002**: A pass that started or stopped mid-loop MUST keep only the range it recorded.+- **FR-003**: After recording, the comp (what plays) MUST be, at every point of the loop, the most recent pass that recorded there — the same audio today's loop recording leaves.+- **FR-004**: Recordings that complete no pass, linear recordings (loop off), Session slot recordings and MIDI recordings MUST behave exactly as today and create no takes.+- **FR-005**: A track with takes MUST show a takes disclosure on its header with the take count; the take lanes MUST be folded by default and open/close from it.+- **FR-006**: Each open take lane MUST be named "Take N" (N in recording order, continuing across recordings on the track), show its waveform over its recorded range, and highlight the sections the comp currently uses.+- **FR-007**: Dragging across a range on a take lane MUST make the comp play that take over the range (clamped to the take's recorded range), leaving the rest of the comp untouched. The range MUST follow the arrangement's snap grid, with the usual modifier to bypass it.+- **FR-008**: Each comp edit MUST be one undo step.+- **FR-009**: The player MUST be able to delete a take (one undo step, what plays is unchanged) and to flatten a track's takes (one undo step): the comp over each recording's range becomes one clip with the same audio and that recording's takes are removed.+- **FR-010**: Takes and which comp sections come from which take MUST be saved with the project and restored on open; projects without takes MUST open unchanged.+- **FR-011**: Recording, comping, deleting and flattening MUST NOT cause an audible glitch: no new work on the audio thread beyond playing ordinary clips.++### Key Entities++- **Take**: One loop pass of one audio recording on one track: its audio, the timeline range it recorded, its number ("Take N"), and the recording it belongs to.+- **Recording (take group)**: The takes of one loop recording; they share the loop range. Flatten works per recording.+- **Comp**: What the track plays — its ordinary clips. A comp section is a clip that came from a take and remembers which take.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: After recording N full passes of a loop, the track holds N takes and 0 passes are lost (today: N − 1 lost).+- **SC-002**: Immediately after recording, the comp plays audio identical, sample for sample, to what today's loop recording leaves.+- **SC-003**: Using a section of another take takes one drag; undoing it takes one Undo.+- **SC-004**: Flattening produces audio identical, sample for sample, to the comp before flattening.+- **SC-005**: Saving and reopening restores 100% of the takes and the comp.+- **SC-006**: No dropout or audio-thread allocation is introduced; playback of a comp costs the same as playing the same number of ordinary clips.++## Assumptions++- No automatic crossfades at comp section boundaries in this version. Automatic crossfades at clip splits are tracked separately (#286) and can apply to comp boundaries when they land.+- Takes are recorded and stored at the same alignment (each take covers the loop region of its recording), so a comp section's position inside its take is its position in the loop.+- The take lanes' open/closed state is view state, not saved with the project (like the clip editor height); lanes start folded.+- Comp sections are ordinary clips, so every existing clip edit works on them; the take link only drives the highlight and flatten.+- MCP / Nota Remote control of takes is out of scope for this version.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [x] 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)+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`+- [x] 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)+- [x] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/067-take-lanes-comping/tasks.md b/specs/067-take-lanes-comping/tasks.mdnew file mode 100644index 00000000..f4c26ebb--- /dev/null+++ b/specs/067-take-lanes-comping/tasks.md@@ -0,0 +1,57 @@+---+description: "Tasks for take lanes and comping"+---++# Tasks: Take lanes and comping (audio loop recording)++**Input**: [spec.md](spec.md), [plan.md](plan.md), [data-model.md](data-model.md), [contracts/c-abi.md](contracts/c-abi.md)++## Phase 1: Foundational (engine data + ABI)++- [x] T001 `AudioTake`, `Track::takes`, `AudioClip::takeId` in `src/native/nota.engine/src/engine/Track.h`; `cloneTrack` copies takes (`Engine.cpp`)+- [x] T002 `findSampleById` searches takes (`Engine_Tracks.cpp`)+- [x] T003 `NotaTakeInfo` + `nota_track_take_*` / `nota_clip_*take_id` / `nota_track_restore_take` / `nota_take_record_test` in `include/nota/nota_engine.h`, wrappers in `src/abi/nota_engine_track.cpp`+- [x] T004 `Engine_Takes.cpp` (new, CMakeLists): info, peaks, comp, delete, flatten, restore, tag, test hook+- [x] T005 Managed contracts: `NotaTakeInfo` (`EngineContracts.cs`), `IAudioEngine` members, `NativeMethods.Tracks.cs`, `NotaEngine.Takes.cs`++## Phase 2: US1 — every loop pass is kept (P1)++- [x] T006 [US1] Pass capture on wrap + take path on stop in `Engine_Recording.cpp` (one pass → today's path)+- [x] T007 [US1] Smoke: N passes → N takes, numbering, default comp sample-exact vs single-buffer reference, partial first/last pass ranges, one pass → no takes, loop off → no takes (`tests/Nota.SmokeTest/TakeLaneTests.cs`, `Program.cs` incl. `--takes`)++## Phase 3: US3 — comp by swiping (P1)++- [x] T008 [US3] Smoke: comp a range → that take plays there only, clamped to the take; undo/redo one step each+- [x] T009 [US3] Swipe gesture on a take lane with snap / Alt bypass and preview (`ArrangementView.Takes.cs`, `ArrangementView.LaneControl.cs`)++## Phase 4: US2 — take lanes in the arrangement (P1)++- [x] T010 [US2] Take VMs loaded in `Refresh` (`ArrangementView.cs`, `ArrangementView.Vms.cs`)+- [x] T011 [US2] Row geometry: open lanes add height; clips draw and hit-test in the clip area (`ArrangementView.cs`, `ArrangementView.LaneControl.cs`)+- [x] T012 [US2] Draw lanes: waveform over the take range, "Take N", in-use highlight (`ArrangementView.Takes.cs`)+- [x] T013 [US2] Header chevron + count on audio tracks with takes; folded by default (`ArrangementView.cs`)++## Phase 5: US4 — delete and flatten (P2)++- [x] T014 [US4] Lane context menu: Use whole take, Delete take, Flatten takes (`ArrangementView.Takes.cs`)+- [x] T015 [US4] Smoke: delete keeps the sound; flatten → one clip, sample-exact, takes gone; undo restores++## Phase 6: US5 — save and reopen (P1)++- [x] T016 [US5] `AudioTakeDto`, `TrackDto.Takes`, `AudioClipDto.TakeId`, format v29 (`ProjectModel.cs`, `ProjectService.cs`)+- [x] T017 [US5] Save takes / restore takes then tag clips (`ProjectService.cs`, `AudioClipState.cs`)+- [x] T018 [US5] Smoke: save + reopen restores takes, comp tags, audio++## Phase 7: Polish++- [x] T019 `CHANGELOG.md` `[Unreleased]`, `FEATURES.md` (nota-features), user manual (nota-docs)+- [x] T020 `scripts/build-linux.sh` green; `/speckit-converge`++## Compliance re-check++- [x] SPDX headers on new files (`Engine_Takes.cpp`, `NotaEngine.Takes.cs`, `ArrangementView.Takes.cs`, `TakeLaneTests.cs`)+- [x] No new dependency+- [x] No audio-thread change (AR-6); takes on the snapshot (AR-5); C ABI only (AR-7)+- [x] Smoke test extended+- [x] CHANGELOG / FEATURES / docs+- [x] DESIGN.md: lane palette, track colour, existing chevron glyphdiff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex 60f56955..12a58e14 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -20,7 +20,7 @@ namespace Nota.App;public sealed partial class ArrangementView{// ---- lanes ------------------------------------------------------------- private sealed class LaneControl : Control, IAutoRows, IValueEntryHost+ private sealed partial class LaneControl : Control, IAutoRows, IValueEntryHost{private readonly ArrangementView _o;private readonly AutoEditor _auto; // automation mode (M9-A3), shared with the footer's return rows@@ -69,7 +69,7 @@ public sealed partial class ArrangementViewTrackVM IAutoRows.TrackAt(int i) => _o._tracks[i];int IAutoRows.IndexOf(TrackVM t) => _o._tracks.IndexOf(t);double IAutoRows.Top(int i) => _o.RowTop(i);- double IAutoRows.Height(int i) => _o.RowHeightAt(i);+ double IAutoRows.Height(int i) => _o.ClipAreaHeightAt(i);bool IAutoRows.Editable(int i) => !_o.IsSlimRowAt(i); // a slim group bar has no room for an envelope(int lo, int hi) IAutoRows.VisibleRange => _o.VisibleRowRange();@@ -182,9 +182,9 @@ public sealed partial class ArrangementView/// <summary>A clip drag / trim, marquee, time-range or envelope edit is in progress:/// Follow must not scroll the lanes out from under it (#105).</summary>- public bool IsGesturing => _drag != Drag.None || _marquee is not null || _auto.IsActive;+ public bool IsGesturing => _drag != Drag.None || _marquee is not null || _auto.IsActive || _takeSwipe is not null;private double RowTop(int i) => _o.RowTop(i);- private double RowH(int i) => _o.RowHeightAt(i);+ private double RowH(int i) => _o.ClipAreaHeightAt(i);protected override void OnPointerWheelChanged(PointerWheelEventArgs e)=> _o.HandleLaneWheel(e, e.GetPosition(this).X);@@ -192,7 +192,7 @@ public sealed partial class ArrangementView{beat = _o._scrollBeats + p.X / _o._pixelsPerBeat;int ti = _o.RowAtY(p.Y);- if (ti < 0) return null;+ if (ti < 0 || p.Y >= RowTop(ti) + RowH(ti)) return null; // below the clip area: take lanesvar t = _o._tracks[ti];foreach (var c in t.Clips)if (beat >= c.StartBeat && beat <= c.StartBeat + c.LengthBeats)@@ -233,6 +233,7 @@ public sealed partial class ArrangementViewprotected override void OnPointerPressed(PointerPressedEventArgs e){if (RowSeamPressed(e)) return;+ if (TakeLanePressed(e)) return;if (_o._automationMode) { _auto.AutoPointerPressed(e); return; }var pt = e.GetCurrentPoint(this);var hit = HitTest(pt.Position, out double beat);@@ -383,6 +384,7 @@ public sealed partial class ArrangementViewprotected override void OnPointerMoved(PointerEventArgs e){if (_o.IsRowResizing) { _o.UpdateRowResize(e.GetPosition(this).Y); return; }+ if (_takeSwipe is not null) { TakeSwipeMoved(e); return; }if (e.GetCurrentPoint(this).Properties is { IsLeftButtonPressed: false, IsRightButtonPressed: false }&& RowSeamHover(e.GetPosition(this))) return;if (_o._automationMode) { _auto.AutoPointerMoved(e); return; }@@ -553,6 +555,7 @@ public sealed partial class ArrangementViewprotected override void OnPointerReleased(PointerReleasedEventArgs e){if (_o.IsRowResizing) { e.Pointer.Capture(null); _o.EndRowResize(); return; }+ if (_takeSwipe is not null) { TakeSwipeReleased(e); return; }if (_o._automationMode) { _auto.AutoPointerReleased(e); return; }var eng = _o._engine;@@ -713,9 +716,11 @@ public sealed partial class ArrangementView// OnPointerReleased turns it into a selection.bool active = _drag != Drag.None || _groupMove is not null || _rangeActive|| _auto.IsActive- || _adsrDrag != AdsrHandle.None;+ || _adsrDrag != AdsrHandle.None+ || _takeSwipe is not null;if (!active) return false;_pending = false; _drag = Drag.None; _groupMove = null; _moveRowDelta = 0; _dragClip = null; _rpPeaks = null;+ _takeSwipe = null; _takeMoved = false; // an abandoned take swipe never comps_marqueeArmed = false; _rangeActive = false; _marquee = null; _shiftClipTrack = -1; _shiftClipIndex = -1;_auto.Cancel();_adsrDrag = AdsrHandle.None; _adsrClip = null;@@ -1119,6 +1124,7 @@ public sealed partial class ArrangementViewtake ? rp : null);}if (take) DrawHeldNotes(ctx, rp!, _o._tracks[i].ColorIndex, y, rh, w, pitches);+ if (_o.TakesOpen(_o._tracks[i])) DrawTakeLanes(ctx, _o._tracks[i], y + rh, w);// Imports still decoding: a translucent placeholder whose waveform fills in.using (ctx.PushOpacity(0.5))foreach (var c in _o.PendingClipsFor(tid))diff --git a/src/managed/Nota.App/ArrangementView.Sizing.cs b/src/managed/Nota.App/ArrangementView.Sizing.csindex 7226955e..f0e4aa04 100644--- a/src/managed/Nota.App/ArrangementView.Sizing.cs+++ b/src/managed/Nota.App/ArrangementView.Sizing.cs@@ -226,14 +226,14 @@ public sealed partial class ArrangementViewvar children = _headers.Children;int crossing = 0;for (int i = 0; i < _tracks.Count; i++)- if (!IsSlimRow(_tracks[i]) && _cardTiers.TryGetValue(_tracks[i].Id, out var b) && b != TierFor(RowHeightAt(i))) crossing++;+ if (!IsSlimRow(_tracks[i]) && _cardTiers.TryGetValue(_tracks[i].Id, out var b) && b != TierFor(ClipAreaHeightAt(i))) crossing++;bool rebuildTiers = crossing <= LiveTierRebuildLimit;for (int i = 0; i < _tracks.Count; i++){var t = _tracks[i];if (!_headerCards.TryGetValue(t.Id, out var hc)) continue;Control card = hc.card;- double h = RowHeightAt(i);+ double h = ClipAreaHeightAt(i);if (rebuildTiers && !IsSlimRow(t) && _cardTiers.TryGetValue(t.Id, out var built) && built != TierFor(h)){int at = children.IndexOf(card);@@ -245,6 +245,7 @@ public sealed partial class ArrangementViewCanvas.SetTop(card, RowTop(i));card.Height = h;}+ PlaceTakeHeaders();PlaceRowSeamGrips();_headers.Height = Math.Max(DefaultRowHeight, RowsHeight);_lanes.Height = _headers.Height;diff --git a/src/managed/Nota.App/ArrangementView.Takes.cs b/src/managed/Nota.App/ArrangementView.Takes.csnew file mode 100644index 00000000..287055e6--- /dev/null+++ b/src/managed/Nota.App/ArrangementView.Takes.cs@@ -0,0 +1,313 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Take lanes (#187, specs/067): the passes of an audio loop recording, one lane per take under+// the track's clip area, folded by default. Swiping a range on a lane comps that take in over+// the range; the lane's menu uses a whole take, deletes it or flattens the track's takes. Every+// edit is one engine call and one undo step; the comp itself is the track's ordinary clips.++using System;+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using Nota.Presentation;++namespace Nota.App;++public sealed partial class ArrangementView+{+ internal sealed class TakeVM+ {+ public int Id;+ public int Number;+ public double StartBeat;+ public double LengthBeats;+ public float[]? Peaks;+ public int PeakCount;+ }++ private const double TakeLaneH = 36;+ private const int TakePeakBuckets = 1024;++ // Open take lanes are view state, like a group's fold: not saved, folded on open.+ private readonly HashSet<int> _takesOpen = new();+ // A take's audio never changes, so its peaks are fetched once per (track, take, sample).+ private Dictionary<(int track, int take, long sample), (float[] peaks, int count)> _takePeaks = new();+ private readonly List<(Border lane, int trackId, int index)> _takeHeaders = new();++ internal bool TakesOpen(TrackVM t) => t.Takes.Count > 0 && _takesOpen.Contains(t.Id);+ private double TakesHeight(TrackVM t) => TakesOpen(t) ? t.Takes.Count * TakeLaneH : 0;++ private void ToggleTakes(int trackId)+ {+ if (!_takesOpen.Remove(trackId)) _takesOpen.Add(trackId);+ Refresh();+ }++ private void LoadTakes(IAudioEngine eng, TrackVM tvm, Dictionary<(int, int, long), (float[], int)> peaks)+ {+ int n = eng.TakeCount(tvm.Id);+ for (int k = 0; k < n; k++)+ {+ if (!eng.TryGetTakeInfo(tvm.Id, k, out var info)) continue;+ var key = (tvm.Id, info.Id, info.SampleId);+ if (!_takePeaks.TryGetValue(key, out var p))+ {+ var buf = new float[TakePeakBuckets * 2];+ p = (buf, eng.GetTakePeaks(tvm.Id, k, buf, TakePeakBuckets));+ }+ peaks[key] = p;+ tvm.Takes.Add(new TakeVM+ {+ Id = info.Id, Number = info.Number, StartBeat = info.StartBeat, LengthBeats = info.LengthBeats,+ Peaks = p.peaks, PeakCount = p.count,+ });+ }+ }++ /// <summary>The take lane under <paramref name="y"/>: its row and the take, or null.</summary>+ internal (int row, TakeVM take)? TakeLaneAt(double y)+ {+ int row = RowAtY(y);+ if (row < 0 || !TakesOpen(_tracks[row])) return null;+ double top = RowTop(row) + ClipAreaHeightAt(row);+ if (y < top) return null;+ int k = (int)((y - top) / TakeLaneH);+ var takes = _tracks[row].Takes;+ return k >= 0 && k < takes.Count ? (row, takes[k]) : null;+ }++ private void CompTake(int trackId, int takeId, double a, double b)+ {+ if (_engine is null || Math.Abs(b - a) < 1e-9) return;+ if (_engine.CompTake(trackId, takeId, Math.Min(a, b), Math.Max(a, b))) Refresh();+ }++ private MenuFlyout BuildTakeMenu(int trackId, TakeVM take)+ {+ var flyout = new MenuFlyout();+ var header = MenuKit.Header($"Take {take.Number}", null, "");+ var use = MenuKit.Item("Use whole take", GlyphKind.Check,+ () => CompTake(trackId, take.Id, take.StartBeat, take.StartBeat + take.LengthBeats));+ var flatten = MenuKit.Danger("Flatten takes", GlyphKind.Flatten,+ () => { if (_engine?.FlattenTakes(trackId) == true) { _takesOpen.Remove(trackId); Refresh(); } });+ var del = MenuKit.Danger("Delete take", GlyphKind.Trash,+ () => { if (_engine?.DeleteTake(trackId, take.Id) == true) Refresh(); });+ MenuKit.AddGroups(flyout.Items, new Control[] { header }, new Control[] { use, flatten }, new Control[] { del });+ return flyout;+ }++ // Header disclosure on an audio track with takes: ▸/▾ and the take count.+ private Control? TakesToggle(TrackVM t)+ {+ if (t.Takes.Count == 0) return null;+ bool open = _takesOpen.Contains(t.Id);+ var toggle = new Border+ {+ Background = Brushes.Transparent, Padding = new Thickness(2, 0), Margin = new Thickness(0, 0, 4, 0),+ Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,+ Child = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 3,+ Children =+ {+ new Glyph(open ? GlyphKind.ChevronDown : GlyphKind.ChevronRight, 8)+ { Foreground = Brush("Brush.TextSecondary"), VerticalAlignment = VerticalAlignment.Center },+ new TextBlock+ {+ Text = $"{t.Takes.Count}", FontSize = 9, Classes = { "Mono" },+ Foreground = Brush("Brush.TextSecondary"), VerticalAlignment = VerticalAlignment.Center,+ },+ },+ },+ };+ ToolTip.SetTip(toggle, open ? "Hide takes" : $"Show {t.Takes.Count} takes");+ toggle.PointerPressed += (_, e) => { e.Handled = true; ToggleTakes(t.Id); };+ return toggle;+ }++ // Header column beside open lanes: "Take N" per lane, with the lane's menu on right-click.+ private void AddTakeHeaders()+ {+ _takeHeaders.Clear();+ foreach (var t in _tracks)+ {+ if (!TakesOpen(t)) continue;+ for (int k = 0; k < t.Takes.Count; k++)+ {+ var take = t.Takes[k];+ int trackId = t.Id;+ var lane = new Border+ {+ Height = TakeLaneH, Background = Brush("Brush.BgSunken"),+ BorderBrush = Brush("Brush.BorderDefault"), BorderThickness = new Thickness(0, 0, 0, 1),+ Padding = new Thickness(22, 0, 8, 0),+ Child = new TextBlock+ {+ Text = $"Take {take.Number}", FontSize = 11, Foreground = Brush("Brush.TextSecondary"),+ VerticalAlignment = VerticalAlignment.Center,+ },+ };+ lane.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(lane).Properties.IsRightButtonPressed) return;+ e.Handled = true;+ BuildTakeMenu(trackId, take).ShowAt(lane, showAtPointer: true);+ };+ _takeHeaders.Add((lane, trackId, k));+ _headers.Children.Add(lane);+ }+ }+ PlaceTakeHeaders();+ }++ private void PlaceTakeHeaders()+ {+ foreach (var (lane, trackId, k) in _takeHeaders)+ {+ int i = _tracks.FindIndex(t => t.Id == trackId);+ lane.IsVisible = i >= 0 && TakesOpen(_tracks[i]);+ if (!lane.IsVisible) continue;+ lane.Width = _headerW;+ Canvas.SetLeft(lane, 0);+ Canvas.SetTop(lane, RowTop(i) + ClipAreaHeightAt(i) + k * TakeLaneH);+ }+ }++ private static readonly IBrush TakeLaneBg = NotaPalette.Wash(NotaPalette.BgSunken, 0xC0);++ private sealed partial class LaneControl+ {+ // A swipe on a take lane: the take, its track, and the snapped range so far.+ // A press that never travels is a click and leaves the comp alone (spec US3).+ private (int trackId, int takeId, double a, double b)? _takeSwipe;+ private double _takePressX;+ private bool _takeMoved;++ private double BeatAt(double x) => _o._scrollBeats + x / _o._pixelsPerBeat;++ private bool TakeLanePressed(PointerPressedEventArgs e)+ {+ var pt = e.GetCurrentPoint(this);+ if (_o.TakeLaneAt(pt.Position.Y) is not { } hit) return false;+ e.Handled = true;+ int trackId = _o._tracks[hit.row].Id;+ if (pt.Properties.IsRightButtonPressed)+ {+ _o.BuildTakeMenu(trackId, hit.take).ShowAt(this, showAtPointer: true);+ return true;+ }+ if (!pt.Properties.IsLeftButtonPressed) return true;+ double a = Math.Max(0, _o.SnapMaybe(BeatAt(pt.Position.X), e.KeyModifiers));+ _takePressX = pt.Position.X;+ _takeMoved = false;+ _takeSwipe = (trackId, hit.take.Id, a, a);+ e.Pointer.Capture(this);+ InvalidateVisual();+ return true;+ }++ private void TakeSwipeMoved(PointerEventArgs e)+ {+ if (_takeSwipe is not { } s) return;+ var pos = e.GetPosition(this);+ if (!_takeMoved && Math.Abs(pos.X - _takePressX) < DragThreshold) return;+ _takeMoved = true;+ double b = Math.Max(0, _o.SnapMaybe(BeatAt(pos.X), e.KeyModifiers));+ if (b == s.b) return;+ _takeSwipe = s with { b = b };+ InvalidateVisual();+ }++ private void TakeSwipeReleased(PointerReleasedEventArgs e)+ {+ var s = _takeSwipe!.Value;+ bool moved = _takeMoved;+ _takeSwipe = null;+ _takeMoved = false;+ e.Pointer.Capture(null);+ InvalidateVisual();+ if (moved) _o.CompTake(s.trackId, s.takeId, s.a, s.b);+ }++ // The lanes under a track's clip area: each take's recorded range dimmed, the sections+ // the comp plays from it in the track colour, and the swipe in progress.+ private void DrawTakeLanes(DrawingContext ctx, TrackVM t, double top, double w)+ {+ var (_, _, _, body) = ClipColors(t.ColorIndex);+ var ink = ClipInk(t.ColorIndex);+ for (int k = 0; k < t.Takes.Count; k++)+ {+ var take = t.Takes[k];+ double y = top + k * TakeLaneH;+ ctx.FillRectangle(TakeLaneBg, new Rect(0, y, w, TakeLaneH));+ ctx.DrawLine(BeatPen, new Point(0, y + TakeLaneH), new Point(w, y + TakeLaneH));++ double x0 = _o.BeatToX(take.StartBeat), x1 = _o.BeatToX(take.StartBeat + take.LengthBeats);+ var r = new Rect(x0, y + 3, Math.Max(2, x1 - x0), TakeLaneH - 6);+ if (x1 >= 0 && x0 <= w)+ {+ using (ctx.PushOpacity(0.35))+ {+ ctx.DrawRectangle(body, null, r, NotaRadius.ClipValue, NotaRadius.ClipValue);+ DrawTakePeaks(ctx, take, r, r, ink);+ }+ foreach (var c in t.Clips)+ {+ if (c.TakeId != take.Id || !c.Active) continue; // a deactivated section is silent+ double cx0 = Math.Max(r.X, _o.BeatToX(c.StartBeat)), cx1 = Math.Min(r.Right, _o.BeatToX(c.StartBeat + c.LengthBeats));+ if (cx1 <= cx0 || cx1 < 0 || cx0 > w) continue;+ var used = new Rect(cx0, r.Y, cx1 - cx0, r.Height);+ ctx.DrawRectangle(body, null, used, NotaRadius.ClipValue, NotaRadius.ClipValue);+ DrawTakePeaks(ctx, take, r, used, ink);+ }+ }++ if (_takeSwipe is { } s && s.trackId == t.Id && s.takeId == take.Id && s.a != s.b)+ {+ double sx0 = _o.BeatToX(Math.Min(s.a, s.b)), sx1 = _o.BeatToX(Math.Max(s.a, s.b));+ var band = new Rect(sx0, y + 1, sx1 - sx0, TakeLaneH - 2);+ ctx.FillRectangle(MarqueeFill, band);+ ctx.DrawRectangle(null, MarqueePen, band);+ }++ // The lane's name stays at the left edge while the take scrolls past.+ var ft = new FormattedText($"Take {take.Number}", CultureInfo.InvariantCulture,+ FlowDirection.LeftToRight, NotaFonts.SansSemiBold, 9.5, RulerText);+ double lx = Math.Max(4, Math.Min(x0 + 4, w - ft.Width - 8));+ var plate = new Rect(lx - 3, y + 4, ft.Width + 6, ft.Height + 1);+ ctx.DrawRectangle(LabelPlate, null, plate, 2, 2);+ ctx.DrawText(ft, new Point(lx, y + 4));+ }+ }++ // The take's waveform over `full` (its recorded range), painted only inside `part`.+ private void DrawTakePeaks(DrawingContext ctx, TakeVM take, Rect full, Rect part, IBrush brush)+ {+ if (take.Peaks is not { } pk || take.PeakCount <= 0 || full.Width < 1) return;+ double mid = full.Y + full.Height / 2, amp = full.Height / 2 - 1;+ int n = take.PeakCount;+ double px0 = Math.Max(Math.Max(part.X, full.X), 0), px1 = Math.Min(Math.Min(part.Right, full.Right), Bounds.Width);+ var geo = new StreamGeometry();+ using (var g = geo.Open())+ for (double px = Math.Floor(px0); px < px1; px++)+ {+ int b0 = (int)((px - full.X) / full.Width * n), b1 = (int)((px + 1 - full.X) / full.Width * n);+ b0 = Math.Clamp(b0, 0, n - 1);+ b1 = Math.Clamp(Math.Max(b1, b0 + 1), b0 + 1, n);+ float min = 0, max = 0;+ for (int b = b0; b < b1; b++) { min = Math.Min(min, pk[b * 2]); max = Math.Max(max, pk[b * 2 + 1]); }+ min = Math.Clamp(min, -1f, 1f); max = Math.Clamp(max, -1f, 1f);+ AddRect(g, px, mid - max * amp, 1, Math.Max(1, (max - min) * amp));+ }+ using (ctx.PushClip(part))+ ctx.DrawGeometry(brush, null, geo);+ }+ }+}diff --git a/src/managed/Nota.App/ArrangementView.Vms.cs b/src/managed/Nota.App/ArrangementView.Vms.csindex fd4728a2..b26fbdc6 100644--- a/src/managed/Nota.App/ArrangementView.Vms.cs+++ b/src/managed/Nota.App/ArrangementView.Vms.cs@@ -37,6 +37,7 @@ public sealed partial class ArrangementViewpublic int LiveRole; // live-freeze (v1.1): 0 none, 1 sleeping source, 2 linked frozenpublic string Name = "";public List<ClipVM> Clips = new();+ public List<TakeVM> Takes = new(); // loop-recording take lanes (specs/067), audio tracks only// Automation (M9-A3): current target + its live-editable envelope.public float Volume = 1f;public float Pan;@@ -78,6 +79,7 @@ public sealed partial class ArrangementViewpublic double LengthBeats;public bool IsMidi;public bool Active = true; // false = deactivated (key 0): stays but silent + greyed+ public int TakeId; // the take this comp section came from (specs/067), 0 = nonepublic float[]? Peaks;public int PeakCount;/// <summary>RMS level per bucket of <see cref="Peaks"/> (null when unknown — an import placeholder).</summary>diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex d3027d71..64b70ee0 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -106,14 +106,19 @@ public sealed partial class ArrangementView : UserControlfor (int i = 0; i < _tracks.Count; i++){tops[i] = y;- y += IsSlimRow(_tracks[i]) ? GroupRowHeight : TrackRowHeight(_tracks[i]);+ y += RowHeightAt(i);}tops[_tracks.Count] = y;_rowTops = tops;}- /// <summary>Height of arrangement row <paramref name="i"/> — a slim bar for a group.</summary>+ /// <summary>Height of arrangement row <paramref name="i"/>: its clip area plus any open take lanes.</summary>internal double RowHeightAt(int i)+ => ClipAreaHeightAt(i) + (i >= 0 && i < _tracks.Count ? TakesHeight(_tracks[i]) : 0);++ /// <summary>Height of row <paramref name="i"/>'s clip area — a slim bar for a group. Clips,+ /// automation and the header card live here; open take lanes sit below it.</summary>+ internal double ClipAreaHeightAt(int i)=> i < 0 || i >= _tracks.Count ? DefaultRowHeight: IsSlimRow(_tracks[i]) ? GroupRowHeight : TrackRowHeight(_tracks[i]);@@ -1016,6 +1021,7 @@ public sealed partial class ArrangementView : UserControlif (rebuildHeaders) ReloadSections(); // sections live in the engine's project (specs/016)_tracks.Clear();_returns.Clear();+ var takePeaks = new Dictionary<(int, int, long), (float[], int)>();if (_engine is { } eng){int n = eng.TrackCount;@@ -1099,14 +1105,18 @@ public sealed partial class ArrangementView : UserControl{cvm.Gain = ai.Gain;cvm.Adsr = eng.GetClipAdsr(ti.Id, c);+ cvm.TakeId = eng.ClipTakeId(ti.Id, c);}tvm.Clips.Add(cvm);}+ if (ti.Type == 0) LoadTakes(eng, tvm, takePeaks);MarkClipRuns(tvm);(tvm.IsReturn ? _returns : _tracks).Add(tvm);}}+ _takePeaks = takePeaks;+ _takesOpen.RemoveWhere(id => !_tracks.Any(t => t.Id == id && t.Takes.Count > 0));ApplyHierarchy(); // reorder _tracks into group DFS order (depth + collapse-filtered)PruneTrackHeights(); // heights of deleted tracks go with themRebuildRowGeometry(); // row tops depend on which rows are groups → after the reorder@@ -2075,6 +2085,7 @@ public sealed partial class ArrangementView : UserControlCanvas.SetTop(card, RowTop(i)); // pin to the same Y as the lane row_headers.Children.Add(card);}+ AddTakeHeaders();AddRowSeamGrips(); // row-height grips sit above the cards_headers.Children.Add(_trackDropLine); // insertion marker (kept invisible until a drag)_headers.Children.Add(_headerDropRing); // browser drop target (kept invisible until a drag)@@ -2197,6 +2208,11 @@ public sealed partial class ArrangementView : UserControlGrid.SetColumn(tri, 0);nameRow.Children.Add(tri);}+ else if (TakesToggle(t) is { } takes)+ {+ Grid.SetColumn(takes, 0);+ nameRow.Children.Add(takes);+ }else if (t.Frozen || t.LiveRole != 0){// Freeze badge: a drawn chain-link for a sleeping live-freeze source (1);diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 8ddd4066..1d830a7c 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -97,6 +97,24 @@ public struct NotaAudioClipInfopublic int Reversed; // 0/1: plays back-to-front (non-destructive)}+/// <summary>One take of an audio loop recording (specs/067). Matches native NotaTakeInfo. Every+/// take of a recording has a loop-length buffer whose frame 0 sits at <see cref="OriginBeat"/>;+/// the pass recorded <see cref="StartBeat"/> .. + <see cref="LengthBeats"/> of it.</summary>+[StructLayout(LayoutKind.Sequential)]+public struct NotaTakeInfo+{+ public int Id; // comp clips carry it (IAudioEngine.ClipTakeId)+ public int Number; // "Take N" on its track+ public int Group; // the loop recording it came from+ public int Reserved;+ public double OriginBeat;+ public double StartBeat;+ public double LengthBeats;+ public double SourceOffsetFrames;+ public long LengthFrames;+ public long SampleId;+}+/// <summary>Audio-clip ADSR amplitude shape in played time (clip-local beats). Matches native/// NotaClipAdsr. Attack ramps 0→1 from the clip start, decay falls to <see cref="Sustain"/>,/// release fades to 0 over the clip's last <see cref="ReleaseBeats"/>. <see cref="Identity"/>diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 72f87cf5..5ae04203 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -1138,6 +1138,25 @@ public interface IAudioEngine : IDisposable// --- Audio persistence (M7-6b) -----------------------------------------bool TryGetAudioClipInfo(int trackId, int clipIndex, out NotaAudioClipInfo info);int AddAudioClipEx(int trackId, string path, double startBeat, double sourceOffsetFrames, long lengthFrames, float gain);++ // --- Take lanes (specs/067) --------------------------------------------+ /// <summary>The takes on an audio track, in recording order.</summary>+ int TakeCount(int trackId);+ bool TryGetTakeInfo(int trackId, int index, out NotaTakeInfo info);+ /// <summary>Min/max peaks over the take's recorded range; buckets written.</summary>+ int GetTakePeaks(int trackId, int index, float[] outMinMax, int maxPoints);+ /// <summary>The take plays over [startBeat, endBeat) (clamped to it). One undo step; false if nothing changed.</summary>+ bool CompTake(int trackId, int takeId, double startBeat, double endBeat);+ /// <summary>Removes a take; what plays is unchanged. One undo step.</summary>+ bool DeleteTake(int trackId, int takeId);+ /// <summary>Each recording's comp becomes one clip and its takes go. One undo step.</summary>+ bool FlattenTakes(int trackId);+ /// <summary>The take an arrangement audio clip plays a section of; 0 = none.</summary>+ int ClipTakeId(int trackId, int clipIndex);+ /// <summary>Project load (no undo entry): a take from a file; its new id, or -1.</summary>+ int RestoreTake(int trackId, string path, int number, int group, double originBeat, double sourceOffsetFrames, long lengthFrames);+ /// <summary>Project load (no undo entry): tag a restored clip as a section of a restored take.</summary>+ void SetClipTakeId(int trackId, int clipIndex, int takeId);bool TryGetSampleInfo(long sampleId, out NotaSampleInfo info);float[] ReadSample(long sampleId);bool TryGetSamplerInfo(int trackId, out NotaSamplerInfo info);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Takes.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Takes.csnew file mode 100644index 00000000..1ebb6ecc--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Takes.cs@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Runtime.InteropServices;++namespace Nota.Infrastructure;++/// <summary>Take lanes (specs/067): the passes of an audio loop recording and the comp built from them.</summary>+/// <remarks>Part of <see cref="NotaEngine"/>'s P/Invoke surface; see nota_engine.h.</remarks>+internal static partial class NativeMethods+{+ [LibraryImport(Lib, EntryPoint = "nota_track_take_count")]+ internal static partial int TakeCount(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_track_take_info")]+ internal static partial int TakeInfo(IntPtr engine, int trackId, int index, out NotaTakeInfo info);++ [LibraryImport(Lib, EntryPoint = "nota_track_take_peaks")]+ internal static partial int TakePeaks(IntPtr engine, int trackId, int index, [Out] float[] outMinMax, int maxPoints);++ [LibraryImport(Lib, EntryPoint = "nota_track_take_comp")]+ internal static partial NotaResult TakeComp(IntPtr engine, int trackId, int takeId, double startBeat, double endBeat);++ [LibraryImport(Lib, EntryPoint = "nota_track_take_delete")]+ internal static partial NotaResult TakeDelete(IntPtr engine, int trackId, int takeId);++ [LibraryImport(Lib, EntryPoint = "nota_track_takes_flatten")]+ internal static partial NotaResult TakesFlatten(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_clip_take_id")]+ internal static partial int ClipTakeId(IntPtr engine, int trackId, int clipIndex);++ [LibraryImport(Lib, EntryPoint = "nota_track_restore_take", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int RestoreTake(IntPtr engine, int trackId, string path, int number, int group,+ double originBeat, double sourceOffsetFrames, long lengthFrames);++ [LibraryImport(Lib, EntryPoint = "nota_clip_set_take_id")]+ internal static partial NotaResult ClipSetTakeId(IntPtr engine, int trackId, int clipIndex, int takeId);++ [LibraryImport(Lib, EntryPoint = "nota_take_record_test")]+ internal static partial int TakeRecordTest(IntPtr engine, int trackId, float[] interleavedStereo, int frames, double startBeat);+}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Takes.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Takes.csnew file mode 100644index 00000000..05a424a7--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Takes.cs@@ -0,0 +1,41 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++namespace Nota.Infrastructure;++public sealed partial class NotaEngine+{+ // --- take lanes (specs/067) ---++ public int TakeCount(int trackId)+ { ThrowIfDisposed(); return NativeMethods.TakeCount(_handle, trackId); }++ public bool TryGetTakeInfo(int trackId, int index, out NotaTakeInfo info)+ { ThrowIfDisposed(); return NativeMethods.TakeInfo(_handle, trackId, index, out info) != 0; }++ public int GetTakePeaks(int trackId, int index, float[] outMinMax, int maxPoints)+ { ThrowIfDisposed(); return NativeMethods.TakePeaks(_handle, trackId, index, outMinMax, maxPoints); }++ public bool CompTake(int trackId, int takeId, double startBeat, double endBeat)+ { ThrowIfDisposed(); return NativeMethods.TakeComp(_handle, trackId, takeId, startBeat, endBeat) == NativeMethods.NotaResult.Ok; }++ public bool DeleteTake(int trackId, int takeId)+ { ThrowIfDisposed(); return NativeMethods.TakeDelete(_handle, trackId, takeId) == NativeMethods.NotaResult.Ok; }++ public bool FlattenTakes(int trackId)+ { ThrowIfDisposed(); return NativeMethods.TakesFlatten(_handle, trackId) == NativeMethods.NotaResult.Ok; }++ public int ClipTakeId(int trackId, int clipIndex)+ { ThrowIfDisposed(); return NativeMethods.ClipTakeId(_handle, trackId, clipIndex); }++ public int RestoreTake(int trackId, string path, int number, int group, double originBeat, double sourceOffsetFrames, long lengthFrames)+ { ThrowIfDisposed(); return NativeMethods.RestoreTake(_handle, trackId, path, number, group, originBeat, sourceOffsetFrames, lengthFrames); }++ public void SetClipTakeId(int trackId, int clipIndex, int takeId)+ { ThrowIfDisposed(); NativeMethods.ClipSetTakeId(_handle, trackId, clipIndex, takeId); }++ /// <summary>Smoke-test hook: record interleaved stereo into an audio track as a take started at+ /// <paramref name="startBeat"/> under the current loop, through the real capture path, no device.</summary>+ public bool TakeRecordTest(int trackId, float[] interleavedStereo, int frames, double startBeat)+ { ThrowIfDisposed(); return NativeMethods.TakeRecordTest(_handle, trackId, interleavedStereo, frames, startBeat) != 0; }+}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.csindex 4aa0da6b..87eacdca 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs@@ -115,6 +115,9 @@ public static class ProjectMigrations// SidechainPart and NestedSidechainDto.Part. Absent in v27 documents = -1, the whole// track — no-op.new Migration(27, _ => { }),+ // v28 -> v29: audio tracks gain Takes and audio clips TakeId (take lanes, specs/067).+ // Absent in v28 documents = no takes, every clip a plain clip — no-op.+ new Migration(28, _ => { }),};/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex a084a852..2342dcc5 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -134,6 +134,7 @@ public sealed class TrackDtopublic List<DeviceDto> Devices { get; set; } = new();public List<MidiClipDto> MidiClips { get; set; } = new();public List<AudioClipDto> AudioClips { get; set; } = new();+ public List<AudioTakeDto>? Takes { get; set; } // loop-recording take lanes (v29, specs/067)public List<SessionSlotDto> SessionSlots { get; set; } = new();/// <summary>Empty slots whose stop button was removed (scene launch leaves the track playing).</summary>public List<int>? SessionNoStop { get; set; }@@ -393,6 +394,22 @@ public sealed class AudioClipDtopublic double WarpPlayEnd { get; set; } // warped clip trim window end (0 = full, v11)public bool Reversed { get; set; } // plays back-to-front (v19); default falsepublic ClipAdsrDto? Adsr { get; set; } // ADSR amplitude shape (v20); null = identity+ public int? TakeId { get; set; } // the AudioTakeDto.Id this comp section came from (v29)++ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }+}++/// <summary>One pass of an Arrangement loop recording (v29, specs/067). `Id` is file-local:+/// it only links comp sections (<see cref="AudioClipDto.TakeId"/>) to their take.</summary>+public sealed class AudioTakeDto+{+ public int Id { get; set; }+ public int Number { get; set; } // "Take N" as shown on the lane+ public int Group { get; set; } // takes of one recording share a group+ public string Sample { get; set; } = "";+ public double OriginBeat { get; set; } // beat of the sample's frame 0+ public double SourceOffsetFrames { get; set; }+ public long LengthFrames { get; set; }[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex 21622bba..1c2c6fc5 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -37,7 +37,8 @@ public sealed class ProjectService/// chain children's sidechain keys / CC targets./// v26 (specs/048) adds Preset on instruments, devices and MIDI effects./// v27 (specs/046) adds Preview on hosted plug-ins: the picture of their window.- public const int CurrentFormatVersion = 28;+ /// v29 (specs/067) adds Takes on audio tracks and TakeId on audio clips.+ public const int CurrentFormatVersion = 29;/// <summary>Manifest file name inside the bundle folder.</summary>public const string ManifestName = "project.json";@@ -236,8 +237,21 @@ public sealed class ProjectServiceif (rel == null) continue;var dto = AudioClipState.Capture(engine, ti.Id, c, ac);dto.Sample = rel;+ int take = engine.ClipTakeId(ti.Id, c);+ if (take != 0) dto.TakeId = take;t.AudioClips.Add(dto);}+ for (int k = 0; k < engine.TakeCount(ti.Id); k++)+ {+ if (!engine.TryGetTakeInfo(ti.Id, k, out var tk)) continue;+ string? rel = RegisterSample(doc, engine, tk.SampleId, warnings);+ if (rel == null) continue;+ (t.Takes ??= new List<AudioTakeDto>()).Add(new AudioTakeDto+ {+ Id = tk.Id, Number = tk.Number, Group = tk.Group, Sample = rel,+ OriginBeat = tk.OriginBeat, SourceOffsetFrames = tk.SourceOffsetFrames, LengthFrames = tk.LengthFrames,+ });+ }}// Session slots.@@ -537,7 +551,8 @@ public sealed class ProjectService/// <summary>Rebuilds the engine from a document. Resets the engine first, so/// call after the user confirms discarding the current project. Transport is- /// NOT applied here (the UI applies it via its view-model so controls update).+ /// NOT applied here (the UI applies it via its view-model so controls update),+ /// except the tempo as a baseline for the clips./// <paramref name="bundleDir"/> resolves sample paths. Returns warnings for/// content downgraded on load.</summary>public static IReadOnlyList<string> Apply(ProjectDocument doc, IAudioEngine engine, string bundleDir)@@ -545,6 +560,10 @@ public sealed class ProjectServicevar warnings = new List<string>();engine.Reset();+ // The saved tempo before any clip (specs/067): take lanes lay their comp out on it, so a+ // section the user moved isn't mistaken for one still on its take when the UI's tempo lands.+ if (doc.Transport.Bpm > 0) engine.SetBpm(doc.Transport.Bpm);+// Pan law (specs/006) first, as the baseline rather than an undo step. A missing mixer// is a pre-v21 project: Balance, so the mix sounds as it was saved.engine.SetPanLaw(ParsePanLaw(doc.Mixer?.PanLaw, warnings), checkpoint: false);@@ -770,10 +789,29 @@ public sealed class ProjectServiceApplyControllers(c.Controllers, warnings, (ctl, pts) => engine.SetMidiClipController(id, ci, ctl, pts));}+ // Takes before clips: a comp section is re-linked to its take (and shares its buffer).+ var takeIds = new Dictionary<int, int>();+ if (t.Takes != null)+ foreach (var tk in t.Takes)+ {+ int nid = engine.RestoreTake(id, ResolveInBundle(bundleDir, tk.Sample), tk.Number, tk.Group,+ tk.OriginBeat, tk.SourceOffsetFrames, tk.LengthFrames);+ if (nid <= 0) { warnings.Add($"Couldn't reload take \"{tk.Sample}\"."); continue; }+ takeIds[tk.Id] = nid;+ for (int k = engine.TakeCount(id) - 1; k >= 0; k--)+ if (engine.TryGetTakeInfo(id, k, out var lti) && lti.Id == nid)+ {+ BundleContent.SeedSample(engine, lti.SampleId, tk.Sample);+ break;+ }+ }+foreach (var ac in t.AudioClips){int ci = AudioClipState.Restore(engine, id, ac, ResolveInBundle(bundleDir, ac.Sample));if (ci < 0) { warnings.Add($"Couldn't reload audio clip \"{ac.Sample}\"."); continue; }+ if (ac.TakeId is int oldTake && takeIds.TryGetValue(oldTake, out int newTake))+ engine.SetClipTakeId(id, ci, newTake);if (engine.TryGetAudioClipInfo(id, ci, out var lci)) BundleContent.SeedSample(engine, lci.SampleId, ac.Sample);}diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex d9a92f7b..344e51f6 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -97,6 +97,7 @@ set(NOTA_ENGINE_SOURCESsrc/engine/Engine_Devices.cppsrc/engine/Engine_Rack.cppsrc/engine/Engine_Recording.cpp+ src/engine/Engine_Takes.cppsrc/engine/Engine_Render.cppsrc/engine/Audition.cppsrc/engine/AudioThreadPool.cpp # fork-join pooldiff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 2b0dd4ad..22990dc6 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -106,6 +106,23 @@ typedef struct NotaAudioClipInfo {int32_t reversed; /* 0/1: play the region back-to-front (non-destructive) */} NotaAudioClipInfo;+/* One take of an audio loop recording (specs/067). Every take of a recording has a+ * loop-length buffer whose frame 0 sits at origin_beat; the pass recorded+ * [source_offset_frames, +length_frames) of it, which is [start_beat, +length_beats) on the+ * timeline at the current tempo. */+typedef struct NotaTakeInfo {+ int32_t id; /* engine-unique; comp clips carry it (nota_clip_take_id) */+ int32_t number; /* "Take N" on its track, recording order */+ int32_t group; /* the loop recording it came from */+ int32_t reserved;+ double origin_beat;+ double start_beat;+ double length_beats;+ double source_offset_frames;+ int64_t length_frames;+ int64_t sample_id; /* the take audio (nota_sample_read) */+} NotaTakeInfo;+/* Audio-clip ADSR amplitude shape, in played time (clip-local beats). Attack ramps* 0->1 from the clip start, decay falls 1->sustain, sustain holds, release fades to 0* over the last release_beats before the clip end (multiplying the ADS stage, so@@ -1075,6 +1092,41 @@ NOTA_API int32_t nota_track_add_audio_clip_ex(NotaEngine* engine, int32_t track_const char* path_utf8, double start_beat,double source_offset_frames, int64_t length_frames,float gain);+/* ---- Take lanes (specs/067) ---------------------------------------------- */+/* An Arrangement audio loop recording that completes a pass keeps every pass as a take; the+ * track plays its ordinary clips (the comp), and a clip made from a take carries its id.+ * Message thread only. */+NOTA_API int32_t nota_track_take_count(const NotaEngine* engine, int32_t track_id);+NOTA_API int32_t nota_track_take_info(const NotaEngine* engine, int32_t track_id, int32_t index, NotaTakeInfo* out);+/* Min/max peaks over the take's recorded range; returns the buckets written. */+NOTA_API int32_t nota_track_take_peaks(const NotaEngine* engine, int32_t track_id, int32_t index,+ float* out_min_max, int32_t max_points);+/* The take plays over [start_beat, end_beat), clamped to its range and cut on whole frames:+ * what the comp had there is carved away. One undo step; NOTA_ERR_INVALID_ARG if nothing+ * of the range lies in the take. */+NOTA_API NotaResult nota_track_take_comp(NotaEngine* engine, int32_t track_id, int32_t take_id,+ double start_beat, double end_beat);+/* Remove a take; the comp keeps playing what came from it. One undo step. */+NOTA_API NotaResult nota_track_take_delete(NotaEngine* engine, int32_t track_id, int32_t take_id);+/* Per recording: the comp sections still where their take put them (plain: unwarped,+ * unreversed, unpitched, no envelope / ADSR, active) become one clip with the same audio, and+ * the recording's takes are removed. One undo step; NOTA_ERR_INVALID_ARG without takes. */+NOTA_API NotaResult nota_track_takes_flatten(NotaEngine* engine, int32_t track_id);+/* The take an arrangement audio clip plays a section of; 0 = none. */+NOTA_API int32_t nota_clip_take_id(const NotaEngine* engine, int32_t track_id, int32_t clip_index);+/* Project load (no undo entry): restore a take from a file, returning its new id (-1 on a bad+ * track / file); tag a restored clip with a restored take's id — the clip then shares the+ * take's decoded audio when it is the same length and rate. */+NOTA_API int32_t nota_track_restore_take(NotaEngine* engine, int32_t track_id, const char* path_utf8,+ int32_t number, int32_t group, double origin_beat,+ double source_offset_frames, int64_t length_frames);+NOTA_API NotaResult nota_clip_set_take_id(NotaEngine* engine, int32_t track_id, int32_t clip_index, int32_t take_id);+/* Smoke-test hook: record `frames` of interleaved stereo into the audio track as a take+ * started at start_beat — through the capture ring, the drain and stop, under the current+ * loop — without a device. 1 = a take was recorded. */+NOTA_API int32_t nota_take_record_test(NotaEngine* engine, int32_t track_id, const float* interleaved_stereo,+ int32_t frames, double start_beat);+/* Decoded-sample metadata by id; returns 1 if found, else 0. */NOTA_API int32_t nota_sample_get_info(const NotaEngine* engine, int64_t sample_id, NotaSampleInfo* out);/* Copies up to `cap` interleaved floats into `out`; returns the total countdiff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cppindex f34fbfda..730f7541 100644--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp@@ -828,6 +828,43 @@ int32_t nota_track_add_audio_clip_ex(NotaEngine* e, int32_t track_id, const charif (!e || !path) return -1;return ENG(e)->addAudioClipEx(track_id, std::string(path), start_beat, source_offset_frames, length_frames, gain);}+int32_t nota_track_take_count(const NotaEngine* e, int32_t track_id) {+ return e ? CENG(e)->takeCount(track_id) : 0;+}+int32_t nota_track_take_info(const NotaEngine* e, int32_t track_id, int32_t index, NotaTakeInfo* out) {+ return (e && CENG(e)->takeInfo(track_id, index, out)) ? 1 : 0;+}+int32_t nota_track_take_peaks(const NotaEngine* e, int32_t track_id, int32_t index, float* out_min_max, int32_t max_points) {+ return e ? CENG(e)->takePeaks(track_id, index, out_min_max, max_points) : 0;+}+NotaResult nota_track_take_comp(NotaEngine* e, int32_t track_id, int32_t take_id, double start_beat, double end_beat) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->compTake(track_id, take_id, start_beat, end_beat) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+NotaResult nota_track_take_delete(NotaEngine* e, int32_t track_id, int32_t take_id) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->deleteTake(track_id, take_id) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+NotaResult nota_track_takes_flatten(NotaEngine* e, int32_t track_id) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->flattenTakes(track_id) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_clip_take_id(const NotaEngine* e, int32_t track_id, int32_t clip_index) {+ return e ? CENG(e)->clipTakeId(track_id, clip_index) : 0;+}+int32_t nota_track_restore_take(NotaEngine* e, int32_t track_id, const char* path, int32_t number, int32_t group,+ double origin_beat, double source_offset_frames, int64_t length_frames) {+ if (!e || !path) return -1;+ return ENG(e)->restoreTake(track_id, std::string(path), number, group, origin_beat, source_offset_frames, length_frames);+}+NotaResult nota_clip_set_take_id(NotaEngine* e, int32_t track_id, int32_t clip_index, int32_t take_id) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setClipTakeId(track_id, clip_index, take_id) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_take_record_test(NotaEngine* e, int32_t track_id, const float* interleaved_stereo, int32_t frames,+ double start_beat) {+ return (e && ENG(e)->takeRecordTest(track_id, interleaved_stereo, frames, start_beat)) ? 1 : 0;+}int32_t nota_sample_get_info(const NotaEngine* e, int64_t sample_id, NotaSampleInfo* out) {return (e && CENG(e)->sampleInfo(sample_id, out)) ? 1 : 0;}diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex 5f6f61dc..f87921bb 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -582,6 +582,10 @@ void Engine::setBpm(double bpm) {// audio thread later, so reading transport_.samplesPerBeat() here would be stale.const double devSR = transport_.sampleRate();if (bpm > 0.0 && devSR > 0.0) reconfigureAllWarpStreams(devSR * 60.0 / bpm, devSR);+ if (bpm > 0.0) {+ authoringBpm_ = bpm;+ placeTakesForTempo(); // take lanes + their comp keep one mapping (specs/067)+ }}double Engine::bpm() const {return transport_.bpm();@@ -641,6 +645,7 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {nt->setMidiFromTrackId(t.midiFromTrackId()); // MIDI routingfor (int b = 0; b < kMaxReturns; ++b) nt->setSend(b, t.send(b)); // M6-1: send levelsnt->clips = t.clips;+ nt->takes = t.takes; // take lanes (specs/067) — buffers sharednt->midiClips = t.midiClips;nt->instrument = t.instrument; // shared — voice state persistsnt->midiEffects = t.midiEffects; // shared — arp held/phase state persists@@ -782,6 +787,7 @@ bool Engine::undo() {// device (a removed look-ahead coming back, #109), so compensation follows them.if (e.graph) {publishRaw(std::move(e.graph));+ placeTakesForTempo(); // the snapshot may predate a tempo changerecomputePdc();reapplyRackMacros();reapplyCcRoutes();@@ -817,6 +823,7 @@ bool Engine::redo() {undoStack_.push_back({e.graph ? authoring_ : nullptr, e.mix});if (e.graph) {publishRaw(std::move(e.graph));+ placeTakesForTempo(); // the snapshot may predate a tempo changerecomputePdc();reapplyRackMacros();reapplyCcRoutes();diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex ed679e4d..dd3525ae 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -1308,6 +1308,20 @@ class Engine {bool audioRecordSelfTest(); // ring -> accumulate -> clip, no devicebool sessionAudioRecordSelfTest(); // ring -> slot.audio -> looped playback, no device (M5-4)+ // --- take lanes (specs/067, Engine_Takes.cpp) ---+ int32_t takeCount(int32_t trackId) const;+ bool takeInfo(int32_t trackId, int32_t index, NotaTakeInfo* out) const;+ int32_t takePeaks(int32_t trackId, int32_t index, float* outMinMax, int32_t maxPoints) const;+ bool compTake(int32_t trackId, int32_t takeId, double startBeat, double endBeat); // one undo step+ bool deleteTake(int32_t trackId, int32_t takeId); // one undo step+ bool flattenTakes(int32_t trackId); // one undo step+ int32_t clipTakeId(int32_t trackId, int32_t clipIndex) const;+ int32_t restoreTake(int32_t trackId, const std::string& path, int32_t number, int32_t group, double originBeat,+ double sourceOffsetFrames, int64_t lengthFrames); // project load, no undo entry+ bool setClipTakeId(int32_t trackId, int32_t clipIndex, int32_t takeId); // project load, no undo entry+ // A loop take through the real capture path (ring -> drain -> stop), no device.+ bool takeRecordTest(int32_t trackId, const float* interleavedStereo, int32_t frames, double startBeat);+// --- undo/redo (M6-6) ---// Every structural edit publishes a fresh, immutable Graph snapshot, so the// previous authoring_ is already a complete restore point. Undo/redo just@@ -1548,6 +1562,17 @@ class Engine {std::vector<std::shared_ptr<Graph>> retired_;std::atomic<Graph*> liveGraph_{nullptr};int32_t nextTrackId_ = 1;+ int32_t nextTakeId_ = 0; // AudioTake::id (specs/067); never reused in a session+ int32_t nextTakeGroup_ = 0; // AudioTake::group+ // The tempo setBpm last asked for. The transport only takes it on the audio thread, so+ // message-thread layout that must agree with the next block reads this instead.+ double authoringBpm_ = 120.0;+ // Beats per frame of `sampleRate` audio at authoringBpm_ (the mapping unwarped clips play+ // at; the device rate cancels out); 0 without a rate.+ double beatsPerSourceFrame(double sampleRate) const;+ // Re-place every take and the unwarped comp sections still where their take put them on+ // authoringBpm_'s mapping (after a tempo change or an undo/redo). No undo entry.+ void placeTakesForTempo();// Clip clipboard (copy/cut/paste). Holds a clone of the copied clip; kind -1 empty.int32_t clipboardKind_ = -1; // -1 none, 0 audio, 1 midi@@ -2032,6 +2057,18 @@ class Engine {size_t captureLoopFrames_ = 0; // loop length in capture-SR framessize_t captureOrigin_ = 0; // cursor position where this take started (for partial clips)double captureLoopStartBeat_ = 0.0;+ // Take lanes (specs/067): each finished loop pass, copied out of the loop buffer when the+ // cursor wraps (message thread), in a zeroed loop-length buffer holding [from, to).+ struct LoopPass {+ std::vector<float> buf;+ size_t from = 0, to = 0;+ };+ std::vector<LoopPass> capturePasses_;+ size_t capturePassFrom_ = 0; // where the open pass started recording+ void finishLoopPass(size_t to);+ // Two or more passes: keep each as a take on `nt` and comp the newest-first coverage.+ void materialiseLoopTakes(Track& nt, std::vector<LoopPass>& passes, size_t loopFrames, double loopStartBeat,+ double sampleRate);void beginCaptureLayout(); // decide linear vs loop capture at take startvoid activateLoopPunch(double atBeat); // switch capture to loop punch (start or mid-take)bool audioRecording_ = false;diff --git a/src/native/nota.engine/src/engine/Engine_Recording.cpp b/src/native/nota.engine/src/engine/Engine_Recording.cppindex ad4d07be..c4dcda4f 100644--- a/src/native/nota.engine/src/engine/Engine_Recording.cpp+++ b/src/native/nota.engine/src/engine/Engine_Recording.cpp@@ -437,6 +437,8 @@ void Engine::beginCaptureLayout() {captureWrapped_ = false;captureWritePos_ = 0;captureOrigin_ = 0;+ capturePasses_.clear();+ capturePassFrom_ = 0;if (!recordSessionAudio_ && loopEnabled_ && loopEnd_ > loopStart_) activateLoopPunch(audioRecordStartBeat_);}@@ -460,6 +462,22 @@ void Engine::activateLoopPunch(double atBeat) {captureWrapped_ = false;audioCaptureBuf_.assign(captureLoopFrames_ * 2, 0.0f); // fresh loop-region buffer, zeroedcaptureLoop_ = true;+ capturePasses_.clear();+ capturePassFrom_ = captureOrigin_;+}++// The pass that started at capturePassFrom_ ends at `to`: keep a copy as a future take+// (specs/067) before the next pass overwrites the loop buffer. Message thread (the drain).+void Engine::finishLoopPass(size_t to) {+ if (to <= capturePassFrom_ || captureLoopFrames_ == 0) return;+ LoopPass p;+ p.buf.assign(captureLoopFrames_ * 2, 0.0f);+ std::copy(audioCaptureBuf_.begin() + static_cast<std::ptrdiff_t>(capturePassFrom_ * 2),+ audioCaptureBuf_.begin() + static_cast<std::ptrdiff_t>(to * 2),+ p.buf.begin() + static_cast<std::ptrdiff_t>(capturePassFrom_ * 2));+ p.from = capturePassFrom_;+ p.to = to;+ capturePasses_.push_back(std::move(p));}double Engine::audioRecordLengthBeats() const {@@ -502,8 +520,10 @@ void Engine::drainInputQueue() {audioCaptureBuf_[idx] = captureScratch_[i * 2];audioCaptureBuf_[idx + 1] = captureScratch_[i * 2 + 1];if (++captureWritePos_ >= captureLoopFrames_) {+ finishLoopPass(captureLoopFrames_);captureWritePos_ = 0;captureWrapped_ = true;+ capturePassFrom_ = 0;}}return;@@ -598,6 +618,24 @@ void Engine::stopAudioRecording() {const size_t loopReached = captureWritePos_;const size_t loopFrames = captureLoopFrames_;const double loopStartBeat = captureLoopStartBeat_;+ std::vector<LoopPass> passes;+ if (loopTake) {+ finishLoopPass(loopReached); // the open pass, up to where recording stopped+ passes = std::move(capturePasses_);+ }+ capturePasses_.clear();++ // Two or more passes keep every pass as a take (specs/067). A session take never loops here.+ if (loopTake && passes.size() >= 2 && !(recordSessionAudio_ && recordSessionScene_ >= 0)) {+ const double sr = audioRecordSampleRate_ > 0 ? audioRecordSampleRate_ : transport_.sampleRate();+ audioCaptureBuf_.clear();+ captureWritePos_ = 0;+ captureLoop_ = false;+ auto nt = cloneTrack(*old);+ materialiseLoopTakes(*nt, passes, loopFrames, loopStartBeat, sr);+ republishWithTrack(trackId, nt);+ return;+ }auto sample = std::make_shared<SampleBuffer>();sample->channels = 2;@@ -680,6 +718,62 @@ void Engine::stopAudioRecording() {republishWithTrack(trackId, nt);}+// Every pass becomes a take (one new group, numbers continuing on the track), and the comp is+// what the in-place loop buffer would have held: each frame from the newest pass that recorded+// it. The loop region is carved as a wrapped loop take always was.+void Engine::materialiseLoopTakes(Track& nt, std::vector<LoopPass>& passes, size_t loopFrames, double loopStartBeat,+ double sampleRate) {+ const double bpf = beatsPerSourceFrame(sampleRate);+ const int32_t group = ++nextTakeGroup_;+ int32_t number = 0;+ for (const auto& k : nt.takes) number = std::max(number, k.number);++ std::vector<AudioTake> takes;+ takes.reserve(passes.size());+ for (auto& p : passes) {+ auto sb = std::make_shared<SampleBuffer>();+ sb->channels = 2;+ sb->frames = static_cast<int64_t>(loopFrames);+ sb->sourceSampleRate = sampleRate;+ sb->samples = std::move(p.buf);+ AudioTake k;+ k.sample = std::move(sb);+ k.id = ++nextTakeId_;+ k.number = ++number;+ k.group = group;+ k.originBeat = loopStartBeat;+ k.sourceOffsetFrames = static_cast<double>(p.from);+ k.lengthFrames = static_cast<int64_t>(p.to - p.from);+ k.beatsPerFrame = bpf;+ takes.push_back(std::move(k));+ }++ overwriteAudioClipsInRange(nt.clips, loopStartBeat, loopStartBeat + static_cast<double>(loopFrames) * bpf);+ std::vector<std::pair<size_t, size_t>> open{{0, loopFrames}}; // loop frames no newer pass covers yet+ for (size_t i = passes.size(); i-- > 0 && !open.empty();) {+ const size_t from = passes[i].from, to = passes[i].to;+ std::vector<std::pair<size_t, size_t>> rest;+ for (auto [a, b] : open) {+ const size_t s = std::max(a, from), e = std::min(b, to);+ if (s >= e) {+ rest.emplace_back(a, b);+ continue;+ }+ AudioClip clip;+ clip.sample = takes[i].sample;+ clip.startBeat = loopStartBeat + static_cast<double>(s) * bpf;+ clip.sourceOffsetFrames = static_cast<double>(s);+ clip.lengthFrames = static_cast<int64_t>(e - s);+ clip.takeId = takes[i].id;+ nt.clips.push_back(std::move(clip));+ if (a < s) rest.emplace_back(a, s);+ if (e < b) rest.emplace_back(e, b);+ }+ open = std::move(rest);+ }+ for (auto& k : takes) nt.takes.push_back(std::move(k));+}+double Engine::latencyCompensatedStart(double startBeat, int32_t latencyFrames, double samplesPerBeat,double* trimFrames) {if (trimFrames) *trimFrames = 0.0;diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex fbb17207..c52afa06 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -1653,17 +1653,9 @@ void Engine::mixAudioClip(float l = static_cast<float>(l0 + (l1 - l0) * frac) * clip.gain * extraGain;float r = static_cast<float>(r0 + (r1 - r0) * frac) * clip.gain * extraGain;// Short edge fade (~3 ms) so a clip that starts/ends mid-waveform doesn't click.- const double edge = std::min(3.0 * sr / 1000.0, clipDeviceLen * 0.5);- if (edge > 1.0) {- const double into = p - startSamples;- double eg = 1.0;- if (into < edge) eg = into / edge;- else if (into > clipDeviceLen - edge)- eg = (clipDeviceLen - into) / edge;- eg = std::clamp(eg, 0.0, 1.0);- l *= (float)eg;- r *= (float)eg;- }+ const float eg = static_cast<float>(audioClipEdgeGain(p - startSamples, clipDeviceLen, sr));+ l *= eg;+ r *= eg;applyEnv(p, l, r);dst[i * 2] += l;dst[i * 2 + 1] += r;diff --git a/src/native/nota.engine/src/engine/Engine_Takes.cpp b/src/native/nota.engine/src/engine/Engine_Takes.cppnew file mode 100644index 00000000..3ef1ac07--- /dev/null+++ b/src/native/nota.engine/src/engine/Engine_Takes.cpp@@ -0,0 +1,329 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Take lanes (specs/067): the passes of an Arrangement audio loop recording, kept on the track+// so they can be comped. Takes are graph data, so every edit here is a message-thread clone ++// republish (AR-5) and undo comes from the snapshot history. The comp is the track's ordinary+// clips; a section made from a take carries the take's id, which only the lanes' highlight and+// flatten read — the audio thread plays clips as always. A take and the sections still where+// it put them share one beat mapping (AudioTake::beatsPerFrame), re-placed on a tempo change+// so the comp stays one recording that meets frame to frame and the lanes keep matching it.++#include "Engine.h"+#include "media/AudioFile.h"++#include <algorithm>+#include <cmath>++namespace nota {++namespace {++const AudioTake* findTake(const Track& t, int32_t takeId) {+ for (const auto& k : t.takes)+ if (k.id == takeId) return &k;+ return nullptr;+}++// A section still where its take put it starts where the take plays its first frame.+bool atTakePosition(const AudioClip& c, const AudioTake& k) {+ return std::abs(c.startBeat - (k.originBeat + c.sourceOffsetFrames * k.beatsPerFrame)) < 1e-6;+}++} // namespace++double Engine::beatsPerSourceFrame(double sampleRate) const {+ const double sr = sampleRate > 0.0 ? sampleRate : transport_.sampleRate();+ return sr > 0.0 && authoringBpm_ > 0.0 ? authoringBpm_ / 60.0 / sr : 0.0;+}++void Engine::placeTakesForTempo() {+ if (!authoring_) return;+ auto stale = [&](const Track& t) {+ for (const auto& k : t.takes)+ if (k.sample && k.beatsPerFrame != beatsPerSourceFrame(k.sample->sourceSampleRate)) return true;+ return false;+ };+ // Runs after every undo/redo: no new graph unless a take is actually off its tempo.+ if (std::none_of(authoring_->tracks.begin(), authoring_->tracks.end(),+ [&](const auto& t) { return stale(*t); }))+ return;+ bool any = false;+ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, *authoring_);+ g->tracks.reserve(authoring_->tracks.size());+ for (auto& t : authoring_->tracks) {+ if (!stale(*t)) {+ g->tracks.push_back(t);+ continue;+ }+ auto nt = cloneTrack(*t);+ // Warped sections already follow the tempo from where they start; moved ones stay put.+ for (auto& c : nt->clips) {+ const AudioTake* k = c.takeId != 0 && !c.warpEnabled ? findTake(*nt, c.takeId) : nullptr;+ if (k && k->sample && atTakePosition(c, *k))+ c.startBeat = k->originBeat + c.sourceOffsetFrames * beatsPerSourceFrame(k->sample->sourceSampleRate);+ }+ for (auto& k : nt->takes)+ if (k.sample) k.beatsPerFrame = beatsPerSourceFrame(k.sample->sourceSampleRate);+ g->tracks.push_back(std::move(nt));+ any = true;+ }+ if (any) publishRaw(std::move(g));+}++int32_t Engine::takeCount(int32_t trackId) const {+ auto t = findTrackAuthoring(trackId);+ return t ? static_cast<int32_t>(t->takes.size()) : 0;+}++bool Engine::takeInfo(int32_t trackId, int32_t index, NotaTakeInfo* out) const {+ auto t = findTrackAuthoring(trackId);+ if (!t || !out || index < 0 || index >= static_cast<int32_t>(t->takes.size())) return false;+ const AudioTake& k = t->takes[index];+ const double bpf = k.beatsPerFrame;+ *out = NotaTakeInfo{};+ out->id = k.id;+ out->number = k.number;+ out->group = k.group;+ out->origin_beat = k.originBeat;+ out->start_beat = k.originBeat + k.sourceOffsetFrames * bpf;+ out->length_beats = static_cast<double>(k.lengthFrames) * bpf;+ out->source_offset_frames = k.sourceOffsetFrames;+ out->length_frames = k.lengthFrames;+ out->sample_id = k.sample ? k.sample->id : 0;+ return true;+}++int32_t Engine::takePeaks(int32_t trackId, int32_t index, float* outMinMax, int32_t maxPoints) const {+ auto t = findTrackAuthoring(trackId);+ if (!t || !outMinMax || maxPoints <= 0 || index < 0 || index >= static_cast<int32_t>(t->takes.size())) return 0;+ const AudioTake& k = t->takes[index];+ if (!k.sample || k.lengthFrames <= 0) return 0;+ const int64_t base = static_cast<int64_t>(k.sourceOffsetFrames);+ const int32_t buckets = static_cast<int32_t>(std::min<int64_t>(maxPoints, k.lengthFrames));+ const int64_t per = k.lengthFrames / buckets;+ for (int32_t b = 0; b < buckets; ++b) {+ const int64_t begin = base + b * per;+ float mn, mx;+ k.sample->peakRange(begin, begin + per, mn, mx);+ outMinMax[b * 2] = mn;+ outMinMax[b * 2 + 1] = mx;+ }+ return buckets;+}++bool Engine::compTake(int32_t trackId, int32_t takeId, double startBeat, double endBeat) {+ auto old = findTrackAuthoring(trackId);+ if (!old) return false;+ const AudioTake* k = findTake(*old, takeId);+ if (!k || !k->sample) return false;+ const double bpf = k->beatsPerFrame;+ if (bpf <= 0.0) return false;+ // Whole frames of the take, clamped to what the pass recorded: sections from one+ // recording then meet frame to frame, so a comp has no gaps or overlaps at its seams.+ const double lo = k->sourceOffsetFrames, hi = k->sourceOffsetFrames + static_cast<double>(k->lengthFrames);+ const double f0 = std::clamp(std::round((std::min(startBeat, endBeat) - k->originBeat) / bpf), lo, hi);+ const double f1 = std::clamp(std::round((std::max(startBeat, endBeat) - k->originBeat) / bpf), lo, hi);+ if (f1 - f0 < 1.0) return false;++ auto nt = cloneTrack(*old);+ const double ns = k->originBeat + f0 * bpf, ne = k->originBeat + f1 * bpf;+ overwriteAudioClipsInRange(nt->clips, ns, ne);+ AudioClip clip;+ clip.sample = k->sample;+ clip.startBeat = ns;+ clip.sourceOffsetFrames = f0;+ clip.lengthFrames = static_cast<int64_t>(f1 - f0);+ clip.takeId = k->id;+ nt->clips.push_back(std::move(clip));+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::deleteTake(int32_t trackId, int32_t takeId) {+ auto old = findTrackAuthoring(trackId);+ if (!old || !findTake(*old, takeId)) return false;+ auto nt = cloneTrack(*old);+ nt->takes.erase(std::remove_if(nt->takes.begin(), nt->takes.end(), [&](const AudioTake& k) { return k.id == takeId; }),+ nt->takes.end());+ for (auto& c : nt->clips)+ if (c.takeId == takeId) c.takeId = 0; // keeps playing, no longer a section of a take+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::flattenTakes(int32_t trackId) {+ auto old = findTrackAuthoring(trackId);+ if (!old || old->takes.empty()) return false;+ auto nt = cloneTrack(*old);++ std::vector<int32_t> groups;+ for (const auto& k : nt->takes)+ if (std::find(groups.begin(), groups.end(), k.group) == groups.end()) groups.push_back(k.group);++ for (int32_t g : groups) {+ const AudioTake* first = nullptr;+ for (const auto& k : nt->takes)+ if (k.group == g && k.sample) {+ first = &k;+ break;+ }+ auto inGroup = [&](int32_t takeId) {+ for (const auto& k : nt->takes)+ if (k.id == takeId) return k.group == g;+ return false;+ };+ if (!first) continue;+ const SampleBuffer& ref = *first->sample;+ const double origin = first->originBeat;+ const double bpf = first->beatsPerFrame;+ const int64_t frames = ref.frames;+ const int32_t ch = ref.channels;++ // A section merges when it is still exactly where its take put it and plays its+ // frames as they are; anything else was edited into a clip of its own and stays one.+ auto plain = [&](const AudioClip& c) {+ if (!c.sample || c.sample->frames != frames || c.sample->channels != ch ||+ c.sample->sourceSampleRate != ref.sourceSampleRate)+ return false;+ if (!c.active || c.warpEnabled || c.reversed || c.pitchSemitones != 0.0f) return false;+ if (!c.volumeEnvelope.points.empty() || !c.panEnvelope.points.empty() || !c.adsr.isIdentity()) return false;+ const double off = std::round(c.sourceOffsetFrames);+ const int64_t len = c.effectiveLength();+ if (off < 0.0 || len <= 0 || static_cast<int64_t>(off) + len > frames) return false;+ return bpf > 0.0 && std::abs(c.startBeat - (origin + off * bpf)) < 1e-6;+ };++ std::vector<const AudioClip*> merged; // into nt->clips, which `kept` leaves them in+ int64_t lo = frames, hi = 0;+ std::vector<AudioClip> kept;+ kept.reserve(nt->clips.size());+ for (auto& c : nt->clips) {+ if (c.takeId == 0 || !inGroup(c.takeId)) {+ kept.push_back(std::move(c));+ continue;+ }+ if (!plain(c)) {+ c.takeId = 0;+ kept.push_back(std::move(c));+ continue;+ }+ const int64_t off = static_cast<int64_t>(std::round(c.sourceOffsetFrames));+ lo = std::min(lo, off);+ hi = std::max(hi, off + c.effectiveLength());+ merged.push_back(&c);+ }++ // Each section keeps the edge fades it played with, so the joins sound as the comp did;+ // only where the merged clip's own edge falls does its playback fade take over.+ std::vector<float> buf;+ if (hi > lo) buf.assign(static_cast<size_t>(frames) * ch, 0.0f);+ const double devSR = transport_.sampleRate();+ const double devPerFrame = devSR > 0.0 && ref.sourceSampleRate > 0.0 ? devSR / ref.sourceSampleRate : 0.0;+ for (const AudioClip* c : merged) {+ const int64_t off = static_cast<int64_t>(std::round(c->sourceOffsetFrames));+ const int64_t len = c->effectiveLength();+ const double devLen = static_cast<double>(len) * devPerFrame;+ const bool fadeIn = off != lo, fadeOut = off + len != hi;+ const float* src = c->sample->samples.data() + off * ch;+ float* dst = buf.data() + off * ch;+ for (int64_t j = 0; j < len; ++j) {+ const double into = static_cast<double>(j) * devPerFrame;+ const bool fade = into < devLen * 0.5 ? fadeIn : fadeOut;+ const float g = fade ? c->gain * static_cast<float>(audioClipEdgeGain(into, devLen, devSR)) : c->gain;+ for (int32_t m = 0; m < ch; ++m) dst[j * ch + m] += src[j * ch + m] * g;+ }+ }+ nt->clips = std::move(kept);+ if (hi > lo) {+ auto sb = std::make_shared<SampleBuffer>();+ sb->channels = ch;+ sb->frames = frames;+ sb->sourceSampleRate = ref.sourceSampleRate;+ sb->samples = std::move(buf);+ AudioClip clip;+ clip.sample = std::move(sb);+ clip.startBeat = origin + static_cast<double>(lo) * bpf;+ clip.sourceOffsetFrames = static_cast<double>(lo);+ clip.lengthFrames = hi - lo;+ nt->clips.push_back(std::move(clip));+ }+ nt->takes.erase(std::remove_if(nt->takes.begin(), nt->takes.end(), [&](const AudioTake& k) { return k.group == g; }),+ nt->takes.end());+ }+ republishWithTrack(trackId, nt);+ return true;+}++int32_t Engine::clipTakeId(int32_t trackId, int32_t clipIndex) const {+ auto t = findTrackAuthoring(trackId);+ if (!t || clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return 0;+ return t->clips[clipIndex].takeId;+}++int32_t Engine::restoreTake(int32_t trackId, const std::string& path, int32_t number, int32_t group, double originBeat,+ double sourceOffsetFrames, int64_t lengthFrames) {+ auto old = findTrackAuthoring(trackId);+ if (!old || old->type() != TrackType::Audio) return -1;+ auto sample = decodeAudioFile(path);+ if (!sample || sample->empty()) return -1;+ auto nt = cloneTrack(*old);+ AudioTake k;+ k.sample = std::move(sample);+ k.id = ++nextTakeId_;+ k.number = number;+ k.group = group;+ nextTakeGroup_ = std::max(nextTakeGroup_, group);+ k.originBeat = originBeat;+ k.sourceOffsetFrames = std::clamp(sourceOffsetFrames, 0.0, static_cast<double>(k.sample->frames));+ k.lengthFrames = std::clamp<int64_t>(lengthFrames, 0, k.sample->frames - static_cast<int64_t>(k.sourceOffsetFrames));+ k.beatsPerFrame = beatsPerSourceFrame(k.sample->sourceSampleRate);+ nt->takes.push_back(std::move(k));+ republishWithTrackRaw(trackId, nt);+ return nextTakeId_;+}++bool Engine::setClipTakeId(int32_t trackId, int32_t clipIndex, int32_t takeId) {+ auto old = findTrackAuthoring(trackId);+ if (!old || clipIndex < 0 || clipIndex >= static_cast<int32_t>(old->clips.size())) return false;+ auto nt = cloneTrack(*old);+ AudioClip& c = nt->clips[clipIndex];+ c.takeId = takeId;+ // A reopened comp section decodes its own copy of the take's file: share the take's buffer+ // instead, as a freshly recorded comp does.+ if (const AudioTake* k = findTake(*nt, takeId); k && k->sample && c.sample && c.sample != k->sample &&+ c.sample->frames == k->sample->frames &&+ c.sample->channels == k->sample->channels &&+ c.sample->sourceSampleRate == k->sample->sourceSampleRate)+ c.sample = k->sample;+ republishWithTrackRaw(trackId, nt);+ return true;+}++bool Engine::takeRecordTest(int32_t trackId, const float* interleavedStereo, int32_t frames, double startBeat) {+ auto t = findTrackAuthoring(trackId);+ if (!t || t->type() != TrackType::Audio || !interleavedStereo || frames <= 0 || audioRecording_) return false;+ const size_t before = t->takes.size();+ audioCaptureBuf_.clear();+ captureWritePos_ = 0;+ captureLoop_ = false;+ captureChannels_ = Track::kInputStereo;+ inputDroppedFrames_.store(0, std::memory_order_relaxed);+ audioRecordTrackId_ = trackId;+ audioRecordStartBeat_ = startBeat;+ audioRecordSampleRate_ = transport_.sampleRate();+ audioRecordLatencyFrames_ = 0;+ beginCaptureLayout();+ audioRecording_ = true;+ constexpr int32_t kChunk = 1024; // well inside the capture ring, drained like poll() would+ for (int32_t at = 0; at < frames; at += kChunk) {+ pushInputFramesForTest(interleavedStereo + static_cast<size_t>(at) * 2, std::min(kChunk, frames - at));+ drainInputQueue();+ }+ stopAudioRecording();+ auto nt = findTrackAuthoring(trackId);+ return nt && (nt->takes.size() > before || !nt->clips.empty());+}++} // namespace notadiff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cppindex cff78391..ff7f52c6 100644--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp@@ -30,6 +30,8 @@ std::shared_ptr<SampleBuffer> Engine::findSampleById(int64_t sampleId) const {for (auto& t : authoring_->tracks) {for (auto& c : t->clips)if (c.sample && c.sample->id == sampleId) return c.sample;+ for (auto& k : t->takes)+ if (k.sample && k.sample->id == sampleId) return k.sample;for (auto& sl : t->sessionSlots)if (sl.audio.sample && sl.audio.sample->id == sampleId) return sl.audio.sample;if (auto* smp = dynamic_cast<Sampler*>(t->instrument.get()))@@ -3126,6 +3128,7 @@ std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId, bfor (int b = 0; b < kMaxReturns; ++b) nt->setSend(b, src.send(b));if (withContent) {nt->clips = src.clips; // sample buffers are shared_ptr (immutable) — fine+ nt->takes = src.takes;nt->midiClips = src.midiClips;nt->sessionSlots = src.sessionSlots;nt->automation = src.automation;diff --git a/src/native/nota.engine/src/engine/Track.h b/src/native/nota.engine/src/engine/Track.hindex a2801620..ca8292ad 100644--- a/src/native/nota.engine/src/engine/Track.h+++ b/src/native/nota.engine/src/engine/Track.h@@ -94,6 +94,9 @@ struct AudioClip {AutomationLane panEnvelope;// ADSR amplitude shape (identity by default). Applied per sample with the envelopes.ClipAdsr adsr;+ // The take this clip plays a section of (specs/067), 0 = none. Drives the take lanes'+ // highlight and flatten only; playback never looks at it.+ int32_t takeId = 0;int64_t effectiveLength() const;// Played warp window (beats). Default (0/0) is the whole warp [0, warpBeats].@@ -104,6 +107,36 @@ struct AudioClip {double pitchRatio() const { return std::pow(2.0, static_cast<double>(pitchSemitones) / 12.0); }};+// The short edge fade (~3 ms) an unwarped clip plays at both ends, so one that starts or ends+// mid-waveform doesn't click: the gain `into` device frames into a clip `len` device frames+// long at device rate `sr`. Flatten (specs/067) bakes the same fades into the joins it removes.+inline double audioClipEdgeGain(double into, double len, double sr) {+ const double edge = std::min(3.0 * sr / 1000.0, len * 0.5);+ if (edge <= 1.0) return 1.0;+ double eg = 1.0;+ if (into < edge) eg = into / edge;+ else if (into > len - edge)+ eg = (len - into) / edge;+ return std::clamp(eg, 0.0, 1.0);+}++// One pass of an Arrangement audio loop recording (specs/067), kept so it can be comped.+// Every take of one recording has a loop-length buffer whose frame 0 sits at the loop start+// (originBeat), so a frame inside a take is the same point of the loop in every take. The+// track plays ordinary clips (the comp); a take is never played directly.+struct AudioTake {+ std::shared_ptr<SampleBuffer> sample;+ int32_t id = 0; // engine-unique; comp clips carry it in AudioClip::takeId+ int32_t number = 0; // "Take N" on its track, in recording order+ int32_t group = 0; // the loop recording it came from+ double originBeat = 0.0;+ double sourceOffsetFrames = 0.0; // the range the pass recorded, inside `sample`+ int64_t lengthFrames = 0;+ // Beats per frame of `sample` that the take and its comp sections are laid out with: the+ // tempo's mapping when they were placed. A tempo change re-places both (placeTakesForTempo).+ double beatsPerFrame = 0.0;+};+// A Session-view clip slot (M5). One per scene on each track. Holds a MIDI clip// (instrument tracks) or a captured audio take (audio tracks, M5-4); the type is// implied by the track type. Immutable in a snapshot.@@ -278,6 +311,7 @@ class Track {// Immutable after publish (only touched while building a snapshot).std::vector<AudioClip> clips; // audio tracks+ std::vector<AudioTake> takes; // audio loop-recording passes (specs/067), recording orderstd::vector<MidiClip> midiClips; // instrument tracksstd::vector<SessionSlot> sessionSlots; // Session view, one per scene (M5)std::vector<TrackLane> automation; // parameter automation lanes (M9)diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex d79a3baf..c6c79b67 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -644,6 +644,14 @@ if (args.Length >= 1 && args[0] == "--live-record")Console.WriteLine(failures == 0 ? "LIVE RECORD PASSED" : $"LIVE RECORD FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Take lanes alone (fast iteration): `--takes`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--takes")+{+ Console.WriteLine("-- take lanes --");+ foreach (var (ok, label) in TakeLaneTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "TAKES PASSED" : $"TAKES FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// MIDI controllers alone (fast iteration): `--midi-ctl`. Also part of the full run.if (args.Length >= 1 && args[0] == "--midi-ctl"){@@ -13193,8 +13201,8 @@ Console.WriteLine("-- simultaneous instrument + audio record --");}// ============ loop recording punches the loop region =======================-// Loop on → each pass wraps and overwrites the loop region in place; the take is bounded-// to the loop and placed at its start. The playhead wraps with the loop (stays inside it).+// Loop on → each pass is kept as a take (specs/067). The comp covers the loop: the newest+// pass where it recorded, earlier passes behind it. The playhead wraps with the loop.Console.WriteLine("-- loop recording (punch) --");{using var le = new NotaEngine();@@ -13215,10 +13223,17 @@ Console.WriteLine("-- loop recording (punch) --");le.SetRecording(false);le.Poll();le.TryGetTrackInfo(1, out var lti);- Check(lti.ClipCount == 1, $"loop record makes one clip ({lti.ClipCount})");- le.TryGetClipInfo(lr, 0, out var lci);- Check(Math.Abs(lci.StartBeat) < 1e-6, $"take placed at the loop start ({lci.StartBeat:F2})");- Check(Math.Abs(lci.LengthBeats - 2.0) < 0.3, $"take is bounded to the loop (~2 beats) ({lci.LengthBeats:F2})");+ double lLo = double.MaxValue, lHi = 0;+ for (int c = 0; c < lti.ClipCount; c++)+ if (le.TryGetClipInfo(lr, c, out var ci))+ {+ lLo = Math.Min(lLo, ci.StartBeat);+ lHi = Math.Max(lHi, ci.StartBeat + ci.LengthBeats);+ }+ Check(lti.ClipCount >= 2 && le.TakeCount(lr) >= 2,+ $"loop record keeps a take per pass ({lti.ClipCount} comp clips, {le.TakeCount(lr)} takes)");+ Check(Math.Abs(lLo) < 1e-6 && Math.Abs(lHi - 2.0) < 0.3,+ $"comp covers the loop [{lLo:F2}, {lHi:F2}]");le.SetTrackMute(li, true);le.SetLoop(false, 0, 0); le.Seek(0); le.Play();var lpb = new float[8192 * 2]; le.RenderOffline(lpb, 8192); le.StopTransport();@@ -13244,9 +13259,16 @@ Console.WriteLine("-- loop enabled mid-record --");for (int b = 0; b < 60; b++) { me.RenderOffline(mcap, 2048); me.Poll(); }me.SetRecording(false);me.Poll();- me.TryGetClipInfo(mr, 0, out var mci);- Check(Math.Abs(mci.StartBeat) < 1e-6 && Math.Abs(mci.LengthBeats - 2.0) < 0.3,- $"mid-record loop switches to punch (start={mci.StartBeat:F2} len={mci.LengthBeats:F2})");+ me.TryGetTrackInfo(1, out var mti);+ double mLo = double.MaxValue, mHi = 0;+ for (int c = 0; c < mti.ClipCount; c++)+ if (me.TryGetClipInfo(mr, c, out var mci))+ {+ mLo = Math.Min(mLo, mci.StartBeat);+ mHi = Math.Max(mHi, mci.StartBeat + mci.LengthBeats);+ }+ Check(mti.ClipCount >= 2 && me.TakeCount(mr) >= 2 && Math.Abs(mLo) < 1e-6 && Math.Abs(mHi - 2.0) < 0.3,+ $"mid-record loop switches to punch (takes {me.TakeCount(mr)}, comp [{mLo:F2}, {mHi:F2}])");}// ============ overwrite / comp: a dropped clip carves what it lands on ======@@ -15236,6 +15258,8 @@ Console.WriteLine("-- loop seam --");foreach (var (ok, label) in LoopSeamTests.Run()) Check(ok, label);Console.WriteLine("-- loop record mode --");foreach (var (ok, label) in LoopRecordModeTests.Run()) Check(ok, label);+Console.WriteLine("-- take lanes --");+foreach (var (ok, label) in TakeLaneTests.Run()) Check(ok, label);Console.WriteLine("-- session launch + record input --");foreach (var (ok, label) in SessionInputTests.Run()) Check(ok, label);Console.WriteLine("-- tempo follow --");diff --git a/tests/Nota.SmokeTest/TakeLaneTests.cs b/tests/Nota.SmokeTest/TakeLaneTests.csnew file mode 100644index 00000000..aa762c7f--- /dev/null+++ b/tests/Nota.SmokeTest/TakeLaneTests.cs@@ -0,0 +1,331 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Take lanes (#187, specs/067-take-lanes-comping): an Arrangement audio recording that wraps+// the loop keeps every pass as a take; the default comp sounds exactly as the single loop+// buffer did; comping a swiped range, deleting a take and flattening are one undo step each;+// flatten sounds as the comp did; a tempo change keeps the takes and their comp on one+// mapping; and takes + comp survive save/reopen.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class TakeLaneTests+{+ private const double Sr = 48000.0;+ private const int Fpb = 24000; // frames per beat at 120 BPM+ private const int Loop = 4 * Fpb; // 1-bar loop, beats 0–4++ public static IEnumerable<(bool, string)> Run()+ {+ foreach (var r in ThreePasses()) yield return r;+ foreach (var r in TempoChange()) yield return r;+ foreach (var r in NoTakes()) yield return r;+ foreach (var r in SaveReopen()) yield return r;+ }++ // Recording starts at beat 1 and runs 72000 + 96000 + 30000 frames: pass 0 covers loop+ // frames [24000, 96000), pass 1 the whole loop, pass 2 [0, 30000).+ private const int RecFrames = 72000 + 96000 + 30000;++ private static float Value(int pass, int loopFrame) => (pass + 1) * 0.1f + (loopFrame % 1000) * 1e-5f;++ private static float Expected(int[] passAt, int f) => passAt[f] < 0 ? float.NaN : Value(passAt[f], f);++ private static NotaEngine Rig(out int track)+ {+ var e = new NotaEngine();+ e.SetBpm(120);+ e.SetMetronome(false);+ e.SetLoop(true, 0.0, 4.0);+ e.RenderOffline(new float[256 * 2], 256, Sr);+ track = e.AddAudioTrack();+ return e;+ }++ private static bool Record(NotaEngine e, int track, int frames, double startBeat)+ {+ var buf = new float[frames * 2];+ int origin = (int)Math.Round(startBeat * Fpb);+ for (int n = 0; n < frames; n++)+ {+ int g = origin + n;+ float v = Value(g / Loop, g % Loop);+ buf[n * 2] = v;+ buf[n * 2 + 1] = -v;+ }+ return e.TakeRecordTest(track, buf, frames, startBeat);+ }++ // What the track's clips play over the loop, frame by frame (left channel; NaN = nothing,+ // +inf = two clips on one frame), with the right channel checked as the mirror.+ private static float[] Timeline(NotaEngine e, int track, out bool mirrored)+ {+ var tl = new float[Loop];+ Array.Fill(tl, float.NaN);+ mirrored = true;+ int count = ClipCount(e, track);+ for (int c = 0; c < count; c++)+ {+ if (!e.TryGetAudioClipInfo(track, c, out var ac) || !e.TryGetSampleInfo(ac.SampleId, out var si)) continue;+ var data = e.ReadSample(ac.SampleId);+ int ch = si.Channels;+ long len = ac.LengthFrames > 0 ? ac.LengthFrames : si.Frames - (long)ac.SourceOffsetFrames;+ int s = (int)Math.Round(ac.StartBeat * Fpb), off = (int)Math.Round(ac.SourceOffsetFrames);+ for (int j = 0; j < len; j++)+ {+ int f = s + j;+ if (f < 0 || f >= Loop) continue;+ float l = data[(off + j) * ch] * ac.Gain;+ float r = ch > 1 ? data[(off + j) * ch + 1] * ac.Gain : -l;+ tl[f] = float.IsNaN(tl[f]) ? l : float.PositiveInfinity;+ if (r != -l) mirrored = false;+ }+ }+ return tl;+ }++ // What the engine plays over the loop, left channel, rendered from beat 0 with the+ // playback edge fades every clip gets.+ private static float[] Render(NotaEngine e)+ {+ var buf = new float[256 * 2];+ e.StopTransport();+ e.Seek(0.0);+ e.RenderOffline(buf, 256, Sr); // drain the stop / seek+ e.RenderOffline(buf, 256, Sr);+ e.Play();+ var outL = new float[Loop];+ for (int done = 0; done < Loop; done += 256)+ {+ e.RenderOffline(buf, 256, Sr);+ for (int i = 0; i < 256; i++) outL[done + i] = buf[i * 2];+ }+ e.StopTransport();+ return outL;+ }++ private static int RenderMismatch(float[] a, float[] b)+ {+ for (int f = 0; f < Loop; f++)+ if (Math.Abs(a[f] - b[f]) > 1e-5f) return f;+ return -1;+ }++ private static int ClipCount(NotaEngine e, int track)+ {+ for (int i = 0; i < e.TrackCount; i++)+ if (e.TryGetTrackInfo(i, out var ti) && ti.Id == track) return ti.ClipCount;+ return 0;+ }++ private static int Mismatch(float[] tl, int[] passAt)+ {+ for (int f = 0; f < Loop; f++)+ {+ float x = Expected(passAt, f);+ if (!(float.IsNaN(x) ? float.IsNaN(tl[f]) : tl[f] == x)) return f;+ }+ return -1;+ }++ private static int[] DefaultComp()+ {+ var p = new int[Loop];+ for (int f = 0; f < Loop; f++) p[f] = f < 30000 ? 2 : 1;+ return p;+ }++ private static NotaTakeInfo[] Takes(NotaEngine e, int track)+ {+ var list = new List<NotaTakeInfo>();+ for (int k = 0; k < e.TakeCount(track); k++)+ if (e.TryGetTakeInfo(track, k, out var t)) list.Add(t);+ return list.ToArray();+ }++ private static IEnumerable<(bool, string)> ThreePasses()+ {+ using var e = Rig(out int track);+ yield return (Record(e, track, RecFrames, 1.0), "a 3-pass loop recording lands on the track");++ var takes = Takes(e, track);+ yield return (takes.Length == 3 && takes.Select(t => t.Number).SequenceEqual(new[] { 1, 2, 3 }),+ $"every loop pass is a take, numbered 1..3 ({takes.Length})");+ yield return (takes.Length == 3 && takes.All(t => t.Group == takes[0].Group && t.OriginBeat == 0.0 && t.LengthFrames > 0),+ "the takes share one group, frame 0 at the loop start");+ yield return (takes.Length == 3+ && takes[0].SourceOffsetFrames == 24000 && takes[0].LengthFrames == 72000+ && takes[1].SourceOffsetFrames == 0 && takes[1].LengthFrames == Loop+ && takes[2].SourceOffsetFrames == 0 && takes[2].LengthFrames == 30000,+ "partial first and last passes keep only what they recorded");+ yield return (takes.Length == 3 && Math.Abs(takes[0].StartBeat - 1.0) < 1e-9 && Math.Abs(takes[2].LengthBeats - 1.25) < 1e-9,+ "take windows in beats match the recorded range");+ if (takes.Length != 3) yield break;++ var passAt = DefaultComp();+ var tl = Timeline(e, track, out bool mirrored);+ int bad = Mismatch(tl, passAt);+ yield return (bad < 0 && mirrored, $"default comp is sample-exact: the newest pass on every frame (first mismatch {bad})");+ int clips = ClipCount(e, track);+ bool allTagged = Enumerable.Range(0, clips).All(c => e.ClipTakeId(track, c) != 0);+ yield return (clips == 2 && allTagged, $"default comp is two take sections ({clips})");++ // Swipe take 1 over beats 1.5–2.5.+ int clipsBefore = clips;+ yield return (e.CompTake(track, takes[0].Id, 1.5, 2.5), "comp a swiped range of take 1");+ var compAt = (int[])passAt.Clone();+ for (int f = 36000; f < 60000; f++) compAt[f] = 0;+ bad = Mismatch(Timeline(e, track, out _), compAt);+ yield return (bad < 0, $"the comped range plays take 1, the rest is unchanged (first mismatch {bad})");++ yield return (e.Undo(), "undo the comp");+ bad = Mismatch(Timeline(e, track, out _), passAt);+ yield return (bad < 0 && ClipCount(e, track) == clipsBefore, $"one undo step restores the comp (first mismatch {bad})");+ yield return (e.Redo(), "redo the comp");+ bad = Mismatch(Timeline(e, track, out _), compAt);+ yield return (bad < 0, $"redo brings it back (first mismatch {bad})");++ // A range past what take 1 recorded clamps to its window (frames 24000..).+ yield return (e.CompTake(track, takes[0].Id, 0.0, 1.5), "comp a range wider than the take");+ for (int f = 24000; f < 36000; f++) compAt[f] = 0;+ bad = Mismatch(Timeline(e, track, out _), compAt);+ yield return (bad < 0, $"the comp clamps to what the take recorded (first mismatch {bad})");+ yield return (!e.CompTake(track, takes[2].Id, 3.0, 4.0), "a range the take never recorded is refused");++ // Delete take 3: its section keeps sounding, as a plain clip.+ yield return (e.DeleteTake(track, takes[2].Id), "delete a take");+ bad = Mismatch(Timeline(e, track, out _), compAt);+ clips = ClipCount(e, track);+ bool noRef = Enumerable.Range(0, clips).All(c => e.ClipTakeId(track, c) != takes[2].Id);+ yield return (e.TakeCount(track) == 2 && bad < 0 && noRef, $"deleting a take keeps the sound ({e.TakeCount(track)} takes, mismatch {bad})");+ e.Undo();+ yield return (e.TakeCount(track) == 3, "undo brings the deleted take back");++ // Flatten: one clip, no takes, and it renders as the comp did — the joins keep the edge+ // fades their sections played with.+ var compSound = Render(e);+ yield return (e.FlattenTakes(track), "flatten the takes");+ Timeline(e, track, out mirrored);+ bad = RenderMismatch(Render(e), compSound);+ clips = ClipCount(e, track);+ yield return (e.TakeCount(track) == 0 && clips == 1 && e.ClipTakeId(track, 0) == 0 && bad < 0 && mirrored,+ $"flatten leaves one clip that sounds as the comp did ({clips} clips, first mismatch {bad})");+ yield return (e.Undo() && e.TakeCount(track) == 3, "one undo step un-flattens");+ bad = Mismatch(Timeline(e, track, out _), compAt);+ yield return (bad < 0, $"...with the comp as it was (first mismatch {bad})");++ // A second loop recording adds a new group whose numbers continue.+ yield return (Record(e, track, Loop + 12000, 0.0), "record a second loop take");+ var more = Takes(e, track);+ yield return (more.Length == 5 && more[3].Number == 4 && more[4].Number == 5 && more[3].Group != more[0].Group,+ $"a new recording continues the take numbers in a new group ({more.Length})");+ }++ // Every take section sits where its take plays its first frame.+ private static bool SectionsOnTakes(NotaEngine e, int track)+ {+ var takes = Takes(e, track);+ int clips = ClipCount(e, track);+ for (int c = 0; c < clips; c++)+ {+ int id = e.ClipTakeId(track, c);+ if (id == 0) continue;+ if (!e.TryGetAudioClipInfo(track, c, out var ac)) return false;+ var t = takes.FirstOrDefault(k => k.Id == id);+ if (t.Id == 0 || t.LengthFrames <= 0) return false;+ double bpf = t.LengthBeats / t.LengthFrames;+ if (Math.Abs(ac.StartBeat - (t.OriginBeat + ac.SourceOffsetFrames * bpf)) > 1e-9) return false;+ }+ return clips > 0;+ }++ // Unwarped audio plays at its own rate, so a tempo change moves where a take's frames land;+ // the comp sections still where their take put them move with it.+ private static IEnumerable<(bool, string)> TempoChange()+ {+ using var e = Rig(out int track);+ Record(e, track, RecFrames, 1.0);+ var takes = Takes(e, track);+ if (takes.Length != 3) { yield return (false, $"tempo: a 3-pass recording makes 3 takes ({takes.Length})"); yield break; }+ e.CompTake(track, takes[0].Id, 1.5, 2.5);+ e.SetBpm(60);+ e.RenderOffline(new float[256 * 2], 256, Sr); // the transport takes the new tempo+ var slow = Takes(e, track);+ yield return (Math.Abs(slow[0].StartBeat - 0.5) < 1e-9 && Math.Abs(slow[1].LengthBeats - 2.0) < 1e-9,+ $"at half tempo a take covers half the beats ({slow[0].StartBeat}, {slow[1].LengthBeats})");+ yield return (SectionsOnTakes(e, track), "after a tempo change the comp sections sit where their takes play them");+ yield return (e.Undo() && SectionsOnTakes(e, track), "...and after undoing an edit made at the old tempo");+ yield return (e.Redo() && SectionsOnTakes(e, track), "...and after redoing it");+ yield return (e.FlattenTakes(track) && ClipCount(e, track) == 1,+ $"flatten after a tempo change still merges the comp into one clip ({ClipCount(e, track)})");+ }++ private static IEnumerable<(bool, string)> NoTakes()+ {+ using (var e = Rig(out int track))+ {+ Record(e, track, 30000, 1.0);+ yield return (e.TakeCount(track) == 0 && ClipCount(e, track) == 1, "one pass makes a clip, no takes");+ }+ using (var e = Rig(out int track))+ {+ e.SetLoop(false, 0.0, 4.0);+ Record(e, track, RecFrames, 1.0);+ yield return (e.TakeCount(track) == 0 && ClipCount(e, track) == 1, "loop off makes a clip, no takes");+ }+ }++ private static IEnumerable<(bool, string)> SaveReopen()+ {+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-takes-" + Guid.NewGuid().ToString("N") + ".nota");+ var transport = new TransportState(120.0, 1.0, false, false);+ try+ {+ float[] before;+ int[] numbers;+ using (var e = Rig(out int track))+ {+ Record(e, track, RecFrames, 1.0);+ var takes = Takes(e, track);+ e.CompTake(track, takes[0].Id, 1.5, 2.5);+ before = Timeline(e, track, out _);+ numbers = takes.Select(t => t.Number).ToArray();+ var w = new List<string>();+ ProjectService.Save(ProjectService.Capture(e, transport, w), dir, e);+ yield return (w.Count == 0, $"a project with takes saves without warnings ({w.Count})");+ }++ using var d = new NotaEngine();+ d.RenderOffline(new float[256 * 2], 256, Sr);+ var doc = ProjectService.Load(dir);+ yield return (doc.FormatVersion == ProjectService.CurrentFormatVersion, "saved as the current format");+ var warnings = ProjectService.Apply(doc, d, dir);+ int t2 = -1;+ for (int i = 0; i < d.TrackCount; i++)+ if (d.TryGetTrackInfo(i, out var ti) && ti.Type == 0) { t2 = ti.Id; break; }+ var reTakes = Takes(d, t2);+ yield return (warnings.Count == 0 && reTakes.Select(t => t.Number).SequenceEqual(numbers),+ $"takes reopen with their numbers ({warnings.Count} warnings, {reTakes.Length} takes)");+ var after = Timeline(d, t2, out _);+ int bad = -1;+ for (int f = 0; f < Loop && bad < 0; f++)+ if (!(float.IsNaN(before[f]) ? float.IsNaN(after[f]) : before[f] == after[f])) bad = f;+ yield return (bad < 0, $"the comp reopens sample-exact (first mismatch {bad})");+ int clips = ClipCount(d, t2);+ var ids = reTakes.Select(t => t.Id).ToHashSet();+ bool linked = Enumerable.Range(0, clips).All(c => ids.Contains(d.ClipTakeId(t2, c)));+ bool shared = Enumerable.Range(0, clips).All(c =>+ d.TryGetAudioClipInfo(t2, c, out var ac) && reTakes.Any(t => t.Id == d.ClipTakeId(t2, c) && t.SampleId == ac.SampleId));+ yield return (linked && shared, "comp sections re-link to their takes and share the take's audio");+ yield return (d.CompTake(t2, reTakes[1].Id, 0.0, 4.0) && d.FlattenTakes(t2) && d.TakeCount(t2) == 0,+ "reopened takes can be comped and flattened");+ }+ finally+ {+ try { Directory.Delete(dir, true); } catch { }+ }+ }+}