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
(fix) Monitoring a track through an audio track no longer crackles (#563) (#567)
Egor Khindikaynen60f39563ed9b
diff --git a/.specify/bugs/563-monitor-crackle/assessment.md b/.specify/bugs/563-monitor-crackle/assessment.mdnew file mode 100644index 00000000..f3b89440--- /dev/null+++ b/.specify/bugs/563-monitor-crackle/assessment.md@@ -0,0 +1,116 @@+# Bug Assessment: Monitoring an instrument track through an audio track crackles++- **Slug**: 563-monitor-crackle+- **Created**: 2026-11-11+- **Source**: https://github.com/nota-daw/nota/issues/563 (host: github.com — allowlisted)+- **Verdict**: valid+- **Severity**: medium++## Report (verbatim or summarized)++> **Monitoring an instrument track through an audio track crackles** (#563, label `bug`, `approved`)+>+> An audio track can take another track as its input. When that input is an instrument track and+> the audio track's monitoring is on, what you hear through the audio track crackles (clicks,+> distortion). Recording the same input works: the recorded take is clean. So the problem is in+> the monitoring path, not in how the input is captured.+>+> Steps: instrument track + audio track; audio track input = the instrument track; monitoring on;+> play notes → crackle. Arm and record → the clip plays back clean. Nota 0.59.2 (develop), macOS+> Apple Silicon.++## Symptom++An audio track monitoring another track (Input = a track, Monitor "In") plays the source with+clicks / distortion, while recording the same source into a take is clean. Expected: the monitored+signal is the source's post-fader output, delayed by a constant amount, with no discontinuities.++## Reproduction++1. Add an instrument track (any built-in synth) and an audio track.+2. Set the audio track's input to the instrument track; turn its monitoring on.+3. Play notes on the instrument → the monitored signal crackles.+4. Arm and record → the take is clean.++Condition found in the code (see below): the crackle needs render segments of **varying length**.+The reporter's machine outputs to a Bluetooth device (`outputDeviceUid` is a MAC address in+`audio.json`); Nota does not set a Bluetooth device's nominal rate+(`CoreAudioBackend.mm:167`), so the AUHAL converts the 44.1 kHz client stream to the device rate+and asks for a varying `inNumberFrames` per callback. The same happens on any device running at+another rate, and inside a callback at every loop seam / count-in end (`processBlock` splits the+segment there) — so it also clicks once per loop pass on a fixed-size device while looping.+[NEEDS CLARIFICATION: whether it also crackles on a wired device at the project rate with the+transport stopped — the code says it should not.]++## Suspected Code Paths++- `src/native/nota.engine/src/engine/Engine_Render.cpp:2433` `Engine::renderMonitorInput()` — for a+ track source it copies `frames` frames out of `routeBus_[slot]`, the source's post-fader tap from+ the *previous* segment.+- `Engine_Render.cpp:3348` (end of `mixGraph`) — `routeBus_[s].swap(routeBusNext_[s])`: the tap is+ double-buffered per segment, with no record of how many frames the previous segment wrote.+- `Engine_Render.cpp:2655` — `routeBusNext_` is cleared for `frames` only, so the frames past the+ previous segment's length hold whatever an older segment left there.+- `Engine_Render.cpp:2269` `processBlock()` — splits a callback at loop seams / count-in end into+ segments of different lengths.+- `src/audio_io/macos/CoreAudioBackend.mm:59` / `OutputRouting.h:137` — the device callback length+ passes straight through as the segment length (chunked at 4096).+- Recording path for comparison: `Engine_Render.cpp` Pass 1 pushes the source's post-fader samples+ of the *current* segment into `internalQueue_` (`w.tapRec`) — a continuous stream, hence clean.++## Root Cause Hypothesis++The monitor reads "the previous segment's tap, `frames` long". That is a clean one-block delay only+while every segment has the same length. When the length changes (AUHAL rate conversion gives e.g.+470/471/470… frames; a loop seam cuts one segment short), a longer segment reads past the end of+what the previous one wrote — stale samples from an older segment — and a shorter one drops the+tail of the previous segment. Each such seam is a discontinuity: with a varying callback size it+happens on most callbacks, which is heard as crackle/distortion. The recording path is a FIFO of+the current segment's samples, so it never loses or repeats a sample. Confidence: **high** for the+mechanism (it follows from the code), **medium** that it is the reporter's exact trigger (Bluetooth+output fits, not reproduced on their device).++## Proposed Remediation++**Preferred**: give the monitor a continuous stream instead of a per-segment snapshot. Keep, per+route slot, a small ring of the source's post-fader tap: after Pass 1 (where the swap happens now)+append this segment's `frames` to the slot's ring; `renderMonitorInput` reads `frames` frames at a+fixed lag behind the write position. The lag is the largest segment length seen so far (one block+on a fixed-size device, as today; on a varying device the largest callback), so a read never+crosses unwritten samples and no sample is dropped or repeated. Capacity 2 × `kMaxBlock` frames+per slot (allocated up front, RT-safe). Reset ring + lag where the route table is re-derived or+the engine (re)starts. Only monitoring reads the ring; sidechain keys keep `routeBus_`.++**Alternatives**:+- Render a monitoring track after its source in the same segment and read `routeBusNext_` (zero+ latency, matches recording timing). Needs ordering across parallel/serial paths, groups and+ monitor→monitor chains; much larger change for a bug fix.+- Fix the general route-bus contract (record the previous length, zero-fill the rest): removes+ stale data but still drops/zero-pads samples at every length change — still clicks.++**Files likely to change**:+- `src/native/nota.engine/src/engine/Engine.h` (ring + lag state)+- `src/native/nota.engine/src/engine/Engine_Render.cpp` (`renderMonitorInput`, tap publish)+- wherever the route table is re-derived (reset)+- `tests/Nota.SmokeTest/` — new test++**Tests to add or update**:+- Smoke test: instrument track playing a steady tone + audio track monitoring it; render offline in+ chunks of varying length (e.g. 470/471/333/512…) and assert the monitoring track's output is the+ source's output shifted by a constant lag (no sample lost or repeated) — fails before the fix.+- Same with constant chunks: unchanged one-block lag (regression guard).++## Risks & Considerations++- Real-time safety: ring buffers sized at construction, no allocation on the audio thread.+- Latency on a varying device becomes the largest callback seen (a few samples more than today's+ average); on a fixed-size device it is unchanged.+- Memory: 16 slots × 2 × 16384 × 2 floats ≈ 4 MB; could be sized to the slots actually used by+ monitors, or capped to the OutputStage chunk (4096) for live use.+- The same per-segment contract affects sidechain keys and the armed-track input meter; out of scope+ for #563 (detectors smooth it), worth a separate issue.++## Open Questions++- [NEEDS CLARIFICATION: does the reporter's case go away on a wired output at the project rate?+ Not needed for the fix — the test pins the mechanism.]diff --git a/.specify/bugs/563-monitor-crackle/fix.md b/.specify/bugs/563-monitor-crackle/fix.mdnew file mode 100644index 00000000..e2a2c98c--- /dev/null+++ b/.specify/bugs/563-monitor-crackle/fix.md@@ -0,0 +1,72 @@+# Bug Fix: Monitoring an instrument track through an audio track crackles++- **Slug**: 563-monitor-crackle+- **Fixed**: 2026-11-11+- **Assessment**: ./assessment.md+- **Status**: applied++## Summary++A monitoring audio track now reads its source track's post-fader tap from a per-slot ring at a+fixed lag, instead of copying "the previous segment, `frames` long" out of the double-buffered+route bus. Segments of varying length (a rate-converting device, a loop seam) no longer read+stale frames or drop any, so the monitored signal is continuous.++## Changes++| File | Change | Notes |+|------|--------|-------|+| `src/native/nota.engine/src/engine/Engine.h` | modified | `trackTapRing_` (one stereo ring per route slot, 2 × `kMaxBlock` frames), owner per slot, write position, `monitorLag_` + its one-second window; `advanceMonitorLag`, `publishTrackTapRings` |+| `src/native/nota.engine/src/engine/Engine.cpp` | modified | rings allocated in the constructor (no audio-thread allocation) |+| `src/native/nota.engine/src/engine/Engine_Render.cpp` | modified | `renderMonitorInput` reads the ring `monitorLag_` frames behind; `advanceMonitorLag` before Pass 1; `publishTrackTapRings` appends each whole-track slot's post tap before the route-bus swap; a slot that changes source starts from silence |+| `tests/Nota.SmokeTest/TrackMonitorTests.cs` | added test | fixed / varying / long-then-short block patterns |+| `tests/Nota.SmokeTest/Program.cs` | modified | `--track-monitor` alone, and in the full run |+| `CHANGELOG.md` | modified | `[Unreleased] → Fixed` entry |++## Diff Highlights (optional)++```cpp+// renderMonitorInput: the source's post-fader tap, monitorLag_ frames behind.+const int64_t from = trackTapRingPos_ - monitorLag_;+for (int32_t i = 0; i < frames; ++i) {+ const size_t k = static_cast<size_t>((from + i) & mask) * 2;+ dst[i * 2] = ring[k];+ dst[i * 2 + 1] = ring[k + 1];+}+```++The lag grows at once to the longest segment and shrinks to the longest segment of the last+second, so an export's 8192-frame chunks or a larger buffer don't keep their latency for good.+A change of lag crossfades from the old read position over ~10 ms (review on #567): shrinking,+the old position is further back and always written; growing, the fade is capped at the old+lag so the old read never reaches unwritten frames.++## Tests Added or Updated++- `TrackMonitorTests` (`--track-monitor`) — an audio track soloed while monitoring a sine clip on+ another track:+ - fixed 512-frame blocks: smooth (worst second difference) and exactly one block behind;+ - blocks of 470/471/470/333/512/128/1024/471: smooth and at a fixed lag (the longest block);+ - 4096-frame chunks for 0.5 s, then 256-frame blocks: smooth across the shrink (~2 s in) and+ the lag is back to 256;+ - 256-frame blocks for 1 s, then 1024: smooth across the growth, lag 1024.+ Without the crossfade the two lag-change checks fail (worst jumps 0.202 and 0.0828).++## Local Verification++- `cmake --build src/native/nota.engine/build` + `dotnet build tests/Nota.SmokeTest -c Release` → OK.+- `Nota.SmokeTest.dll --track-monitor`, engine **without** the fix (dylib copied into `bin/`):+ varying blocks FAIL — worst jump 0.389, correlation with the delayed source 0.445.+- Same, **with** the fix: all 5 PASS — worst jump 0.000442 (the sine's own), correlation 1.000.+- `scripts/build.sh` (full build + smoke run): see `test.md`.++## Deviations from Assessment++- Ring capacity is per slot for whole-track slots only (part slots never feed a monitor); the+ owner check is by track id.+- The armed-not-monitoring input meter (#352) still reads `routeBus_`: a meter, not heard.++## Follow-ups++- Sidechain keys and that input meter share the per-segment route-bus contract; a key read+ across varying segments sees the same stale frames (a detector smooths it). Worth its own issue.diff --git a/.specify/bugs/563-monitor-crackle/test.md b/.specify/bugs/563-monitor-crackle/test.mdnew file mode 100644index 00000000..a88c575f--- /dev/null+++ b/.specify/bugs/563-monitor-crackle/test.md@@ -0,0 +1,55 @@+# Bug Verification: Monitoring an instrument track through an audio track crackles++- **Slug**: 563-monitor-crackle+- **Tested**: 2026-11-11+- **Assessment**: ./assessment.md+- **Fix**: ./fix.md+- **Result**: partial++## Summary++The mechanism is reproduced and fixed in the engine: with blocks of varying length the monitored+signal had jumps of 0.389 before the fix and none after it (0.00044, the sine's own curvature),+at a fixed lag. The full smoke run passes apart from the render-pool timing checks, which fail+the same way on the unchanged engine on this loaded machine. Not exercised: the reporter's steps+in the app on a Bluetooth output — hence `partial`, not `verified`.++## Checks Performed++| Check | Command / Action | Result | Notes |+|-------|------------------|--------|-------|+| Reproduction, pre-fix (automated equivalent) | engine without the fix, dylib copied into `bin/`; `Nota.SmokeTest.dll --track-monitor` | fail (as expected) | varying blocks: worst jump 0.389, correlation 0.445 |+| Reproduction, post-fix (automated equivalent) | same, with the fix | pass | 5/5 |+| Reproduction in the app (instrument → audio track, Bluetooth output) | — | not-run | needs the real app + device by hand |+| New tests | `--track-monitor` | pass | fixed / varying / long-then-short blocks |+| Regression suite | `scripts/build.sh` (engine, solution, full smoke) | fail (3, unrelated) | all 4 FAIL lines are in `-- render pool --` (deadline / late-block timing) |+| Render-pool timing, fixed engine | `--perf` ×2 | fail | 2–3/100 deadlines, 200–243 late blocks |+| Render-pool timing, base engine | `--perf` ×2, fix stashed | fail | 41/100 deadlines, 163–210 late blocks: same failures without the fix |+| Lint / format | clang-format | skipped | not installed on this machine |++## Output Excerpts++```+== BEFORE FIX+ [FAIL] …and with blocks of varying length, as a rate-converting device asks (rms 0,129, worst jump 0,389)+ [FAIL] …at a fixed lag, the longest block (correlation 0,445)+== AFTER FIX+ [PASS] …and with blocks of varying length, as a rate-converting device asks (rms 0,141, worst jump 0,000442)+ [PASS] …at a fixed lag, the longest block (correlation 1,000)+ [PASS] …and the lag shrinks back once long chunks give way to short blocks (correlation 1,000, worst jump 0,000442)+```++`uptime` during the perf comparison: load averages 10.27 15.35 11.64.++## Residual Risks++- The reporter's trigger (Bluetooth output → varying callback sizes) is inferred from their+ `audio.json`, not observed in a live callback trace.+- The render-pool timing checks need a re-run on an idle machine (or CI) to confirm they pass.+- Sidechain keys and the armed input meter keep the per-segment route-bus read (follow-up).++## Recommendation++Hold for a by-hand check in the app (instrument track monitored through an audio track, on the+Bluetooth output, then on a loop), and re-run `scripts/build.sh` on an idle machine; then close+#563 with the PR.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f27d829..7e90d40c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -511,6 +511,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.MCP: `list_audio_inputs`, `set_track_input`, `get_track_input`.### Fixed+- **Monitoring a track through an audio track no longer crackles** (#563): an audio track whose+ input is another track (an instrument, say) played it with clicks while monitoring, though a+ recording of the same input was clean. It happened whenever the audio device asked for blocks+ of varying length, as a Bluetooth output or one running at another sample rate does, and once+ a pass at the loop seam. The monitored signal is now continuous, one block behind its source+ as before.- **Discard and retry keeps the count-in out of an audio take** (#521): retrying an audio takethat counted in from stop counted in again, but the input was recorded from the moment of theretry, so the new clip began with the count-in and ran late against the playhead by itsdiff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex 10ea7d43..8bc123a7 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -37,6 +37,8 @@ Engine::Engine()for (auto& s : routeSlotTrackId_) s.store(-1, std::memory_order_relaxed);for (auto& s : routeSlotPart_) s.store(0, std::memory_order_relaxed);silentKey_.assign(kMaxBlock * 2, 0.0f); // the key of a part that is gone (specs/050)+ for (auto& b : trackTapRing_) b.assign(static_cast<size_t>(kTrackTapRingFrames) * 2, 0.0f); // #563+ for (auto& s : trackTapRingTrack_) s = -1;ensureRenderScratch(authoring_->tracks.size());graphHist_.publish(authoring_);installRackPluginFactory(); // lets rack blobs rebuild hosted-plugin children on loaddiff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 26727fe3..c9769eff 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -2772,6 +2772,26 @@ class Engine {// the table is cleared and refilled in place), never touch a buffer out of range.std::atomic<int32_t> routeSlotCount_{0};std::vector<float> silentKey_; // kMaxBlock stereo zeros: the key of a part that is gone+ // Monitoring a track (#563): a detector can live with routeBus_'s "previous segment" view,+ // an ear can't — segments vary in length (a device that converts the rate, a loop seam), and+ // a longer segment would read stale frames past what the shorter one before it wrote. So+ // each slot's post tap is also appended to a ring, and a monitoring track reads it at a fixed+ // lag behind the write position: no frame lost or repeated, whatever the segment lengths.+ // The lag is the longest segment seen (one block on a fixed-size device, as before); it+ // comes back down after a second of shorter ones (an export's chunks, a smaller buffer).+ // A change of lag crossfades from the old read position over ~10 ms.+ // Audio thread only; sized in the constructor.+ static constexpr int32_t kTrackTapRingFrames = 2 * kMaxBlock; // power of two, > the largest lag+ std::array<std::vector<float>, kMaxRoutes> trackTapRing_; // stereo interleaved+ int32_t trackTapRingTrack_[kMaxRoutes]; // whose tap each ring holds (-1: none)+ int64_t trackTapRingPos_ = 0; // frames appended (same for every slot)+ int32_t monitorLag_ = 0; // read lag in frames+ int32_t monitorLagPeak_ = 0; // longest segment in the current window+ int64_t monitorLagWindow_ = 0; // frames into the window+ int32_t monitorLagFrom_ = 0; // the lag a change fades from+ int32_t monitorFadePos_ = 0, monitorFadeLen_ = 0; // that crossfade, in frames+ void advanceMonitorLag(int32_t frames); // audio thread, before any read this segment+ void publishTrackTapRings(int32_t frames); // audio thread, after the taps are filledvoid feedPartTaps(const Track& t); // audio threadconst float* keyBuffer(int32_t src, uint64_t part, bool pre) const; // audio thread// Audio + message thread.diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex ff262014..23b1fc9d 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -2458,8 +2458,86 @@ void Engine::renderMonitorInput(Graph* g, const Track& t, float* dst, int32_t fr}a = parent;}+ // The source's post-fader tap, `monitorLag_` frames behind: a continuous stream (#563).const int32_t slot = routeSlotForTrack(src);- if (slot >= 0) std::copy_n(routeBus_[slot].data(), frames * 2, dst);+ if (slot < 0 || trackTapRingTrack_[slot] != src) return; // routed this segment: silent once+ const float* ring = trackTapRing_[slot].data();+ constexpr int64_t mask = kTrackTapRingFrames - 1;+ const int64_t from = trackTapRingPos_ - monitorLag_; // before the first lag: the ring's zeros+ for (int32_t i = 0; i < frames; ++i) {+ const size_t k = static_cast<size_t>((from + i) & mask) * 2;+ dst[i * 2] = ring[k];+ dst[i * 2 + 1] = ring[k + 1];+ }+ // A lag that just changed crossfades from the old read position, so the change neither+ // skips nor repeats frames audibly. The old position stays inside what has been written+ // (see advanceMonitorLag), so both reads are real signal.+ if (monitorFadePos_ >= monitorFadeLen_) return;+ const int64_t old = trackTapRingPos_ - monitorLagFrom_;+ const int32_t n = std::min(frames, monitorFadeLen_ - monitorFadePos_);+ for (int32_t i = 0; i < n; ++i) {+ const float w = static_cast<float>(monitorFadePos_ + i) / static_cast<float>(monitorFadeLen_);+ const size_t k = static_cast<size_t>((old + i) & mask) * 2;+ dst[i * 2] = w * dst[i * 2] + (1.0f - w) * ring[k];+ dst[i * 2 + 1] = w * dst[i * 2 + 1] + (1.0f - w) * ring[k + 1];+ }+}++// The monitoring lag for this segment (#563): never shorter than the segment, so a read never+// reaches frames not yet written. It grows at once and shrinks to the longest segment of the+// last second, so an export's long chunks or a larger buffer don't keep their latency for good.+void Engine::advanceMonitorLag(int32_t frames) {+ const int32_t was = monitorLag_;+ int32_t lag = std::max(was, frames);+ if (frames > monitorLagPeak_) monitorLagPeak_ = frames;+ monitorLagWindow_ += frames;+ const double sr = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;+ if (static_cast<double>(monitorLagWindow_) >= sr) {+ if (monitorLagPeak_ < lag) lag = monitorLagPeak_;+ monitorLagPeak_ = 0;+ monitorLagWindow_ = 0;+ }+ if (lag == was) return;+ monitorLag_ = lag;+ // Crossfade from the old read position (~10 ms). Shrinking, the old position is further+ // back: written. Growing, it runs into unwritten frames `was` frames into this segment, so+ // the fade ends there. From nothing (the first segment) there is nothing to fade from.+ const int32_t fade = static_cast<int32_t>(0.010 * sr);+ monitorLagFrom_ = was;+ monitorFadePos_ = 0;+ monitorFadeLen_ = lag < was ? fade : std::min(fade, was);+}++// Append this segment's post-fader taps to the monitoring rings (#563). A slot that now mirrors+// another source starts from silence rather than the old source's frames.+void Engine::publishTrackTapRings(int32_t frames) {+ constexpr int64_t mask = kTrackTapRingFrames - 1;+ const int32_t n = routeSlotCount_.load(std::memory_order_acquire);+ for (int32_t s = 0; s < kMaxRoutes; ++s) {+ const int32_t id = s < n ? routeSlotTrackId_[s].load(std::memory_order_relaxed) : -1;+ if (id < 0) {+ trackTapRingTrack_[s] = -1;+ continue;+ }+ const uint64_t part = routeSlotPart_[s].load(std::memory_order_relaxed);+ if (part != 0) { // monitoring hears whole tracks only+ trackTapRingTrack_[s] = -1;+ continue;+ }+ float* ring = trackTapRing_[s].data();+ if (trackTapRingTrack_[s] != id) {+ std::fill_n(ring, static_cast<size_t>(kTrackTapRingFrames) * 2, 0.0f);+ trackTapRingTrack_[s] = id;+ }+ const float* tap = routeBusNext_[s].data();+ for (int32_t i = 0; i < frames; ++i) {+ const size_t k = static_cast<size_t>((trackTapRingPos_ + i) & mask) * 2;+ ring[k] = tap[i * 2];+ ring[k + 1] = tap[i * 2 + 1];+ }+ }+ trackTapRingPos_ += frames;+ if (monitorFadePos_ < monitorFadeLen_) monitorFadePos_ = std::min(monitorFadeLen_, monitorFadePos_ + frames);}// Per-leaf DSP for Pass 1 : render the track's dry stereo (pre-fader,@@ -2635,6 +2713,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b// monitoring it), and the set of tracks whose output some monitoring track hears —// those keep rendering while solo-gated, feeding only their route tap / record tap.pullMonitorInput(frames);+ advanceMonitorLag(frames); // a monitored track's lag, before any track reads it (#563)constexpr int kMaxFeeds = 16;int32_t feedIds[kMaxFeeds];int numFeeds = 0;@@ -3346,6 +3425,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b}// Phase B/D: publish this block's route taps (post + pre) for next block.+ publishTrackTapRings(frames); // and to the monitoring rings, before the swap (#563)for (int s = 0, n = routeSlotCount_.load(std::memory_order_acquire); s < n; ++s)if (routeSlotTrackId_[s].load(std::memory_order_relaxed) >= 0) {routeBus_[s].swap(routeBusNext_[s]);diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex acc3352b..e441c4c6 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -616,6 +616,14 @@ if (args.Length >= 1 && args[0] == "--audio-tails")Console.WriteLine(failures == 0 ? "AUDIO TAILS PASSED" : $"AUDIO TAILS FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Monitoring a track through an audio track (#563) alone: `--track-monitor`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--track-monitor")+{+ Console.WriteLine("-- monitoring a track --");+ foreach (var (ok, label) in TrackMonitorTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "TRACK MONITOR PASSED" : $"TRACK MONITOR FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Opt-in (needs a VST3 built and scanned): `--hosted-plugin <vst3 folder> <nota-scanworker>`.if (args.Length >= 3 && args[0] == "--hosted-plugin"){@@ -15839,6 +15847,8 @@ Console.WriteLine("-- device copy + rack undo --");foreach (var (ok, label) in DeviceCopyTests.Run()) Check(ok, label);Console.WriteLine("-- audio-track tails after Stop --");foreach (var (ok, label) in AudioTailTests.Run()) Check(ok, label);+Console.WriteLine("-- monitoring a track --");+foreach (var (ok, label) in TrackMonitorTests.Run()) Check(ok, label);Console.WriteLine("-- instrument chain --");foreach (var (ok, label) in InstrumentChainTests.Run()) Check(ok, label);foreach (var (ok, label) in DeviceGroupTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/TrackMonitorTests.cs b/tests/Nota.SmokeTest/TrackMonitorTests.csnew file mode 100644index 00000000..d85246bb--- /dev/null+++ b/tests/Nota.SmokeTest/TrackMonitorTests.cs@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Monitoring another track through an audio track (#563). The monitor used to copy its source's+// tap from the previous segment, `frames` long — clean only while every segment has the same+// length. A device that converts the rate (a Bluetooth output) asks for 470, 471, 470… frames,+// and a loop seam cuts a segment short; each change read stale frames or dropped some, and the+// monitored signal crackled. Now it reads a continuous stream at a fixed lag.+// Also runnable alone: `dotnet Nota.SmokeTest.dll --track-monitor`.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class TrackMonitorTests+{+ private const int Rate = 44100;++ public static IEnumerable<(bool ok, string label)> Run()+ {+ string wav = Wav();+ try+ {+ // A 330 Hz sine at 0.4 moves at most ~0.0009 per sample in its second difference; a+ // stale or dropped frame jumps by far more.+ var fixedX = Monitor(wav, [512]);+ var (fixedJump, fixedRms) = Smoothness(fixedX, Rate * 3 / 4, Rate * 7 / 4);+ yield return (fixedRms > 0.05 && fixedJump < 0.01,+ $"an audio track monitoring another track hears it whole with fixed blocks (rms {fixedRms:F3}, worst jump {fixedJump:G3})");+ double fixedLag = Match(fixedX, 512, Rate * 3 / 4, Rate * 7 / 4);+ yield return (fixedLag > 0.99, $"…one block behind its source, as before (correlation {fixedLag:F3})");++ var varX = Monitor(wav, [470, 471, 470, 333, 512, 128, 1024, 471]);+ var (varJump, varRms) = Smoothness(varX, Rate * 3 / 4, Rate * 7 / 4);+ yield return (varRms > 0.05 && varJump < 0.01,+ $"…and with blocks of varying length, as a rate-converting device asks (rms {varRms:F3}, worst jump {varJump:G3})");+ double varLag = Match(varX, 1024, Rate * 3 / 4, Rate * 7 / 4);+ yield return (varLag > 0.99, $"…at a fixed lag, the longest block (correlation {varLag:F3})");++ // An export's long chunks, then short live blocks: after a second of short ones the+ // lag comes back down to one short block (~2 s in), crossfading from the old read+ // position rather than skipping 3840 frames. Measured across the change itself.+ var downX = Monitor(wav, [256], warmup: [4096]);+ var (downJump, downRms) = Smoothness(downX, Rate * 3 / 4, Rate * 11 / 4);+ double downLag = Match(downX, 256, Rate * 9 / 4, Rate * 11 / 4);+ yield return (downRms > 0.05 && downJump < 0.01 && downLag > 0.99,+ $"…and the lag shrinks back smoothly once long chunks give way to short blocks (correlation {downLag:F3}, worst jump {downJump:G3})");++ // Short blocks, then longer ones (a larger buffer picked while monitoring, 1 s in):+ // the lag grows without repeating frames audibly.+ var upX = Monitor(wav, [1024], warmup: [256], warmupSeconds: 1.0);+ var (upJump, upRms) = Smoothness(upX, Rate * 3 / 4, Rate * 7 / 4);+ double upLag = Match(upX, 1024, Rate * 5 / 4, Rate * 7 / 4);+ yield return (upRms > 0.05 && upJump < 0.01 && upLag > 0.99,+ $"…and grows smoothly when longer blocks arrive (correlation {upLag:F3}, worst jump {upJump:G3})");+ }+ finally { try { File.Delete(wav); } catch { } }+ }++ // The monitoring track alone (soloed: its source still feeds it) over 3 s of the clip,+ // rendered in `chunks` (cycled), after `warmupSeconds` of `warmup` chunks if given.+ private static float[] Monitor(string wav, int[] chunks, int[]? warmup = null, double warmupSeconds = 0.5)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int src = e.AddAudioTrack();+ e.AddAudioClip(src, wav, 0.0);+ int mon = e.AddAudioTrack();+ e.SetTrackRecordInput(mon, src);+ e.SetTrackMonitor(mon, true);+ e.SetTrackSolo(mon, true);+ e.Seek(0.0);+ e.Play();+ var head = warmup != null ? Render(e, warmup, (int)(Rate * warmupSeconds)) : [];+ var tail = Render(e, chunks, 3 * Rate - head.Length / 2);+ return [.. head, .. tail];+ }++ // The worst second difference of the left channel and its RMS over [from, to) frames.+ private static (double Jump, double Rms) Smoothness(float[] x, int from, int to)+ {+ double jump = 0, sq = 0;+ for (int i = from; i < to; i++)+ {+ double l = x[i * 2];+ jump = Math.Max(jump, Math.Abs(l - 2 * x[(i - 1) * 2] + x[(i - 2) * 2]));+ sq += l * l;+ }+ return (jump, Math.Sqrt(sq / (to - from)));+ }++ // Normalized correlation of the left channel over [from, to) with the clip's sine `lag`+ // frames late (the clip starts on frame 0 of the render).+ private static double Match(float[] x, int lag, int from, int to)+ {+ double xy = 0, xx = 0, yy = 0;+ for (int i = from; i < to; i++)+ {+ double a = x[i * 2], b = Sine(i - lag);+ xy += a * b;+ xx += a * a;+ yy += b * b;+ }+ return xy / Math.Sqrt(Math.Max(1e-12, xx * yy));+ }++ private static float Sine(int i) => 0.4f * (float)Math.Sin(2 * Math.PI * 330 * i / Rate);++ private static float[] Render(NotaEngine e, int[] chunks, int frames)+ {+ var all = new float[frames * 2];+ var b = new float[chunks.Max() * 2];+ for (int done = 0, k = 0; done < frames; k++)+ {+ int n = Math.Min(chunks[k % chunks.Length], frames - done);+ e.RenderOffline(b, n);+ Array.Copy(b, 0, all, done * 2, n * 2);+ done += n;+ }+ return all;+ }++ private static string Wav()+ {+ var path = Path.Combine(Path.GetTempPath(), $"nota-monitor-{Guid.NewGuid():N}.wav");+ var x = new float[Rate * 4 * 2];+ for (int i = 0; i < x.Length / 2; i++) x[2 * i] = x[2 * i + 1] = Sine(i);+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, x.Length / 2);+ return path;+ }+}