Skip to content

armgit / nota

Public Imported from GitHub
0

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

(fix) Take-lane joins, tempo cuts, and moved-clip highlights (#187) (#474)

Chris Laupamaf815a2d1a54c
diff --git a/.specify/bugs/take-lane-review/assessment.md b/.specify/bugs/take-lane-review/assessment.md
new file mode 100644
index 00000000..43a4a5a7
--- /dev/null
+++ b/.specify/bugs/take-lane-review/assessment.md
@@ -0,0 +1,89 @@
+# Bug Assessment: Take-lane review follow-ups (#187)
+
+- **Slug**: take-lane-review
+- **Created**: 2026-11-04
+- **Source**: review comments on https://github.com/nota-daw/nota/pull/403 (host: github.com — allowlisted), the three left after #187 was merged. Issue #187 stays closed; this follow-up references it.
+- **Verdict**: valid
+- **Severity**: high (the two P1 playback bugs); medium for the highlight
+
+## Report (verbatim or summarized)
+
+Greptile comments on PR #403, created 2026-10-31T11:31:05Z, after #187 closed. Earlier comments on that PR (flatten sound, tempo re-place, Escape swipe, inactive highlight, saved tempo on load) were already fixed before merge and are out of scope.
+
+1. **Recording adds a volume dip** (`Engine_Recording.cpp`, P1). When loop recording stops partway through the last pass, `materialiseLoopTakes` creates adjacent clips for that pass and the earlier pass behind it. Playback fades both clips to zero at their shared edge. The old recording used one clip, so it had no fade there. This adds a roughly 6 ms volume dip before the user makes any comp edit. Preserve the old playback gain across these automatic joins, and compare rendered audio against the old single-buffer result.
+
+2. **Comp cuts use old tempo** (`Engine_Takes.cpp`, P1). `compTake` uses the take's new tempo mapping, but `overwriteAudioClipsInRange` reads the transport's old tempo until the next audio block. Calling `SetBpm(60)` and then comping a range before that block can cut existing sections at the wrong source frames. Once the tempo command lands, the remaining clips play the wrong audio and can extend beyond the selected range. Use the same requested tempo for both the new section and the cuts.
+
+3. **Moved clips highlight different audio** (`ArrangementView.Takes.cs`, P2). Moving a comp section keeps its `takeId`, but `DrawTakeLanes` highlights the section's new timeline range on the original take. Moving audio from beat 1 to beat 2 therefore highlights beat 2's waveform even though the clip still plays beat 1's source frames. The highlight points users at different audio from what they hear, so swiping it can select the wrong section. Only highlight sections that still match the take's position, or map the highlight through their source offset.
+
+## Symptom
+
+A loop recording that ends mid-pass plays a short fade to silence where the last pass meets the pass under it. Comping immediately after a tempo change carves neighbouring clips with the tempo that has not reached the transport yet, so those clips keep the wrong source frames. A comp clip that has been moved still lights up the take lane over its new timeline range, which is a different part of the take than the clip plays.
+
+## Reproduction
+
+1. Record three loop passes on an audio track and stop during the third pass. Render across the frame where the newest partial pass meets the previous pass (the default comp is two clips). The samples at that join fall to silence for about 3 ms on each side. The first sample of the comp still fades in, as a single clip always did.
+2. Record the same three passes at 120 BPM, call `SetBpm(60)`, and `CompTake` a range of the first take before any render block. The new section's own frames follow the new mapping, but the neighbours are cut with 120 BPM's samples-per-beat, so their source offsets and lengths are wrong.
+3. Move a comp section off the beat where its take placed it and open the take lanes. The lane paints the in-use highlight over the clip's new timeline range. Expected: no highlight there, because that range is not the audio the clip plays. Delete and flatten behaviour stay as they are (the clip keeps its `takeId`).
+
+## Suspected Code Paths
+
+- `src/native/nota.engine/src/engine/Track.h` `audioClipEdgeGain` — ~3 ms linear fade at both ends of every unwarped clip.
+- `src/native/nota.engine/src/engine/Engine_Render.cpp` `mixAudioClip` — applies that fade on the unwarped path. Two adjacent clips therefore dip at the join.
+- `src/native/nota.engine/src/engine/Engine_Recording.cpp` `materialiseLoopTakes` — builds the default comp as newest-first coverage clips that meet at a frame boundary. It does not settle fades itself; the following republish is the right place.
+- `src/native/nota.engine/src/engine/Engine_Takes.cpp` `flattenTakes` — bakes `audioClipEdgeGain` at every inner edge so flatten matches multi-clip playback. A fade change has to bake the same edges or the existing render comparison breaks.
+- `src/native/nota.engine/src/engine/Engine_Tracks.cpp` `overwriteAudioClipsInRange` — calls `audioOverwriteRange` with `transport_.samplesPerBeat()`.
+- `src/native/nota.engine/src/engine/Engine.cpp` `setBpm` — updates `authoringBpm_` immediately and says `transport_.samplesPerBeat()` is stale until the audio thread applies `SetBpm`. `republishWithTrackRaw` publishes the clone. `placeTakesForTempo` publishes through `publishRaw` and must not be settled by mutating a track still shared with the previous snapshot.
+- `src/native/nota.engine/src/engine/Engine_Takes.cpp` `atTakePosition` — a section is still where its take put it when `startBeat` equals `originBeat + sourceOffsetFrames * beatsPerFrame`.
+- `src/managed/Nota.App/ArrangementView.Takes.cs` `DrawTakeLanes` — highlights every active clip with a matching `TakeId` over `c.StartBeat`. `TakeVM` has no origin or beats-per-frame. `ClipVM` has `TakeId` but not `SourceOffsetFrames`. `ArrangementView.cs` `Refresh` already calls `TryGetAudioClipInfo`.
+
+## Root Cause Hypothesis
+
+Confidence: high. Each report matches the code. The dip is the ordinary per-clip edge fade applied to two clips that replaced one buffer. The tempo cut is `overwriteAudioClipsInRange` reading the transport clock while `compTake` and `placeTakesForTempo` already use `authoringBpm_`. The highlight treats `takeId` as "this timeline range is that take's audio", but a moved clip keeps the id and the source frames while its start beat changes.
+
+## Proposed Remediation
+
+**Preferred**:
+
+1. Add `fadeHead` and `fadeTail` on `AudioClip`, default true, so ordinary clips and older in-memory snapshots keep today's fades. `audioClipEdgeGain` and the unwarped `mixAudioClip` path honour them. On the message thread, `settleTakeJoins` runs on the new track clone at the start of `republishWithTrackRaw`, and on each clone inside `placeTakesForTempo` before `publishRaw`. It sets both fades on, then turns off the shared edge of unwarped take clips in the same group whose beat ranges meet. Outer edges, gaps, other groups, and non-take clips keep both fades. Do not persist the flags and do not settle inside `publishRaw` (that graph can still share track pointers). `flattenTakes` bakes a fade only when the clip's flag is on and the edge is not the outer edge of the merged range.
+2. `overwriteAudioClipsInRange` passes authoring samples-per-beat (`deviceRate * 60 / authoringBpm_`, falling back to the transport when that is unavailable) into `audioOverwriteRange`. No other `samplesPerBeat()` call changes.
+3. `TakeVM` stores `OriginBeat` and `BeatsPerFrame` (`LengthBeats / LengthFrames`). `ClipVM` stores `SourceOffsetFrames` from `TryGetAudioClipInfo`. `DrawTakeLanes` skips the in-use paint unless `startBeat` is still `origin + sourceOffset * beatsPerFrame`.
+
+**Alternatives**:
+
+- Drop the edge fade for every butt-joined clip. That also changes ordinary splits, which are supposed to fade.
+- Map the highlight through the source offset onto the take waveform. Correct visually, but the comment's first option (only sections still at the take position) matches `atTakePosition` and does not paint a moved clip as if it were still a comp section.
+
+**Files likely to change**:
+
+- `src/native/nota.engine/src/engine/Track.h`
+- `src/native/nota.engine/src/engine/Engine.h`
+- `src/native/nota.engine/src/engine/Engine.cpp`
+- `src/native/nota.engine/src/engine/Engine_Takes.cpp`
+- `src/native/nota.engine/src/engine/Engine_Tracks.cpp`
+- `src/native/nota.engine/src/engine/Engine_Render.cpp`
+- `src/managed/Nota.App/ArrangementView.Takes.cs`
+- `src/managed/Nota.App/ArrangementView.Vms.cs`
+- `src/managed/Nota.App/ArrangementView.cs`
+- `tests/Nota.SmokeTest/TakeLaneTests.cs`
+- `CHANGELOG.md`
+
+**Tests to add or update**:
+
+- After the three-pass default comp, render the loop and require the join frame (30000) and the frame before it to match the raw timeline, while frame 0 stays near silence.
+- `SetBpm(60)` then `CompTake` on the first take over beats 0.5–1.0 before any render block. The new section is source frames 24000–48000; the left neighbour keeps frames 0–24000; the right neighbour starts at source frame 48000. Update the flatten comment that says every inner join keeps a fade.
+
+The highlight is view-only. The smoke project does not reference `Nota.App`, so it is not pinned by `TakeLaneTests`. A before/after screenshot of a moved clip is the check.
+
+## Risks & Considerations
+
+- Settling a track that is still shared with the previous snapshot would change audio already playing. Settle only the clone about to be published.
+- Suppressing fades for every butt join would change split clips. Limit it to `takeId != 0`, the same take group, and unwarped clips.
+- Flags are derived at publish time, so project format stays v29. A snapshot published before this change defaults the new fields to true, and undoing back to it can dip again. Acceptable.
+- `overwriteAudioClipsInRange` is also the recording-stop carve. Using the authoring tempo there matches a pending tempo change; other edit paths keep reading the transport.
+- `placeTakesForTempo` must settle after it updates `beatsPerFrame`, so the meet test uses the mapping the clips were just moved onto.
+- No new dependency. No audio-thread allocation: the flags are plain fields read while mixing, and settling runs on the message thread before publish.
+
+## Open Questions
+
+- None. The maintainer asked for these three comments in one follow-up, referencing #187 without reopening it.
diff --git a/.specify/bugs/take-lane-review/fix.md b/.specify/bugs/take-lane-review/fix.md
new file mode 100644
index 00000000..96e8e527
--- /dev/null
+++ b/.specify/bugs/take-lane-review/fix.md
@@ -0,0 +1,69 @@
+# Bug Fix: Take-lane review follow-ups (#187)
+
+- **Slug**: take-lane-review
+- **Fixed**: 2026-11-04
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+Butt-joined take sections of one recording no longer fade at the shared edge, a comp cut uses the tempo `setBpm` already stored, and a moved clip is not painted as the take's audio at its new timeline range.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/native/nota.engine/src/engine/Track.h` | modified | `fadeHead` / `fadeTail` on `AudioClip`; `audioClipEdgeGain` honours them |
+| `src/native/nota.engine/src/engine/Engine.h` | modified | `authoringSamplesPerBeat`, `settleTakeJoins` |
+| `src/native/nota.engine/src/engine/Engine.cpp` | modified | `publishRaw` settles tracks the new graph does not share |
+| `src/native/nota.engine/src/engine/Engine_Takes.cpp` | modified | settle implementation; flatten keeps a full-level join against a section that stays separate |
+| `src/native/nota.engine/src/engine/Engine_Tracks.cpp` | modified | `overwriteAudioClipsInRange` takes the caller's samples-per-beat |
+| `src/native/nota.engine/src/engine/Engine_Recording.cpp` | modified | a stopped recording is placed and carved at the authoring tempo |
+| `src/native/nota.engine/src/engine/Engine_Render.cpp` | modified | unwarped mix passes the clip's fade flags |
+| `src/managed/Nota.App/ArrangementView.Takes.cs` | modified | highlight only a section still at the take position |
+| `src/managed/Nota.App/ArrangementView.Vms.cs` | modified | `ClipVM.SourceOffsetFrames` |
+| `src/managed/Nota.App/ArrangementView.cs` | modified | copy `SourceOffsetFrames` on refresh |
+| `src/native/nota.engine/include/nota/nota_engine.h` | modified | `nota_clip_joined_edges`, `nota_track_restore_joined_edges` |
+| `src/native/nota.engine/src/abi/nota_engine_track.cpp` | modified | the two exports |
+| `src/native/nota.engine/src/engine/Engine_TakeRetry.cpp` | modified | a take retry publishes its restored graph as restored |
+| `src/managed/Nota.Application/Engine/IAudioEngine.cs` | modified | `ClipJoinedEdges`, `RestoreJoinedEdges` |
+| `src/managed/Nota.Infrastructure/Interop/*.Takes.cs` | modified | P/Invoke and wrapper |
+| `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs` | modified | optional `AudioClipDto.JoinedEdges` |
+| `src/managed/Nota.Infrastructure/Persistence/ProjectService.cs` | modified | save it; restore it once a track's clips are in |
+| `tests/Nota.SmokeTest/TakeLaneTests.cs` | modified | join level, pre-block comp and record cuts, reversed flatten (and its reopen), cross-track fade, deactivated half, undo/redo |
+| `CHANGELOG.md` | modified | Unreleased Fixed entry |
+
+## Tests Added or Updated
+
+- `TakeLaneTests.ThreePasses` — rendered audio at the default-comp join (frame 30000) matches a full-level frame of the same clip; frame 0 still fades out to silence.
+- `TakeLaneTests.CompBeforeBlock` — `SetBpm(60)` then `CompTake` of take 1 over beats 0.5–1.0, with no render in between, leaves source frames 24000–48000 on the new section, 0–24000 on the partial last pass, and 48000 onward on the full pass.
+- `TakeLaneTests.RecordBeforeBlock` — with the loop off, a 96000-frame clip is on the track, `SetBpm(60)`, then a 48000-frame recording stops before the next block. The new clip occupies beat 0 and the neighbour starts at beat 1, source frame 48000.
+- `TakeLaneTests.FlattenKeepsSeparateJoin` — reversing the partial last pass keeps the join at full level, and flatten renders the same.
+- `TakeLaneTests.MoveToTrackFadesExposedEdge` — moving the left section to another track fades the edge that used to meet it. The frame just past that fade is unchanged.
+- `TakeLaneTests.FlattenKeepsSeparateJoin` (reopen) — the flattened project with a reversed section saves and reopens in a new engine; the render matches the comp sample for sample.
+- `TakeLaneTests.DeactivatedSideFades` — deactivating the left section fades the right one's head at frame 30000; reactivating it restores the full-level join.
+- `TakeLaneTests.UndoKeepsJoins` — comp, flatten, undo twice renders as the recording did; redo twice renders as the flatten did.
+
+## Local Verification
+
+- Commands run: native Release build (`CC=gcc CXX=g++`), `dotnet build` of the smoke project, `Nota.SmokeTest.dll --takes` → TAKES PASSED, then the full `Nota.SmokeTest.dll` again after the review fixes → SMOKE TEST PASSED (includes the render-pool guards).
+- Manual checks: take lanes of a moved section, develop build versus this branch. The moved clip stays on the track; the lane no longer lights the part of the take under the clip's new range.
+
+## Deviations from Assessment
+
+`overwriteAudioClipsInRange` takes the caller's samples-per-beat instead of always reading the authoring tempo. A comp and a loop take pass the authoring tempo. Stopping a recording measures the new clip with that same tempo, because playback will, and passes it into the carve. When the transport has already caught up, the two clocks match.
+
+`publishRaw` recomputes fades on tracks the new graph does not share with the one still playing. That covers a clip moved to another track, and any other edit that publishes clones without going through `republishWithTrackRaw`. Shared tracks are left alone.
+
+A join that already played full-level stays full-level when the clips still meet, so flatten can keep a reversed section as its own clip without putting the dip back. The merged clip's facing edge is set off before publish when that neighbour's edge was off.
+
+Second Greptile round:
+
+- **Undo changed audio still playing.** `publishRaw(g, restored)`: undo, redo and a take retry pass `restored = true`. A restored track was published before and a render may still walk it, so when its derived fades differ it is cloned and the clone is settled; it is never written in place. An edit's own clones are still settled in place.
+- **Reopening brought back the dip.** A join whose takes are gone (flatten keeping a reversed neighbour) cannot be derived again, so `AudioClipDto.JoinedEdges` saves it (optional, written only when non-zero; no format bump — an older file has none and an older app ignores it). Load restores the whole track's edges in one call after every clip is in, and the join is kept only where both clips still meet.
+- **Large comps.** `takeJoinEdges` maps take id → group once (sorted, binary search), sorts the active clips' heads and finds each tail's partner by binary search: O(n log n + T log T) per published track, both passes in one.
+- **Deactivated sections.** A silent clip joins nothing in either pass, so the half that still plays fades at the shared edge.
+
+## Follow-ups
+
+- None from review.
diff --git a/.specify/bugs/take-lane-review/test.md b/.specify/bugs/take-lane-review/test.md
new file mode 100644
index 00000000..e9c8ac30
--- /dev/null
+++ b/.specify/bugs/take-lane-review/test.md
@@ -0,0 +1,49 @@
+# Bug Verification: Take-lane review follow-ups (#187)
+
+- **Slug**: take-lane-review
+- **Tested**: 2026-11-04
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+The join no longer dips, a comp cut before the next audio block uses the new tempo, and a moved clip no longer highlights the wrong part of its take. The full Linux smoke suite passed, including the render-pool guards.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (post-fix) | `Nota.SmokeTest.dll --takes` | pass | Join level, pre-block comp cut, pre-block record cut, reversed flatten, cross-track fade |
+| New / updated tests | same run, `TAKES PASSED` | pass | Flatten of a fully merged comp still matches; a reversed neighbour does too |
+| Regression suite | `Nota.SmokeTest.dll` (full), rerun after the review fixes | pass | `SMOKE TEST PASSED`, exit 0 |
+| Highlight | develop app vs this branch, same project | pass | Moved section stays on the track; its lane range is dim after the fix |
+| Lint / type-check | `dotnet build Nota.sln -c Release` | pass | Existing warnings only |
+| macOS / Windows | — | not-run | Linux only in this environment |
+
+## Output Excerpts
+
+```
+[PASS] a butt-joined take section does not dip (head 0, join 0.2192/0.1414, scale 0.7071)
+[PASS] comping after a tempo change, before the next block, cuts neighbours on the new tempo
+[PASS] stopping a recording after a tempo change, before the next block, cuts one beat
+[PASS] a reversed take section stays full-level at the join (head 0, join 0.2121/0.1414)
+[PASS] flatten keeps the full-level join (first mismatch -1)
+[PASS] moving one half of a join onto another track fades the edge that was shared (0)
+TAKES PASSED
+SMOKE TEST PASSED
+EXIT:0
+```
+
+The mixer applies a constant pan-law gain (~0.707), so the join is compared with a full-level frame of the same clip rather than the raw sample. Frame 0 is still silence.
+
+Second review round: `TakeLaneTests` adds the reopen of a flattened join, a deactivated half, and undo/redo across comp + flatten (macOS, `scripts/build.sh`).
+
+## Residual Risks
+
+- The highlight check is a screenshot, not a smoke assertion: `Nota.SmokeTest` does not reference `Nota.App`.
+- Scanner self-test and `--scan-scale` were not re-run.
+
+## Recommendation
+
+The three review comments on #403, and the four on this follow-up, are fixed on this branch. Reference #187; do not reopen it. The pair-scan note is addressed by looking up each section's group once and walking boundaries in start order.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e3589b8a..01e637fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -309,6 +309,13 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
block size stopped Nota when added, because every plug-in was prepared for 16384-sample
blocks. Plug-ins are now prepared for at most 4096; a longer block (an export, a large audio
buffer) is played to them in pieces, each with its own notes and transport position.
+- **Take lanes no longer dip, cut on the old tempo, or highlight a moved clip** (#187):
+ where two sections of one loop recording meet, playback stays at full level instead of
+ fading out and back in, including after flatten when one of those sections stays its own
+ clip. Comping a take, or stopping a recording, after a tempo change uses the new tempo
+ even before the next audio block, so the recording covers the beats it will play and does
+ not cut the neighbours short or long. Moving a comp clip no longer lights the wrong part
+ of its take lane, and moving it onto another track fades the edges that used to meet.
- **The loop region is saved with the project** (#455): its start and end, and whether the
loop is on, come back when you open the project again. A new project starts without one.
- **The Mixer's volume reaches −∞** (#453): a fader pulled all the way down, a dB value dragged
diff --git a/src/managed/Nota.App/ArrangementView.Takes.cs b/src/managed/Nota.App/ArrangementView.Takes.cs
index 3a8fbfe4..3042d169 100644
--- a/src/managed/Nota.App/ArrangementView.Takes.cs
+++ b/src/managed/Nota.App/ArrangementView.Takes.cs
@@ -29,6 +29,8 @@ public sealed partial class ArrangementView
public int Number;
public double StartBeat;
public double LengthBeats;
+ public double OriginBeat;
+ public double BeatsPerFrame;
public float[]? Peaks;
public int PeakCount;
}
@@ -67,6 +69,8 @@ public sealed partial class ArrangementView
tvm.Takes.Add(new TakeVM
{
Id = info.Id, Number = info.Number, StartBeat = info.StartBeat, LengthBeats = info.LengthBeats,
+ OriginBeat = info.OriginBeat,
+ BeatsPerFrame = info.LengthFrames > 0 ? info.LengthBeats / info.LengthFrames : 0,
Peaks = p.peaks, PeakCount = p.count,
});
}
@@ -262,6 +266,10 @@ public sealed partial class ArrangementView
foreach (var c in t.Clips)
{
if (c.TakeId != take.Id || !c.Active) continue; // a deactivated section is silent
+ // A moved clip keeps the take id but no longer plays this part of the lane.
+ if (!(take.BeatsPerFrame > 0
+ && Math.Abs(c.StartBeat - (take.OriginBeat + c.SourceOffsetFrames * take.BeatsPerFrame)) < 1e-4))
+ continue;
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);
diff --git a/src/managed/Nota.App/ArrangementView.Vms.cs b/src/managed/Nota.App/ArrangementView.Vms.cs
index f46c0efd..902c8e67 100644
--- a/src/managed/Nota.App/ArrangementView.Vms.cs
+++ b/src/managed/Nota.App/ArrangementView.Vms.cs
@@ -91,6 +91,7 @@ public sealed partial class ArrangementView
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 = none
+ public double SourceOffsetFrames; // where in the take that section starts; the lane highlight uses it
/// <summary>What the audio clip's peaks were drawn from (everything but where it sits), so a
/// refresh after a clip only moved can keep them (specs/073). Null for MIDI.</summary>
public PeakSourceKey? PeakSource;
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 16e33e55..ca490afc 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -1168,6 +1168,7 @@ public sealed partial class ArrangementView : UserControl
cvm.Gain = ai.Gain;
cvm.Adsr = eng.GetClipAdsr(ti.Id, c);
cvm.TakeId = eng.ClipTakeId(ti.Id, c);
+ cvm.SourceOffsetFrames = ai.SourceOffsetFrames;
}
tvm.Clips.Add(cvm);
}
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 139858d4..e8908303 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -1191,6 +1191,12 @@ public interface IAudioEngine : IDisposable
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);
+ /// <summary>The ends of an arrangement audio clip that play at full level (1 head, 2 tail):
+ /// a take join, or one a flatten kept. 0 = both ends fade.</summary>
+ int ClipJoinedEdges(int trackId, int clipIndex);
+ /// <summary>Project load (no undo entry): the saved <see cref="ClipJoinedEdges"/> of the track's
+ /// first clips. A join is kept only where both clips still meet.</summary>
+ void RestoreJoinedEdges(int trackId, int[] edges);
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.cs
index 1ebb6ecc..422691ff 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Takes.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Takes.cs
@@ -37,6 +37,12 @@ internal static partial class NativeMethods
[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_clip_joined_edges")]
+ internal static partial int ClipJoinedEdges(IntPtr engine, int trackId, int clipIndex);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_restore_joined_edges")]
+ internal static partial NotaResult TrackRestoreJoinedEdges(IntPtr engine, int trackId, int[] edges, int count);
+
[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.cs
index 05a424a7..b13eb50d 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Takes.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Takes.cs
@@ -34,6 +34,12 @@ public sealed partial class NotaEngine
public void SetClipTakeId(int trackId, int clipIndex, int takeId)
{ ThrowIfDisposed(); NativeMethods.ClipSetTakeId(_handle, trackId, clipIndex, takeId); }
+ public int ClipJoinedEdges(int trackId, int clipIndex)
+ { ThrowIfDisposed(); return NativeMethods.ClipJoinedEdges(_handle, trackId, clipIndex); }
+
+ public void RestoreJoinedEdges(int trackId, int[] edges)
+ { ThrowIfDisposed(); NativeMethods.TrackRestoreJoinedEdges(_handle, trackId, edges, edges.Length); }
+
/// <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)
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 02393d99..1b9e9356 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -400,6 +400,9 @@ public sealed class AudioClipDto
public bool Reversed { get; set; } // plays back-to-front (v19); default false
public ClipAdsrDto? Adsr { get; set; } // ADSR amplitude shape (v20); null = identity
public int? TakeId { get; set; } // the AudioTakeDto.Id this comp section came from (v29)
+ // Ends that play at full level where take sections meet: 1 head, 2 tail (v29, optional;
+ // absent = both fade). A flatten keeps such a join after its takes are gone.
+ public int? JoinedEdges { 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.cs
index ad1c99c3..a2d942f9 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -242,6 +242,8 @@ public sealed class ProjectService
dto.Sample = rel;
int take = engine.ClipTakeId(ti.Id, c);
if (take != 0) dto.TakeId = take;
+ int joined = engine.ClipJoinedEdges(ti.Id, c);
+ if (joined != 0) dto.JoinedEdges = joined;
t.AudioClips.Add(dto);
}
for (int k = 0; k < engine.TakeCount(ti.Id); k++)
@@ -816,14 +818,23 @@ public sealed class ProjectService
}
}
+ var joinedEdges = new List<(int Clip, int Edges)>();
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 (ac.JoinedEdges is int je && je != 0) joinedEdges.Add((ci, je));
if (engine.TryGetAudioClipInfo(id, ci, out var lci)) BundleContent.SeedSample(engine, lci.SampleId, ac.Sample);
}
+ // After every clip is in: a join is kept only where both of its clips are there.
+ if (joinedEdges.Count > 0)
+ {
+ var edges = new int[joinedEdges.Max(j => j.Clip) + 1];
+ foreach (var (clip, e) in joinedEdges) edges[clip] = e;
+ engine.RestoreJoinedEdges(id, edges);
+ }
// Freeze (M7): restore the frozen-audio buffer so the track re-opens frozen
// (the live chain above is kept intact for a later unfreeze). cloneTrack carries
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index b77c9346..19fd9e09 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1184,6 +1184,14 @@ NOTA_API int32_t nota_track_restore_take(NotaEngine* engine, int32_t track_id
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);
+/* The ends of an arrangement audio clip that play at full level, with no edge fade: bit 1 the
+ * head, bit 2 the tail. Two sections of one recording that meet join that way, and a flatten
+ * keeps the join after the takes are gone, so a project saves it. 0 = both ends fade. */
+NOTA_API int32_t nota_clip_joined_edges(const NotaEngine* engine, int32_t track_id, int32_t clip_index);
+/* Project load (no undo entry): the saved nota_clip_joined_edges of the track's first `count`
+ * arrangement audio clips. A join is kept only where both clips still meet. */
+NOTA_API NotaResult nota_track_restore_joined_edges(NotaEngine* engine, int32_t track_id, const int32_t* edges,
+ int32_t count);
/* 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. */
diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cpp
index a53f0477..b2735485 100644
--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp
@@ -878,6 +878,13 @@ NotaResult nota_clip_set_take_id(NotaEngine* e, int32_t track_id, int32_t clip_i
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_clip_joined_edges(const NotaEngine* e, int32_t track_id, int32_t clip_index) {
+ return e ? CENG(e)->clipJoinedEdges(track_id, clip_index) : 0;
+}
+NotaResult nota_track_restore_joined_edges(NotaEngine* e, int32_t track_id, const int32_t* edges, int32_t count) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->restoreJoinedEdges(track_id, edges, count) ? 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;
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index f45fa663..c1215679 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -725,7 +725,31 @@ bool Engine::setRenderThreads(int n) {
return true;
}
-void Engine::publishRaw(std::shared_ptr<Graph> g) {
+void Engine::publishRaw(std::shared_ptr<Graph> g, bool restored) {
+ // Fade flags are derived, not stored. A track this graph shares with the one still
+ // playing is the audio thread's — leave it. Any other one an edit just cloned is
+ // settled in place. A restored track (undo, redo, take retry) was published before and
+ // a render may still be walking it, so it is cloned when its fades would change.
+ // Every take id comes from nextTakeId_; until one does (or a load restores a kept join),
+ // no clip can join, and this runs on every edit, undo and redo (perf-gate edit-warp-split).
+ if (g && authoring_ && (nextTakeId_ > 0 || joinedEdgesRestored_)) {
+ auto shared = [&](const std::shared_ptr<Track>& t) {
+ for (const auto& old : authoring_->tracks)
+ if (old == t) return true;
+ return authoring_->masterTrack && authoring_->masterTrack == t;
+ };
+ auto settle = [&](std::shared_ptr<Track>& t) {
+ if (!t || !mayHaveTakeJoins(*t) || shared(t)) return;
+ if (!restored) {
+ settleTakeJoins(*t);
+ } else if (!takeJoinsSettled(*t)) {
+ t = cloneTrack(*t);
+ settleTakeJoins(*t);
+ }
+ };
+ for (auto& t : g->tracks) settle(t);
+ settle(g->masterTrack);
+ }
// Ensure every track has a session slot per scene (M5). Only grows freshly
// added tracks (already-sized tracks are a no-op), so no race with audio.
for (auto& t : g->tracks)
@@ -824,7 +848,7 @@ bool Engine::undo() {
// device (a removed look-ahead coming back, #109), so compensation follows them.
if (e.graph) {
if (authoring_) keepLiveSends(*e.graph, *authoring_);
- publishRaw(std::move(e.graph));
+ publishRaw(std::move(e.graph), true);
placeTakesForTempo(); // the snapshot may predate a tempo change
recomputePdc();
reapplyRackMacros();
@@ -903,7 +927,7 @@ bool Engine::redo() {
undoStack_.push_back({e.graph ? authoring_ : nullptr, e.mix});
if (e.graph) {
if (authoring_) keepLiveSends(*e.graph, *authoring_);
- publishRaw(std::move(e.graph));
+ publishRaw(std::move(e.graph), true);
placeTakesForTempo(); // the snapshot may predate a tempo change
recomputePdc();
reapplyRackMacros();
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index 3d79421a..02b5520a 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -1339,6 +1339,13 @@ class Engine {
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
+ // The ends of an arrangement audio clip that play without the edge fade (bit 1 head, bit 2
+ // tail): a take join, or one a flatten kept. Saved with the project, because a join whose
+ // takes are gone cannot be derived again.
+ int32_t clipJoinedEdges(int32_t trackId, int32_t clipIndex) const;
+ // Project load, no undo entry: the saved clipJoinedEdges of the track's first `count`
+ // clips. A join comes back only where both clips still meet (settleTakeJoins).
+ bool restoreJoinedEdges(int32_t trackId, const int32_t* edges, int32_t count);
// 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);
@@ -1513,7 +1520,10 @@ class Engine {
std::shared_ptr<SampleBuffer> findSampleById(int64_t sampleId) const; // M7-6b
static std::shared_ptr<SampleBuffer> chainSampleById(const RackCore* rack, int64_t sampleId, int depth);
void publish(std::shared_ptr<Graph> g); // checkpoints (undo), then publishRaw
- void publishRaw(std::shared_ptr<Graph> g); // swap live/authoring only, no undo entry
+ // Swap live/authoring only, no undo entry. `restored`: the graph holds tracks published
+ // before (undo, redo, a take retry) that a render may still be reading, so a track whose
+ // take-join fades must change is cloned rather than written in place.
+ void publishRaw(std::shared_ptr<Graph> g, bool restored = false);
void configureClipWarp(AudioClip& c, double spb, double devSR); // build the clip's warp cache (unless deferred)
const AudioClip* warpBuildTargetClip() const; // in-progress build target, revalidated (null = abandon)
void reconfigureAllWarpStreams(); // rebuild warp caches for the current tempo + device SR
@@ -1609,6 +1619,9 @@ class Engine {
SnapshotHistory<Graph> graphHist_;
int32_t nextTrackId_ = 1;
int32_t nextTakeId_ = 0; // AudioTake::id (specs/067); never reused in a session
+ // A project load restored a join whose takes are gone (restoreJoinedEdges). With it and
+ // nextTakeId_ still 0 no clip can have a take join, so publishRaw skips settling them.
+ bool joinedEdgesRestored_ = false;
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.
@@ -1616,9 +1629,24 @@ class Engine {
// 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;
+ // Samples per beat at authoringBpm_. setBpm stores that before the transport applies it,
+ // so a message-thread carve reads this instead of transport_.samplesPerBeat().
+ double authoringSamplesPerBeat() 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();
+ // The edges that play without a fade, per clip (bit 1 head, bit 2 tail): where unwarped
+ // take sections of one group meet, and where a join that already played full-level still
+ // meets (flatten and delete clear the take id). Both clips must be active. O(n log n).
+ std::vector<uint8_t> takeJoinEdges(const Track& t) const;
+ // Write takeJoinEdges into the clips' fade flags; true if any changed. Message thread,
+ // on a track no render can see yet (publishRaw decides which).
+ bool settleTakeJoins(Track& nt) const;
+ bool takeJoinsSettled(const Track& t) const;
+ // False when takeJoinEdges cannot turn an edge off and every edge already fades: no clip
+ // is an unwarped take section and none keeps a join. publishRaw runs on every edit, undo
+ // and redo, so it checks this first and skips the rest (perf-gate edit-warp-split).
+ static bool mayHaveTakeJoins(const Track& t);
// 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
@@ -1698,7 +1726,8 @@ class Engine {
std::vector<int32_t> insertTrackClones(
const std::vector<std::shared_ptr<Track>>& src, int32_t afterId, int32_t rootParent, bool keepParent);
// Carve [ns, ne) out of a track's audio clips (overwrite/comp on record + drag).
- void overwriteAudioClipsInRange(std::vector<AudioClip>& clips, double ns, double ne);
+ // `spb` is the samples-per-beat the caller used to measure `ns` and `ne`.
+ void overwriteAudioClipsInRange(std::vector<AudioClip>& clips, double ns, double ne, double spb);
// Loop region mirror (see loopEnabled()/loopStart()/loopEnd()).
bool loopEnabled_ = false;
diff --git a/src/native/nota.engine/src/engine/Engine_Recording.cpp b/src/native/nota.engine/src/engine/Engine_Recording.cpp
index dd06e171..5a277cd9 100644
--- a/src/native/nota.engine/src/engine/Engine_Recording.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Recording.cpp
@@ -775,7 +775,9 @@ void Engine::stopAudioRecording() {
// Place the take and carve whatever it lands on (overwrite/comp). Loop punch: a
// completed pass fills the loop region [loopStart, loopEnd]; a partial pass is the
// recorded sub-range. Linear: sits where recording began, spanning the captured length.
- const double spb = transport_.samplesPerBeat();
+ // setBpm stores the new tempo before the transport applies it. Playback will measure
+ // this clip in that tempo, so the beat range it occupies — and the carve — must too.
+ const double spb = authoringSamplesPerBeat();
const double devSR = transport_.sampleRate();
const double sampleSR = sample->sourceSampleRate > 0 ? sample->sourceSampleRate : devSR;
const double beatsPerFrame = (spb > 0.0 && sampleSR > 0.0) ? devSR / sampleSR / spb : 0.0;
@@ -813,7 +815,7 @@ void Engine::stopAudioRecording() {
ne = clip.startBeat + kept * beatsPerFrame;
}
if (ne <= ns) return;
- overwriteAudioClipsInRange(nt->clips, ns, ne);
+ overwriteAudioClipsInRange(nt->clips, ns, ne, spb);
nt->clips.push_back(clip);
republishWithTrack(trackId, nt);
}
@@ -848,7 +850,8 @@ void Engine::materialiseLoopTakes(Track& nt, std::vector<LoopPass>& passes, size
takes.push_back(std::move(k));
}
- overwriteAudioClipsInRange(nt.clips, loopStartBeat, loopStartBeat + static_cast<double>(loopFrames) * bpf);
+ overwriteAudioClipsInRange(nt.clips, loopStartBeat,
+ loopStartBeat + static_cast<double>(loopFrames) * bpf, authoringSamplesPerBeat());
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;
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index 6342628d..a2a77d3a 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -1782,7 +1782,8 @@ 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 float eg = static_cast<float>(audioClipEdgeGain(p - startSamples, clipDeviceLen, sr));
+ const float eg = static_cast<float>(
+ audioClipEdgeGain(p - startSamples, clipDeviceLen, sr, clip.fadeHead, clip.fadeTail));
l *= eg;
r *= eg;
applyEnv(p, l, r);
diff --git a/src/native/nota.engine/src/engine/Engine_TakeRetry.cpp b/src/native/nota.engine/src/engine/Engine_TakeRetry.cpp
index 3f63bee0..4e41223e 100644
--- a/src/native/nota.engine/src/engine/Engine_TakeRetry.cpp
+++ b/src/native/nota.engine/src/engine/Engine_TakeRetry.cpp
@@ -124,7 +124,7 @@ void Engine::discardTake() {
return g;
};
if (authoring_ && !a.baseTracks.empty()) {
- publishRaw(restoreGraph(*authoring_));
+ publishRaw(restoreGraph(*authoring_), true);
placeTakesForTempo();
recomputePdc();
reapplyRackMacros();
diff --git a/src/native/nota.engine/src/engine/Engine_Takes.cpp b/src/native/nota.engine/src/engine/Engine_Takes.cpp
index 3ef1ac07..30fa7acb 100644
--- a/src/native/nota.engine/src/engine/Engine_Takes.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Takes.cpp
@@ -14,6 +14,7 @@
#include <algorithm>
#include <cmath>
+#include <limits>
namespace nota {
@@ -30,6 +31,14 @@ bool atTakePosition(const AudioClip& c, const AudioTake& k) {
return std::abs(c.startBeat - (k.originBeat + c.sourceOffsetFrames * k.beatsPerFrame)) < 1e-6;
}
+// Timeline length (beats) of an unwarped clip at `spb` samples per beat. Matches playback.
+double unwarpedLenBeats(const AudioClip& c, double spb, double devSR) {
+ if (!c.sample || spb <= 0.0 || devSR <= 0.0 || c.sample->sourceSampleRate <= 0.0) return 0.0;
+ const double devFrames =
+ static_cast<double>(c.effectiveLength()) * devSR / c.sample->sourceSampleRate / c.pitchRatio();
+ return devFrames / spb;
+}
+
} // namespace
double Engine::beatsPerSourceFrame(double sampleRate) const {
@@ -37,14 +46,121 @@ double Engine::beatsPerSourceFrame(double sampleRate) const {
return sr > 0.0 && authoringBpm_ > 0.0 ? authoringBpm_ / 60.0 / sr : 0.0;
}
+double Engine::authoringSamplesPerBeat() const {
+ const double devSR = transport_.sampleRate();
+ if (authoringBpm_ > 0.0 && devSR > 0.0) return devSR * 60.0 / authoringBpm_;
+ return transport_.samplesPerBeat();
+}
+
+std::vector<uint8_t> Engine::takeJoinEdges(const Track& t) const {
+ const double devSR = transport_.sampleRate();
+ const double spb = authoringSamplesPerBeat();
+ constexpr double eps = 1e-6;
+ const size_t n = t.clips.size();
+ std::vector<uint8_t> off(n, 0);
+ if (n < 2) return off;
+
+ // One edge of an unwarped clip: where it sits, which clip, and the take group a take
+ // section belongs to (-1 for none). Silent clips count: a join outlives deactivation.
+ struct Edge {
+ double at;
+ size_t index;
+ int32_t group;
+ };
+ std::vector<int32_t> groupOf(n, -1);
+ if (!t.takes.empty()) {
+ std::vector<std::pair<int32_t, int32_t>> ids; // take id -> group, sorted by id
+ ids.reserve(t.takes.size());
+ for (const auto& k : t.takes) ids.emplace_back(k.id, k.group);
+ std::sort(ids.begin(), ids.end());
+ for (size_t i = 0; i < n; ++i) {
+ const int32_t id = t.clips[i].takeId;
+ if (id == 0) continue;
+ auto it = std::lower_bound(ids.begin(), ids.end(), std::make_pair(id, std::numeric_limits<int32_t>::min()));
+ if (it != ids.end() && it->first == id) groupOf[i] = it->second;
+ }
+ }
+ std::vector<Edge> heads, tails;
+ heads.reserve(n);
+ tails.reserve(n);
+ for (size_t i = 0; i < n; ++i) {
+ const AudioClip& c = t.clips[i];
+ if (!c.sample || c.warpEnabled) continue;
+ heads.push_back({c.startBeat, i, groupOf[i]});
+ tails.push_back({c.startBeat + unwarpedLenBeats(c, spb, devSR), i, groupOf[i]});
+ }
+ std::sort(heads.begin(), heads.end(), [](const Edge& a, const Edge& b) { return a.at < b.at; });
+
+ // Each tail meets the heads that start where it ends. Two sections of one recording
+ // join; so does a pair that already joined and still meets (flatten and delete clear
+ // the take id, the clips that stay keep the join). A join plays at full level only
+ // when both sides play: a silent clip leaves its neighbour's edge to fade.
+ for (const Edge& tl : tails) {
+ auto it = std::lower_bound(heads.begin(), heads.end(), tl.at - eps,
+ [](const Edge& h, double v) { return h.at < v; });
+ for (; it != heads.end() && it->at <= tl.at + eps; ++it) {
+ if (it->index == tl.index) continue;
+ const AudioClip& a = t.clips[tl.index];
+ const AudioClip& b = t.clips[it->index];
+ const bool sameTake = tl.group >= 0 && tl.group == it->group;
+ const bool kept = (a.joinedEdges & 2) && (b.joinedEdges & 1);
+ if (!sameTake && !kept) continue;
+ off[tl.index] |= 2;
+ off[it->index] |= 1;
+ if (a.active && b.active) {
+ off[tl.index] |= 8;
+ off[it->index] |= 4;
+ }
+ }
+ }
+ return off;
+}
+
+bool Engine::mayHaveTakeJoins(const Track& t) {
+ for (const auto& c : t.clips)
+ if (c.joinedEdges || !c.fadeHead || !c.fadeTail || (c.takeId != 0 && !c.warpEnabled)) return true;
+ return false;
+}
+
+bool Engine::settleTakeJoins(Track& nt) const {
+ if (!mayHaveTakeJoins(nt)) return false;
+ const auto off = takeJoinEdges(nt);
+ bool changed = false;
+ for (size_t i = 0; i < off.size(); ++i) {
+ AudioClip& c = nt.clips[i];
+ const uint8_t joined = off[i] & 3;
+ const bool head = !(off[i] & 4), tail = !(off[i] & 8);
+ if (c.joinedEdges == joined && c.fadeHead == head && c.fadeTail == tail) continue;
+ c.joinedEdges = joined;
+ c.fadeHead = head;
+ c.fadeTail = tail;
+ changed = true;
+ }
+ return changed;
+}
+
+bool Engine::takeJoinsSettled(const Track& t) const {
+ if (!mayHaveTakeJoins(t)) return true;
+ const auto off = takeJoinEdges(t);
+ for (size_t i = 0; i < off.size(); ++i) {
+ const AudioClip& c = t.clips[i];
+ if (c.joinedEdges != (off[i] & 3) || c.fadeHead != !(off[i] & 4) || c.fadeTail != !(off[i] & 8)) return false;
+ }
+ return true;
+}
+
void Engine::placeTakesForTempo() {
if (!authoring_) return;
+ // A join outlives its takes (flatten, delete), and a tempo change moves the ends of the
+ // unwarped clips that kept it: a track with no takes still needs its joins refreshed.
+ const bool joins = nextTakeId_ > 0 || joinedEdgesRestored_;
auto stale = [&](const Track& t) {
for (const auto& k : t.takes)
if (k.sample && k.beatsPerFrame != beatsPerSourceFrame(k.sample->sourceSampleRate)) return true;
- return false;
+ return joins && mayHaveTakeJoins(t) && !takeJoinsSettled(t);
};
- // Runs after every undo/redo: no new graph unless a take is actually off its tempo.
+ // Runs after every undo/redo: no new graph unless a take is off its tempo or a join no
+ // longer matches where the clips end.
if (std::none_of(authoring_->tracks.begin(), authoring_->tracks.end(),
[&](const auto& t) { return stale(*t); }))
return;
@@ -66,7 +182,7 @@ void Engine::placeTakesForTempo() {
}
for (auto& k : nt->takes)
if (k.sample) k.beatsPerFrame = beatsPerSourceFrame(k.sample->sourceSampleRate);
- g->tracks.push_back(std::move(nt));
+ g->tracks.push_back(std::move(nt)); // publishRaw settles joins on this clone
any = true;
}
if (any) publishRaw(std::move(g));
@@ -129,7 +245,7 @@ bool Engine::compTake(int32_t trackId, int32_t takeId, double startBeat, double
auto nt = cloneTrack(*old);
const double ns = k->originBeat + f0 * bpf, ne = k->originBeat + f1 * bpf;
- overwriteAudioClipsInRange(nt->clips, ns, ne);
+ overwriteAudioClipsInRange(nt->clips, ns, ne, authoringSamplesPerBeat());
AudioClip clip;
clip.sample = k->sample;
clip.startBeat = ns;
@@ -215,8 +331,9 @@ bool Engine::flattenTakes(int32_t trackId) {
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.
+ // Each section keeps the edge fades it played with, so the joins sound as the comp did.
+ // A butt-joined take section has that shared edge off. 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();
@@ -225,7 +342,7 @@ bool Engine::flattenTakes(int32_t trackId) {
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 bool fadeIn = c->fadeHead && off != lo, fadeOut = c->fadeTail && 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) {
@@ -247,6 +364,15 @@ bool Engine::flattenTakes(int32_t trackId) {
clip.startBeat = origin + static_cast<double>(lo) * bpf;
clip.sourceOffsetFrames = static_cast<double>(lo);
clip.lengthFrames = hi - lo;
+ // A neighbour that could not merge (reversed, moved, pitched) and joined this range
+ // keeps that join. publishRaw would otherwise fade both new edges.
+ const double mergedEnd = clip.startBeat + static_cast<double>(hi - lo) * bpf;
+ for (const auto& kpt : nt->clips) {
+ if (!kpt.sample || kpt.warpEnabled) continue;
+ const double kEnd = kpt.startBeat + unwarpedLenBeats(kpt, authoringSamplesPerBeat(), devSR);
+ if ((kpt.joinedEdges & 2) && std::abs(kEnd - clip.startBeat) < 1e-6) clip.joinedEdges |= 1;
+ if ((kpt.joinedEdges & 1) && std::abs(kpt.startBeat - mergedEnd) < 1e-6) clip.joinedEdges |= 2;
+ }
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; }),
@@ -301,6 +427,26 @@ bool Engine::setClipTakeId(int32_t trackId, int32_t clipIndex, int32_t takeId) {
return true;
}
+int32_t Engine::clipJoinedEdges(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;
+ const AudioClip& c = t->clips[clipIndex];
+ return c.joinedEdges;
+}
+
+bool Engine::restoreJoinedEdges(int32_t trackId, const int32_t* edges, int32_t count) {
+ auto old = findTrackAuthoring(trackId);
+ if (!old || count < 0 || (count > 0 && !edges)) return false;
+ auto nt = cloneTrack(*old);
+ const size_t n = std::min(nt->clips.size(), static_cast<size_t>(count));
+ for (size_t i = 0; i < n; ++i) {
+ if (edges[i] & 3) joinedEdgesRestored_ = true;
+ nt->clips[i].joinedEdges = static_cast<uint8_t>(edges[i] & 3);
+ }
+ republishWithTrackRaw(trackId, nt); // publishRaw keeps the pairs that still meet
+ 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;
diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
index 0e5d887b..51ddb0c9 100644
--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
@@ -1537,8 +1537,10 @@ bool raiseSplitEdge(AudioClip& clip, bool fadeIn, bool fadeOut, double fadeBeats
}
} // namespace
-void Engine::overwriteAudioClipsInRange(std::vector<AudioClip>& clips, double ns, double ne) {
- audioOverwriteRange(clips, ns, ne, transport_.samplesPerBeat(), transport_.sampleRate());
+void Engine::overwriteAudioClipsInRange(std::vector<AudioClip>& clips, double ns, double ne, double spb) {
+ // The caller measured ns/ne with `spb`. Comp and a loop take use the authoring tempo;
+ // a recording that just stopped uses the same clock as the clip it is about to place.
+ audioOverwriteRange(clips, ns, ne, spb, transport_.sampleRate());
}
int32_t Engine::pasteAudioFrames(
diff --git a/src/native/nota.engine/src/engine/Track.h b/src/native/nota.engine/src/engine/Track.h
index 50925821..d9ebd418 100644
--- a/src/native/nota.engine/src/engine/Track.h
+++ b/src/native/nota.engine/src/engine/Track.h
@@ -99,6 +99,15 @@ struct AudioClip {
// 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;
+ // The ends that join the clip meeting them (bit 1 head, bit 2 tail): take sections of one
+ // recording, or a join that outlived its takes (flatten, delete). Kept while the clips
+ // meet, silent or not, so deactivating a side does not lose it; the project saves it
+ // (nota_clip_joined_edges). Derived when the track is published (settleTakeJoins).
+ uint8_t joinedEdges = 0;
+ // Edge fades (~3 ms) at the played ends: off at a join both sides of which play, so the
+ // comp does not dip to silence there. Derived with joinedEdges, read by playback only.
+ bool fadeHead = true;
+ bool fadeTail = true;
int64_t effectiveLength() const;
// Played warp window (beats). Default (0/0) is the whole warp [0, warpBeats].
@@ -109,15 +118,16 @@ 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) {
+// The short edge fade (~3 ms) an unwarped clip plays at an end that asks for one, so a clip
+// 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`. A take join turns the shared end off
+// (AudioClip::fadeHead / fadeTail). Flatten (specs/067) bakes the fades the section played with.
+inline double audioClipEdgeGain(double into, double len, double sr, bool fadeHead = true, bool fadeTail = true) {
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)
+ if (fadeHead && into < edge) eg = into / edge;
+ else if (fadeTail && into > len - edge)
eg = (len - into) / edge;
return std::clamp(eg, 0.0, 1.0);
}
diff --git a/tests/Nota.SmokeTest/TakeLaneTests.cs b/tests/Nota.SmokeTest/TakeLaneTests.cs
index aa762c7f..1acd586a 100644
--- a/tests/Nota.SmokeTest/TakeLaneTests.cs
+++ b/tests/Nota.SmokeTest/TakeLaneTests.cs
@@ -3,9 +3,12 @@
//
// 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.
+// buffer did, including across the join a partial last pass makes; 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 a comp cut or a recording
+// stopped before the next audio block uses that mapping too; a reversed section that cannot
+// flatten still meets its neighbour at full level afterwards; moving one half of a join onto
+// another track fades the edges that used to meet; takes + comp survive save/reopen.
using Nota.Application;
using Nota.Infrastructure;
@@ -22,6 +25,13 @@ internal static class TakeLaneTests
{
foreach (var r in ThreePasses()) yield return r;
foreach (var r in TempoChange()) yield return r;
+ foreach (var r in CompBeforeBlock()) yield return r;
+ foreach (var r in RecordBeforeBlock()) yield return r;
+ foreach (var r in FlattenKeepsSeparateJoin()) yield return r;
+ foreach (var r in FlattenedJoinFollowsTempo()) yield return r;
+ foreach (var r in MoveToTrackFadesExposedEdge()) yield return r;
+ foreach (var r in DeactivatedSideFades()) yield return r;
+ foreach (var r in UndoKeepsJoins()) yield return r;
foreach (var r in NoTakes()) yield return r;
foreach (var r in SaveReopen()) yield return r;
}
@@ -173,6 +183,18 @@ internal static class TakeLaneTests
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})");
+ // The two sections meet at frame 30000. Playback used to fade both edges there (~6 ms
+ // of silence). The outer head of the comp still fades, as one clip always did.
+ // Render goes through the mixer, so compare the join to a full-level frame of the
+ // same clip rather than to the raw sample.
+ var played = Render(e);
+ double scale = tl[200] != 0f ? played[200] / tl[200] : 0;
+ yield return (Math.Abs(played[0]) < 1e-3
+ && scale > 0.5
+ && Math.Abs(played[29999] - tl[29999] * scale) < 1e-3
+ && Math.Abs(played[30000] - tl[30000] * scale) < 1e-3,
+ $"a butt-joined take section does not dip (head {played[0]:G4}, join {played[29999]:G4}/{played[30000]:G4}, scale {scale:G4})");
+
// 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");
@@ -204,8 +226,8 @@ internal static class TakeLaneTests
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.
+ // Flatten: one clip, no takes, and it renders as the comp did — including joins that
+ // no longer fade.
var compSound = Render(e);
yield return (e.FlattenTakes(track), "flatten the takes");
Timeline(e, track, out mirrored);
@@ -263,6 +285,245 @@ internal static class TakeLaneTests
$"flatten after a tempo change still merges the comp into one clip ({ClipCount(e, track)})");
}
+ private static bool ClipIs(NotaEngine e, int track, int takeId, double start, double offset, long length)
+ {
+ int n = ClipCount(e, track);
+ for (int c = 0; c < n; c++)
+ {
+ if (e.ClipTakeId(track, c) != takeId) continue;
+ if (!e.TryGetAudioClipInfo(track, c, out var ac)) continue;
+ if (Math.Abs(ac.StartBeat - start) < 1e-6
+ && Math.Abs(ac.SourceOffsetFrames - offset) < 1.0
+ && ac.LengthFrames == length)
+ return true;
+ }
+ return false;
+ }
+
+ // SetBpm updates the authoring tempo immediately and the transport only on the next block.
+ // A comp in between must cut neighbours with the new samples-per-beat. At 60 BPM, take 1
+ // (source frames 24000–96000) over beats 0.5–1.0 is frames 24000–48000; the partial last
+ // pass keeps frames 0–24000 and the full pass continues from frame 48000.
+ private static IEnumerable<(bool, string)> CompBeforeBlock()
+ {
+ using var e = Rig(out int track);
+ if (!Record(e, track, RecFrames, 1.0))
+ {
+ yield return (false, "tempo cut: recording failed");
+ yield break;
+ }
+ var takes = Takes(e, track);
+ if (takes.Length != 3)
+ {
+ yield return (false, $"tempo cut: expected 3 takes ({takes.Length})");
+ yield break;
+ }
+ e.SetBpm(60);
+ bool shaped = e.CompTake(track, takes[0].Id, 0.5, 1.0)
+ && ClipIs(e, track, takes[0].Id, 0.5, 24000, 24000)
+ && ClipIs(e, track, takes[2].Id, 0.0, 0, 24000)
+ && ClipIs(e, track, takes[1].Id, 1.0, 48000, 48000)
+ && ClipCount(e, track) == 3;
+ yield return (shaped, "comping after a tempo change, before the next block, cuts neighbours on the new tempo");
+ }
+
+ // 48,000 frames at 48 kHz is two beats on the transport's 120 BPM and one beat at the
+ // tempo setBpm has stored. The new clip and the hole it cuts must both be that one beat.
+ private static IEnumerable<(bool, string)> RecordBeforeBlock()
+ {
+ using var e = Rig(out int track);
+ e.SetLoop(false, 0.0, 4.0);
+ if (!Record(e, track, Loop, 0.0))
+ {
+ yield return (false, "record carve: the existing clip failed");
+ yield break;
+ }
+ e.SetBpm(60);
+ const int frames = 2 * Fpb; // 48,000
+ if (!Record(e, track, frames, 0.0))
+ {
+ yield return (false, "record carve: the second recording failed");
+ yield break;
+ }
+ bool neu = false, rest = false;
+ int n = ClipCount(e, track);
+ for (int c = 0; c < n; c++)
+ {
+ if (!e.TryGetAudioClipInfo(track, c, out var ac)) continue;
+ // An untrimmed recording leaves lengthFrames at 0, meaning the whole buffer.
+ bool whole = ac.LengthFrames == frames || ac.LengthFrames == 0;
+ if (Math.Abs(ac.StartBeat) < 1e-6 && whole && Math.Abs(ac.SourceOffsetFrames) < 1.0
+ && e.TryGetSampleInfo(ac.SampleId, out var si) && si.Frames == frames)
+ neu = true;
+ if (Math.Abs(ac.StartBeat - 1.0) < 1e-6 && ac.LengthFrames == frames
+ && Math.Abs(ac.SourceOffsetFrames - frames) < 1.0)
+ rest = true;
+ }
+ yield return (e.TakeCount(track) == 0 && n == 2 && neu && rest,
+ "stopping a recording after a tempo change, before the next block, cuts one beat");
+ }
+
+ private static int ClipAt(NotaEngine e, int track, double startBeat)
+ {
+ int n = ClipCount(e, track);
+ for (int c = 0; c < n; c++)
+ if (e.TryGetAudioClipInfo(track, c, out var ac) && Math.Abs(ac.StartBeat - startBeat) < 1e-4)
+ return c;
+ return -1;
+ }
+
+ // Reverse keeps a section out of the merge. The join played full-level; flatten must too.
+ private static IEnumerable<(bool, string)> FlattenKeepsSeparateJoin()
+ {
+ using var e = Rig(out int track);
+ if (!Record(e, track, RecFrames, 1.0))
+ {
+ yield return (false, "flatten join: recording failed");
+ yield break;
+ }
+ int left = ClipAt(e, track, 0.0);
+ if (left < 0)
+ {
+ yield return (false, "flatten join: no section at beat 0");
+ yield break;
+ }
+ e.SetClipReverse(track, left, true);
+ var comp = Render(e);
+ bool full = Math.Abs(comp[0]) < 1e-3 && Math.Abs(comp[29999]) > 0.05 && Math.Abs(comp[30000]) > 0.05;
+ yield return (full,
+ $"a reversed take section stays full-level at the join (head {comp[0]:G4}, join {comp[29999]:G4}/{comp[30000]:G4})");
+ var before = Render(e);
+ yield return (e.FlattenTakes(track) && e.TakeCount(track) == 0, "flatten with one section left reversed");
+ int bad = RenderMismatch(Render(e), before);
+ yield return (bad < 0, $"flatten keeps the full-level join (first mismatch {bad})");
+
+ // Silencing a side fades the edge it leaves; the join itself outlives that.
+ int flatLeft = ClipAt(e, track, 0.0);
+ e.SetClipActive(track, flatLeft, false);
+ var muted = Render(e);
+ e.SetClipActive(track, flatLeft, true);
+ bad = RenderMismatch(Render(e), before);
+ yield return (Math.Abs(muted[30000]) < 1e-3 && bad < 0,
+ $"after flatten, deactivating and reactivating a side joins full-level again (edge {muted[30000]:G4}, first mismatch {bad})");
+
+ // The takes are gone, so only the saved project knows that join plays full-level.
+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-join-" + Guid.NewGuid().ToString("N") + ".nota");
+ try
+ {
+ var w = new List<string>();
+ ProjectService.Save(ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), w), dir, e);
+ using var d = new NotaEngine();
+ d.RenderOffline(new float[256 * 2], 256, Sr);
+ var warnings = ProjectService.Apply(ProjectService.Load(dir), d, dir);
+ bad = RenderMismatch(Render(d), before);
+ yield return (w.Count == 0 && warnings.Count == 0 && bad < 0,
+ $"the flattened join reopens full-level (first mismatch {bad}, {w.Count}+{warnings.Count} warnings)");
+ }
+ finally
+ {
+ try { Directory.Delete(dir, true); } catch { }
+ }
+ }
+
+ // A flattened join has no takes left to re-place, but a tempo change still parts it.
+ private static IEnumerable<(bool, string)> FlattenedJoinFollowsTempo()
+ {
+ using var e = Rig(out int track);
+ int left = Record(e, track, RecFrames, 1.0) ? ClipAt(e, track, 0.0) : -1;
+ if (left < 0)
+ {
+ yield return (false, "flatten tempo: recording failed");
+ yield break;
+ }
+ e.SetClipReverse(track, left, true);
+ var before = Render(e);
+ bool flat = e.FlattenTakes(track) && e.TakeCount(track) == 0 && RenderMismatch(Render(e), before) < 0;
+ // At 60 BPM the reversed section still ends at frame 30000, its neighbour now starts at
+ // beat 1.25 = frame 60000: they no longer meet, so both ends fade against the silence.
+ e.SetBpm(60);
+ var slow = Render(e);
+ bool faded = Math.Abs(slow[29999]) < 0.01 && Math.Abs(slow[60000]) < 1e-3 && Math.Abs(slow[60300]) > 0.05;
+ yield return (flat && faded,
+ $"after flatten, a tempo change that parts the join fades both ends (tail {slow[29999]:G4}, head {slow[60000]:G4})");
+ }
+
+ // A silent section joins nothing: the one that still plays fades where they met.
+ private static IEnumerable<(bool, string)> DeactivatedSideFades()
+ {
+ using var e = Rig(out int track);
+ if (!Record(e, track, RecFrames, 1.0))
+ {
+ yield return (false, "deactivate fade: recording failed");
+ yield break;
+ }
+ var before = Render(e);
+ int left = ClipAt(e, track, 0.0);
+ if (left < 0)
+ {
+ yield return (false, "deactivate fade: no section at beat 0");
+ yield break;
+ }
+ e.SetClipActive(track, left, false);
+ var after = Render(e);
+ bool faded = Math.Abs(before[30000]) > 0.05 && Math.Abs(after[30000]) < 1e-3
+ && Math.Abs(after[30200] - before[30200]) < 1e-3 && Math.Abs(after[100]) < 1e-6;
+ yield return (faded,
+ $"deactivating one half of a join fades the other half's shared edge ({after[30000]:G4})");
+ e.SetClipActive(track, left, true);
+ int bad = RenderMismatch(Render(e), before);
+ yield return (bad < 0, $"reactivating it joins full-level again (first mismatch {bad})");
+ }
+
+ // Undo restores tracks a render may still be reading; their joins come back as they played.
+ private static IEnumerable<(bool, string)> UndoKeepsJoins()
+ {
+ using var e = Rig(out int track);
+ if (!Record(e, track, RecFrames, 1.0))
+ {
+ yield return (false, "undo joins: recording failed");
+ yield break;
+ }
+ var before = Render(e);
+ var takes = Takes(e, track);
+ bool edited = e.CompTake(track, takes[0].Id, 1.5, 2.5);
+ var comp = Render(e);
+ edited &= e.FlattenTakes(track);
+ var flat = Render(e);
+ int bad = RenderMismatch(flat, comp);
+ yield return (edited && bad < 0, $"comp then flatten plays the same (first mismatch {bad})");
+ bool undone = e.Undo() && e.Undo();
+ bad = RenderMismatch(Render(e), before);
+ yield return (undone && bad < 0, $"undo twice plays the recording's joins full-level (first mismatch {bad})");
+ bool redone = e.Redo() && e.Redo() && e.TakeCount(track) == 0;
+ bad = RenderMismatch(Render(e), flat);
+ yield return (redone && bad < 0, $"redo twice brings the flatten back as it played (first mismatch {bad})");
+ }
+
+ // The half that stays, and the half that moved, both get their edge fade back.
+ private static IEnumerable<(bool, string)> MoveToTrackFadesExposedEdge()
+ {
+ using var e = Rig(out int track);
+ if (!Record(e, track, RecFrames, 1.0))
+ {
+ yield return (false, "move fade: recording failed");
+ yield break;
+ }
+ var before = Render(e);
+ int left = ClipAt(e, track, 0.0);
+ int other = e.AddAudioTrack();
+ if (left < 0)
+ {
+ yield return (false, "move fade: no section at beat 0");
+ yield break;
+ }
+ e.MoveClipToTrack(track, left, other, 8.0);
+ var after = Render(e);
+ bool faded = Math.Abs(before[30000]) > 0.05 && Math.Abs(after[30000]) < 1e-3
+ && Math.Abs(after[30200] - before[30200]) < 1e-3;
+ yield return (faded,
+ $"moving one half of a join onto another track fades the edge that was shared ({after[30000]:G4})");
+ }
+
private static IEnumerable<(bool, string)> NoTakes()
{
using (var e = Rig(out int track))