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) Smooth Windows playback cursors (#423) (#424)
ret_xed29842b41acdf
diff --git a/.specify/bugs/piano-roll-playhead-stutter/assessment.md b/.specify/bugs/piano-roll-playhead-stutter/assessment.mdnew file mode 100644index 00000000..6630c9ee--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/assessment.md@@ -0,0 +1,67 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Bug Assessment: Piano-roll playhead still stutters++- **Slug**: piano-roll-playhead-stutter (user accepted)+- **Created**: 2026-11-01+- **Source**: pasted text+- **Verdict**: valid+- **Severity**: medium++## Report++> the aranger cursor works perfectly but not the piano roll++## Symptom and Reproduction++On the current Windows build, open an arrangement MIDI clip and play. The arrangement+cursor is smooth but the piano-roll cursor still advances in steps. Expected: both+follow the same authoritative transport presentation position.++## Suspected Code Paths and Root Cause++High confidence: MainWindow.Playhead.cs explicitly excludes the piano roll from its+animation-frame loop. MainWindow.axaml.cs feeds it only from PlayheadUpdated (the+33 ms Background dispatcher service timer). PianoRollView.SetPlayhead invalidates+the full NoteGrid and RulerLane, which draw the cursor alongside all notes/beat labels.+Thus the previous arrangement fix did not reach this editor. Session slots use their+own authoritative clock and must retain that mapping.++## Proposed Remediation++Put the ruler and note-grid cursor strokes in separate clipped, non-interactive+overlay controls. Invalidate only these for a cursor change; also invalidate them on+zoom/scroll/content changes. Keep all existing cursor styling, visibility/range and+ruler/grid seeking semantics. Feed arrangement MIDI cursors from the existing+bounded TransportDisplayPosition calculation on animation frames, using roll.Origin+for single/multiple clips. Suppress the slower service updates while frame delivery+is active, retaining stopped/fallback updates and the separate Session-slot clock.+Reuse existing docked/floating window ownership and shutdown/suspension checks.++**Files likely to change**:+- src/managed/Nota.App/MainWindow.Playhead.cs+- src/managed/Nota.App/MainWindow.axaml.cs+- src/managed/Nota.App/PianoRollView.cs+- CHANGELOG.md+- Diagnostics under this bug directory (no new dependencies).++**Tests to add or update**:+- Instrument the actual main window and its real clip editor before/after the fix;+ compare arrangement and piano-roll cursor changes per animation callback.+- Count NoteGrid/RulerLane render calls: cursor-only animation must not repaint them.+- Exercise stopped seeks, out-of-range hiding, horizontal zoom/scroll, pause/resume,+ song loops, floating editor with minimized main window, suspension and shutdown.+- Build Release and run the Windows smoke checks.++## Risks & Considerations++Overlays must stay clipped to the existing columns and scroll with their grid, allow+pointer input through to existing controls, and follow theme slots. Service ticks must+not overwrite interpolated beats. No native engine, audio processing or ABI changes.+Frame sampling measures cursor property changes, not physical monitor presentation.++## Open Questions++No blocking questions for the arrangement MIDI editor. Session-slot interpolation+is outside this remediation; its own clock and existing update cadence are retained.diff --git a/.specify/bugs/piano-roll-playhead-stutter/diagnostics/.gitignore b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/.gitignorenew file mode 100644index 00000000..eb9871bd--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/.gitignore@@ -0,0 +1,6 @@+bin/+obj/+probe-data/+*.log+*.png+/*.jsondiff --git a/.specify/bugs/piano-roll-playhead-stutter/diagnostics/PianoProbe.csproj b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/PianoProbe.csprojnew file mode 100644index 00000000..4a857a64--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/PianoProbe.csproj@@ -0,0 +1,17 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <UseAppHost>false</UseAppHost>+ <NotaBinaries>$(MSBuildThisFileDirectory)..\..\..\..\src\managed\Nota.App\bin\Release\net10.0</NotaBinaries>+ </PropertyGroup>+ <ItemGroup>+ <FrameworkReference Include="Microsoft.AspNetCore.App" />+ <Reference Include="$(NotaBinaries)\*.dll" Exclude="$(NotaBinaries)\nota_engine.dll" />+ <None Include="$(NotaBinaries)\nota_engine.dll;$(NotaBinaries)\runtimes\win-x64\native\*.dll" Link="%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />+ </ItemGroup>+</Project>diff --git a/.specify/bugs/piano-roll-playhead-stutter/diagnostics/Program.cs b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/Program.csnew file mode 100644index 00000000..71a69ebf--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/Program.cs@@ -0,0 +1,206 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Diagnostics;+using System.Reflection;+using System.Text.Json;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.ApplicationLifetimes;+using Avalonia.Rendering.Composition;+using Avalonia.Media.Imaging;+using Avalonia.Threading;+using Nota.App;+using Nota.Application;+using Nota.Presentation;++// Runs the actual App/clip editor with scratch settings and generated MIDI content.+// Draw-list replacements count re-recordings of static content, not presented frames.+internal static class Program+{+ const BindingFlags Hidden = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;+ static object? Field(object o, string n) => o.GetType().GetField(n, Hidden)!.GetValue(o);+ static object? Call(object o, string n, params object[] a) => o.GetType().GetMethods(Hidden)+ .Single(m => m.Name == n && m.GetParameters().Length == a.Length).Invoke(o, a);+ static object? DrawList(Control c)+ {+ var v = ElementComposition.GetElementVisual(c);+ return v?.GetType().GetProperty("DrawList", Hidden)?.GetValue(v);+ }+ [STAThread]+ static int Main(string[] args)+ {+ try { Run(args); return 0; }+ catch (Exception e) { Console.Error.WriteLine(e); return 1; }+ }+ static void Run(string[] args)+ {+ string mode = args[0], output = Path.GetFullPath(args[1]);+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);+ Environment.SetEnvironmentVariable("NOTA_DATA_DIR", Path.Combine(Path.GetDirectoryName(output)!, "probe-data", Path.GetFileNameWithoutExtension(output)));+ var lifetime = new ClassicDesktopStyleApplicationLifetime { ShutdownMode = ShutdownMode.OnExplicitShutdown };+ AppBuilder.Configure<Nota.App.App>().UseWin32().UseSkia().UseHarfBuzz().WithNotaFonts().SetupWithLifetime(lifetime);+ var settings = (ISettingsService)App.Services.GetService(typeof(ISettingsService))!;+ settings.Current.ShowWelcomeOnStartup = false; settings.Current.CheckForUpdates = false;+ settings.Current.LastSeenVersion = AppInfo.Version;+ var vm = (MainWindowViewModel)App.Services.GetService(typeof(MainWindowViewModel))!;+ string requestedAsio = args.Length > 2 ? args[2] : "";+ if (requestedAsio.Length > 0)+ {+ var driver = vm.Engine.AsioDrivers().Single(d => d.Name == requestedAsio);+ vm.Engine.SetAudioSystem(AudioSystem.Asio);+ vm.Engine.SetAsioDriver(driver.Uid);+ vm.ApplyAudioSettings();+ if (!vm.Engine.IsRunning || vm.Engine.ActiveAudioSystem != AudioSystem.Asio)+ throw new InvalidOperationException("Requested ASIO device is unavailable: " + vm.Engine.AudioFallbackReason);+ }+ using var stop = new CancellationTokenSource();+ Exception? error = null; bool completed = false;+ var checks = new List<string>();+ void Require(bool ok, string text) { if (!ok) throw new InvalidOperationException(text); checks.Add(text); }+ void Fail(Exception e) { error = e; stop.Cancel(); }+ DispatcherTimer.RunOnce(() =>+ {+ try+ {+ var main = (MainWindow)lifetime.MainWindow!;+ main.WindowState = WindowState.Normal; main.Width = 1280; main.Height = 900;+ while (vm.Engine.TrackCount > 0) { vm.Engine.TryGetTrackInfo(0, out var info); vm.Engine.RemoveTrack(info.Id); }+ int id = vm.Engine.AddInstrumentTrack(); int ci = vm.Engine.AddMidiClip(id, 4, 64);+ var notes = Enumerable.Range(0, 128).Select(i => new NotaNote(48 + i % 24, i * .5, .25, .6f)).ToArray();+ vm.Engine.SetClipNotes(id, ci, notes);+ var timeline = main.FindControl<ArrangementView>("Timeline")!;+ timeline.Refresh(); timeline.SelectTrackFromOutside(id);+ Call(main, "BuildClipEditor", id, ci); Call(main, "ShowClipPanel");+ var roll = (PianoRollView)Field(main, "_editorRoll")!;+ var grid = (Control)Field(roll, "_gridControl")!;+ var ruler = (Control)Field(roll, "_ruler")!;+ // The visible probe must not accept real wheel/hover/edit input during the+ // cursor-only recording: those interactions legitimately repaint the grid.+ main.IsEnabled = false;+ vm.Engine.SetCountIn(0); vm.Engine.SetMetronome(false); vm.Engine.Seek(4); vm.Engine.Play();+ var clock = Stopwatch.StartNew();+ var cursorTimes = new List<double>(); var arrangementTimes = new List<double>();+ int frameCount = 0, gridDraws = 0, rulerDraws = 0;+ object? oldGrid = null, oldRuler = null;+ double previous = double.NaN, previousArrangement = double.NaN;+ int stage = 0; double stageAt = 0; bool finishedFrames = false;+ var xrunStart = vm.Engine.XrunCount;+ Window frameOwner = main;+ Action<TimeSpan>? sample = null;+ sample = _ =>+ {+ try+ {+ double now = clock.Elapsed.TotalMilliseconds;+ double beat = (double)Field(roll, "_playheadBeat")!;+ if (now >= 1000 && now < 6000)+ {+ frameCount++;+ if (beat != previous) { cursorTimes.Add(now); previous = beat; }+ double ab = (double)Field(timeline, "_displayPlayheadBeats")!;+ if (ab != previousArrangement) { arrangementTimes.Add(now); previousArrangement = ab; }+ var gd = DrawList(grid); var rd = DrawList(ruler);+ if (gd is null || rd is null) throw new InvalidOperationException("Cannot inspect composition draw lists");+ if (oldGrid is not null && !ReferenceEquals(oldGrid, gd))+ {+ gridDraws++;+ Console.Error.WriteLine($"grid redraw at {now:F1}: bounds={grid.Bounds}, ppb={Field(roll, "_pixelsPerBeat")}, scroll={Field(roll, "_scrollBeats")}, hover={Field(grid, "_hoverNote")}");+ }+ if (oldRuler is not null && !ReferenceEquals(oldRuler, rd)) rulerDraws++;+ oldGrid = gd; oldRuler = rd;+ }+ if (now >= 6000 && !finishedFrames)+ {+ finishedFrames = true;+ main.IsEnabled = true;+ Console.Error.WriteLine(JsonSerializer.Serialize(new { frameCount, cursorUpdates = cursorTimes.Count, gridDraws, rulerDraws }));+ if (mode != "before")+ {+ Require(cursorTimes.Count > frameCount * .9, "piano roll changes on at least 90% of animation callbacks");+ Require(gridDraws == 0 && rulerDraws == 0, $"cursor animation preserves note-grid and ruler draw lists (grid {gridDraws}, ruler {rulerDraws})");+ }+ vm.Engine.StopTransport(); vm.Engine.Seek(9); stageAt = now;+ }+ if (finishedFrames && now - stageAt >= 300)+ {+ switch (stage++)+ {+ case 0:+ Require(Math.Abs(beat - 5) < .001, "paused seek maps global beat through clip origin");+ if (mode != "before")+ {+ var gl = (Control)Field(roll, "_gridPlayhead")!;+ var rl = (Control)Field(roll, "_rulerPlayhead")!;+ Require(gl.Bounds == grid.Bounds && rl.Bounds == ruler.Bounds,+ "cursor layers match content geometry");+ Require(!gl.IsHitTestVisible && !rl.IsHitTestVisible && gl.ClipToBounds && rl.ClipToBounds,+ "cursor layers clip without intercepting editing gestures");+ Call(roll, "ZoomAt", 2.0, 5.0);+ Call(roll, "SetScrollBeats", 2.0);+ Require(Math.Abs((double)Field(roll, "_scrollBeats")! - 2) < .001,+ "horizontal zoom and scroll retain cursor transform");+ Require((double)Call(roll, "BeatToX", 5.0)! > 0,+ "cursor remains in the scrolled viewport");+ using var image = new RenderTargetBitmap(new PixelSize((int)main.Bounds.Width, (int)main.Bounds.Height));+ image.Render(main); image.Save(Path.ChangeExtension(output, ".png"));+ }+ roll.SetPlayhead(65, true); Require((double)Field(roll, "_playheadBeat")! < 0, "outside clip hides cursor");+ roll.SetPlayhead(3, false); Require((double)Field(roll, "_playheadBeat")! < 0, "playing=false hides cursor");+ Call(roll, "SetScrollBeats", 2.0);+ vm.Engine.Seek(10); vm.Engine.Play(); break;+ case 1:+ Require(beat > 6, "resuming advances cursor after seek");+ vm.Engine.SetLoop(true, 10, 10.25); break;+ case 2:+ Require(beat >= 6 && beat <= 6.25, "song loop stays within clip-local bounds");+ Call(main, "OnToggleDetailWindow", null!, new Avalonia.Interactivity.RoutedEventArgs());+ main.WindowState = WindowState.Minimized;+ frameOwner = (Window)Field(main, "_detailWindow")!; break;+ case 3:+ Require(Field(main, "_playheadFrameOwner") == frameOwner && roll.IsEffectivelyVisible,+ "floating editor owns frames when arrangement is minimized");+ vm.SuspendEnginePolling = true; break;+ case 4:+ Require(Field(main, "_playheadFrameOwner") is null, "suspension stops frame delivery");+ vm.SuspendEnginePolling = false; break;+ case 5:+ Require(Field(main, "_playheadFrameOwner") == frameOwner, "resuming polling restarts floating frames");+ vm.Engine.StopTransport(); break;+ case 6:+ Require(Field(main, "_playheadFrameOwner") is null, "pause detaches animation loop");+ vm.Engine.SetLoop(false, 0, 4); vm.Engine.Seek(11); break;+ case 7:+ Require(Math.Abs(beat - 7) < .001, "stopped seek updates floating piano roll");+ var gaps = cursorTimes.Zip(cursorTimes.Skip(1), (a,b) => b-a).Order().ToArray();+ var result = new {+ mode, backend = vm.Engine.ActiveAudioSystem.ToString(), vm.Engine.NegotiatedBufferFrames,+ requestedAsio,+ frameCount, cursorUpdates = cursorTimes.Count, arrangementUpdates = arrangementTimes.Count,+ cursorUpdatesPerSecond = 1000 / gaps.Average(), medianGapMs = gaps[gaps.Length/2],+ p95GapMs = gaps[(int)(gaps.Length*.95)], gridDraws, rulerDraws,+ dropouts = vm.Engine.XrunCount - xrunStart, checks+ };+ typeof(MainWindow).GetField("_closeConfirmed", Hidden)!.SetValue(main, true);+ main.Close();+ Require(Field(main, "_playheadFrameOwner") is null, "closing detaches animation loop");+ File.WriteAllText(output, JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));+ completed = true; stop.Cancel(); return;+ }+ stageAt = now;+ }+ frameOwner.RequestAnimationFrame(sample!);+ }+ catch (Exception e) { Fail(e); }+ };+ main.RequestAnimationFrame(sample);+ }+ catch (Exception e) { Fail(e); }+ }, TimeSpan.FromMilliseconds(800));+ using var watchdog = new Timer(_ => Dispatcher.UIThread.Post(() => stop.Cancel()), null, 25000, Timeout.Infinite);+ Dispatcher.UIThread.MainLoop(stop.Token);+ if (error is not null) throw error;+ if (!completed) throw new InvalidOperationException("Timed out before completing probe");+ Console.WriteLine(File.ReadAllText(output));+ }+}diff --git a/.specify/bugs/piano-roll-playhead-stutter/diagnostics/README.md b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/README.mdnew file mode 100644index 00000000..a8de050f--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/diagnostics/README.md@@ -0,0 +1,12 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Piano-roll diagnostic results++The JSON outputs cited in the bug assessment, fix and verification report are preserved+on [pr-assets](https://github.com/thoi1/nota/tree/pr-assets/issue-423/historical-results/piano-roll-playhead-stutter/diagnostics).++See [the verification report](../test.md) for reproduction commands. Running PianoProbe+regenerates the ignored local JSON/PNG files using scratch settings and generated MIDI+content. The diagnostic source remains with the fix; recorded measurements live with+the PR evidence.diff --git a/.specify/bugs/piano-roll-playhead-stutter/fix.md b/.specify/bugs/piano-roll-playhead-stutter/fix.mdnew file mode 100644index 00000000..69ad7059--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/fix.md@@ -0,0 +1,56 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Bug Fix: Piano-roll playhead still stutters++- **Slug**: piano-roll-playhead-stutter (from assessment context)+- **Fixed**: 2026-11-01+- **Assessment**: ./assessment.md+- **Status**: applied++## Summary++Arrangement MIDI editor cursors now use the existing bounded frame-timed transport+presentation position. Independent note-grid and ruler overlays move without+re-recording static note/grid/label drawing commands.++## Changes++| File | Change | Notes |+|------|--------|-------|+| src/managed/Nota.App/MainWindow.Playhead.cs | modified | Deliver frame position minus editor Origin to visible arrangement MIDI editors. |+| src/managed/Nota.App/MainWindow.axaml.cs | modified | Retain stopped/fallback and Session updates; prevent service ticks overwriting frame positions. |+| src/managed/Nota.App/PianoRollView.cs | modified | Two non-interactive clipped cursor layers in existing layout cells; repaint on cursor or view-transform changes. Remove strokes from static content. |+| CHANGELOG.md | modified | Unreleased fix entry. |+| diagnostics/PianoProbe.csproj, diagnostics/Program.cs, diagnostics/.gitignore | added | Reproducible actual-App diagnostic using existing binaries and scratch settings. |++## Tests Added or Updated++PianoProbe compares actual piano-roll and arrangement cursor changes on animation+callbacks, and inspects composition draw-list replacement counts for the notes and+ruler. It exercises stopped seeks, hiding, resume, song loops, floating detail with+minimized main window, polling suspension and shutdown. Before mode records baseline+without asserting the new cadence/render-isolation requirements.++## Local Verification++- Release app build: passed, 0 errors (26 existing warnings).+- Actual-App baseline: 150 piano cursor changes / 1120 callbacks in five seconds,+ 29.90 changes/s; 150 grid and 150 ruler draw-list replacements.+- Post-fix: 1116 cursor changes / 1116 callbacks, 223.18 changes/s; zero grid/ruler+ draw-list replacements and zero reported dropouts. Lifecycle checks passed.+- git diff --check: passed.+- Full Windows regression checks are recorded by the subsequent bug-test report.++## Deviations from Assessment++Composition draw-list identity replaces production render counters: it observes the+actual renderer re-recording static controls without adding instrumentation to the app.+No source scope expansion. No native/DSP/ABI or theme changes.++## Follow-ups++Run speckit-bug-test for the full Windows checks and final report. The nota-features+and nota-docs trigger rules were reviewed: this restores expected cursor smoothness,+adds no capability and changes no documented workflow, so no manual/feature-list+change is needed. Session-slot interpolation remains outside this fix.diff --git a/.specify/bugs/piano-roll-playhead-stutter/test.md b/.specify/bugs/piano-roll-playhead-stutter/test.mdnew file mode 100644index 00000000..af181d35--- /dev/null+++ b/.specify/bugs/piano-roll-playhead-stutter/test.md@@ -0,0 +1,88 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Bug Verification: Piano-roll playhead still stutters++- **Slug**: piano-roll-playhead-stutter (from assessment/fix context)+- **Tested**: 2026-11-01+- **Assessment**: ./assessment.md+- **Fix**: ./fix.md+- **Result**: verified++## Summary++The actual App's arrangement MIDI piano roll now advances on every observed animation+callback, matching the arrangement. Cursor-only animation retains the notes and ruler+composition draw lists. The rebuilt Windows Release app passes the full build/smoke/+scanner checks and the real-window lifecycle diagnostic on WASAPI and Yamaha ASIO.++## Checks Performed++| Check | Command / Action | Result | Notes |+|-------|------------------|--------|-------|+| Before-fix reproduction | PianoProbe before diagnostics/before.json | pass (bug reproduced) | 150 cursor updates / 1120 frame callbacks; 150 grid and 150 ruler draw-list replacements. |+| WASAPI final reproduction | PianoProbe after diagnostics/after-final.json | pass | 1176 cursor and arrangement updates / 1176 callbacks; 235.20 changes/s; zero static draw-list replacements and zero reported dropouts. |+| Yamaha Steinberg USB ASIO | PianoProbe after diagnostics/after-yamaha-isolated.json "Yamaha Steinberg USB ASIO" | pass | Active backend Asio, negotiated 64 frames; 1175 cursor and arrangement updates / 1175 callbacks, 235.03 changes/s; zero static replacements and zero dropouts. |+| Seeks and playback | Automated actual clip editor checks | pass | Nonzero clip origin, paused/stopped seeks, hiding outside clip, playing=false, resume and repeated song loops. |+| Overlay geometry and transforms | Reflection and real-window capture | pass | Existing ruler/grid bounds match their overlays; clipped and non-interactive; horizontal zoom and scrolling work. |+| Floating editor and lifecycle | Actual detail popout, minimize, suspend, resume, close | pass | Floating window takes frame ownership when main is minimized; suspend/pause/close detach callbacks; stopped seek still updates. |+| Full Windows regression | scripts/build-win.ps1 from VS x64 developer environment | pass | Exit 0; SMOKE TEST PASSED; SCAN SCALE PASSED; scanner self-test passed. |+| Whitespace | git diff --check | pass | No errors. |++## Diagnostic Refinement++Earlier unisolated ASIO runs passed the cursor-cadence assertion but failed the strict+zero-static-redraw assertion (one repeat counted 41 replacements; another counted 11).+The instrumented repeat captured pixels-per-beat changing from 15.625 through 18.75,+22.5 and 27 during the nominal cursor-only interval, before the probe's own zoom step.+Interactive zoom legitimately redraws notes/ruler, invalidating a cursor-only premise.+The first failed run did not record enough input state to determine its precise cause.++The final probe disables input in its temporary main window only during the initial+cursor-only interval, then restores it before lifecycle/geometry checks. That isolated+ASIO run passed with zero replacements. No production changes were made in response+to those diagnostic assertions. The prior successful unisolated ASIO run is retained+as after-yamaha.json (235.60 changes/s, 0 replacements, 0 dropouts).++## Output Excerpts++```text+Before: cursorUpdates=150, frameCount=1120, gridDraws=150, rulerDraws=150+After WASAPI: cursorUpdates=1176, frameCount=1176, gridDraws=0, rulerDraws=0+After isolated Yamaha ASIO: cursorUpdates=1175, frameCount=1175, gridDraws=0, rulerDraws=0+SMOKE TEST PASSED+SCAN SCALE PASSED+```++## Reproduce++From the repository root, after building Release:++```powershell+dotnet build .specify/bugs/piano-roll-playhead-stutter/diagnostics/PianoProbe.csproj+dotnet .specify/bugs/piano-roll-playhead-stutter/diagnostics/bin/Debug/net10.0/PianoProbe.dll after .specify/bugs/piano-roll-playhead-stutter/diagnostics/recheck.json+dotnet .specify/bugs/piano-roll-playhead-stutter/diagnostics/bin/Debug/net10.0/PianoProbe.dll after .specify/bugs/piano-roll-playhead-stutter/diagnostics/recheck-yamaha.json "Yamaha Steinberg USB ASIO"+```++The probe opens the real app with scratch settings and generated MIDI notes, never a+user project. It also captures a local PNG beside each successful final JSON output.+Inspected after-final.png: cursor aligned through ruler and grid, correctly clipped+after zoom/scroll. Logs, images and scratch data are ignored; source and small JSON+measurements are retained. Local full build log: diagnostics/build-win.log.++## Residual Risks++- Counts measure actual cursor-property changes on animation callbacks, not physical+ monitor/compositor presentation or a guarantee for every machine.+- Musical/status colours, editing data, native audio/ABI and Session-slot clock semantics+ were not changed. This fixes arrangement MIDI editors; Session-slot interpolation+ remains outside scope.+- The diagnostic verifies pointer-routing properties and transforms; full interactive+ ruler scrubbing/note editing across all display scales remains a manual check.+- The diagnostic screenshot call has an existing-API deprecation warning; the app build+ succeeds with its existing unrelated warnings.++## Recommendation++Close this arrangement MIDI editor follow-up as verified. Restart the Release executable+at src/managed/Nota.App/bin/Release/net10.0/Nota.App.exe to test the updated cursor.diff --git a/.specify/bugs/windows-playhead-stutter/.gitignore b/.specify/bugs/windows-playhead-stutter/.gitignorenew file mode 100644index 00000000..74976db2--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/.gitignore@@ -0,0 +1,5 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+diagnostics/*.log+diagnostics/probe-data/+/diagnostics/**/*.jsondiff --git a/.specify/bugs/windows-playhead-stutter/asio-test.md b/.specify/bugs/windows-playhead-stutter/asio-test.mdnew file mode 100644index 00000000..da1a69d2--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/asio-test.md@@ -0,0 +1,89 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# ASIO Verification: Windows playhead++- **Slug**: windows-playhead-stutter+- **Tested**: 2026-11-01+- **Assessment**: ./assessment.md+- **Fix**: ./fix.md+- **Earlier verification**: ./test.md (WASAPI)+- **Result**: verified on Yamaha Steinberg USB ASIO at 48 kHz / 64 frames++## Summary++The user selected Yamaha Steinberg USB ASIO from the installed drivers. The actual Nota+window and engine successfully ran that driver at 48,000 Hz with 64-frame callbacks.+The final frame path updated the Arrangement cursor on all 1,184 observed animation+callbacks, approximately 237 times per second. The original timer path updated it about+22 times per second. No run reported an audio dropout or a fallback to WASAPI.++## Driver and Environment++- Windows build: `Microsoft Windows NT 10.0.26300.0`.+- Driver: `Yamaha Steinberg USB ASIO`.+- Driver CLSID: `{CB7F9FFD-A33B-48B2-8BC0-437D94F37142}`.+- Actual active backend: `Asio`, checked throughout each frame or lifecycle callback.+- Negotiated sample rate / buffer: 48 kHz / 64 frames in all three runs.+- Fallback reason: empty in all three runs.++The diagnostic uses scratch Nota settings and the driver's existing buffer setting.+It does not open the driver's control panel or change its buffer setting. This task+changed only diagnostic code/documentation and added evidence; no production code+changes were needed for the ASIO check.++## Checks Performed++| Check | Result | Evidence |+|-------|--------|----------|+| Diagnostic build | pass | `dotnet build .specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj --nologo -v quiet`, exit 0, no warnings/errors |+| Actual ASIO startup | pass | Active backend remained ASIO; exact requested driver ID confirmed |+| Original timer path | pass | `diagnostics/app-asio-yamaha-legacy-results.json` |+| Final frame path | pass | `diagnostics/app-asio-yamaha-frames-results.json` |+| Lifecycle integration | pass | All 12 checks in `diagnostics/app-asio-yamaha-lifecycle-results.json` |+| Whitespace | pass | `git diff --check` |++The three executions exited 0. The lifecycle checks cover play, export suspension,+backend stop/start and resume, minimize/restore, seek, short repeated loops, tempo+changes, stop to the launch anchor, replay, closing, and a late callback after engine+disposal. The lifecycle result also confirms ASIO remained active after restarting+the audio backend.++## Measured Cursor Cadence++| Path | Cursor changes/s | Median gap | 95th percentile | Observed callbacks / cursor changes | Reported dropouts |+|------|-----------------:|-----------:|----------------:|-----------------------------------:|------------------:|+| Original service timer | 22.22 | 47.43 ms | 48.89 ms | 453 / 112 | 0 |+| Final frame path | 236.80 | 4.16 ms | 4.40 ms | 1184 / 1184 | 0 |++These are actual Arrangement display-position changes sampled on animation callbacks+over five seconds on this high-refresh display. They are not physical compositor+presentation measurements. The empty-project comparison uses the same production+window, native engine, driver and negotiated buffer; `legacy` disables only the newly+added frame loop so the existing service timer drives the cursor directly.++## Reproduce++From the repository root after the Windows Release build:++```powershell+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj -- frames .specify/bugs/windows-playhead-stutter/diagnostics/app-asio-yamaha-frames-results.json 0 "Yamaha Steinberg USB ASIO"+```++Use `legacy` or `lifecycle` instead of `frames` with a corresponding result file for+the other checks. The probe writes an explicit failure and exits unsuccessfully if+the requested ASIO driver is unavailable or the engine falls back to WASAPI.++## Coverage Limits++- Covers the selected Yamaha driver at its current 64-frame buffer and 48 kHz rate;+ other driver settings and other installed ASIO drivers were not exercised.+- Measures the reported empty-project playhead behavior, not loaded-project DSP+ performance or an audible-content playback test.+- Existing WASAPI results remain in `test.md`; that historical report was not overwritten.++## Recommendation++The empty-project playhead fix is also verified on the user's selected Yamaha+Steinberg USB ASIO configuration. No additional ASIO-specific fix is indicated by+these checks.diff --git a/.specify/bugs/windows-playhead-stutter/assessment.md b/.specify/bugs/windows-playhead-stutter/assessment.mdnew file mode 100644index 00000000..febef24e--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/assessment.md@@ -0,0 +1,107 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Bug Assessment: Windows playhead stutters even in an empty project++- **Slug**: windows-playhead-stutter (accepted by the user)+- **Created**: 2026-11-01+- **Source**: pasted text and follow-up clarification+- **Revision inspected**: 55c3c29f+- **Verdict**: likely valid, needs reproduction of the complete application's visible symptom; uneven Windows timer cadence reproduced in isolation+- **Severity**: medium — affects basic playback feedback even without project content; no evidence of data loss or an audio dropout in this investigation++## Report (verbatim or summarized)++> inspect the nota source code and identify the bug that causes stuttering playhead in windows system++Follow-up clarification: **Even in an empty project**.++## Symptom++The playback cursor advances in visible steps on Windows with an empty project. Expected: smooth movement synchronized to the engine transport, independent of clips or open editors.++## Reproduction++User-reported application scenario: an empty project on Windows during playback. Exact application version, audio backend, buffer size, display refresh rate and steps beyond this are [NEEDS CLARIFICATION].++An isolated reproduction of the timing defect is included under `diagnostics/`. It compiles the repository's actual `AvaloniaPeriodicTimerFactory` and `IPeriodicTimer` sources, initializes the Windows Avalonia dispatcher without creating a window, and records 120 intervals with a nearly empty callback. It uses the existing Release build's Avalonia 12.1.4 assemblies; it adds no application dependency.++From the repository root, after a Windows Release build exists at `src/managed/Nota.App/bin/Release/net10.0`:++```powershell+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/TimerProbe.csproj -- src/managed/Nota.App/bin/Release/net10.0/nota_engine.dll+```++Measured on this machine (`Microsoft Windows NT 10.0.26300.0`, .NET 10.0.14):++| Probe | Requested interval | Mean | Median | 95th percentile | Actual update rate |+|---|---:|---:|---:|---:|---:|+| Windows dispatcher, no engine DLL loaded | 33 ms | 45.19 ms | 47.68 ms | 48.54 ms | 22.13/s |+| Same, with native engine DLL loaded | 33 ms | 44.65 ms | 47.59 ms | 48.15 ms | 22.40/s |++Raw samples: `diagnostics/timer-results.json` and `diagnostics/timer-engine-loaded-results.json`. An earlier unrecorded successful run also averaged 44.64 ms / 22.40 updates per second. Loading the native DLL controls for its static initialization, including JUCE's Windows timer-period request. The probe does **not** start the audio backend, show a window, or measure presented frames: these figures establish the timer defect, not the precise frame rate of a running Nota window.++## Suspected Code Paths++- `src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs:102` — creates the sole playhead polling clock with a fixed 33 ms interval.+- `src/managed/Nota.App/AvaloniaPeriodicTimer.cs:23` — implements that clock with the parameterless `DispatcherTimer` constructor, which defaults to Background priority.+- `src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs:113` — each tick runs engine polling and transport readout updates before invoking all `PlayheadUpdated` subscribers with the raw `Engine.PositionBeats` value.+- `src/managed/Nota.App/MainWindow.axaml.cs:303` — the event directly calls `Timeline.SetPlayhead(beats)` alongside meters, live device controls and other UI work.+- `src/managed/Nota.App/ArrangementView.cs:693` — stores the supplied position and invalidates the overlay. There is no display-frame callback or interpolation between ticks.+- `src/native/nota.engine/src/engine/Transport.cpp:14` and `:35` — advances and publishes the engine position per render segment. `Engine.h:356` returns that atomic position through the ABI; this is a discrete render position rather than a continuous presentation clock.++## Root Cause Hypothesis++**High confidence in the mechanism; medium-to-high confidence it explains the reported empty-project stutter.** The moving cursor is driven by a Background-priority, 33 ms dispatcher timer instead of a display animation callback. On the inspected Windows dispatcher this timer delivers about 22 updates per second even with essentially no callback work. Each update assigns the latest block-based transport position directly to the cursor. Between updates the cursor stays stationary. Irregular timer gaps therefore become irregular visual jumps, and block-size quantization can add variation to the distance moved. Neither waveform rendering nor DSP overload is required for this mechanism.++Avalonia 12.1.4's [Windows dispatcher implementation](https://github.com/AvaloniaUI/Avalonia/blob/12.1.4/src/Windows/Avalonia.Win32/Win32DispatcherImpl.cs#L37) schedules dispatcher timers through Win32 `SetTimer`. Its [DispatcherTimer implementation](https://github.com/AvaloniaUI/Avalonia/blob/12.1.4/src/Avalonia.Base/Threading/DispatcherTimer.cs#L16) selects Background priority by default and, in `FireTick` / `Restart`, schedules the next interval after the callback returns. As a result, callback work further lengthens the period, and the timer provides no synchronization to presentation frames. These dependency sources match the package version in `Nota.App.csproj`.++The Native DLL's vendored JUCE source requests a finer Windows timer period (`juce_SystemStats_windows.cpp`, `HiResCounterHandler`). It would be incorrect to claim Nota simply forgot `timeBeginPeriod`, or to assume adding it fixes animation. The engine-loaded probe still exhibited the same uneven dispatcher cadence.++### Other paths investigated++- The older `.specify/bugs/audio-editor-playhead-redraw/` issue addressed full waveform repaints in the audio clip editor. That fix is already present: `WaveformView.SetPlayhead` invalidates only `PlayheadLayer`. It cannot explain the clarified empty-project case.+- Follow mode can repaint arrangement lanes and synchronously refresh detailed waveform peaks; this is a separate content-dependent performance concern, not a prerequisite for this report.+- The piano roll still invalidates its grid and ruler when the cursor moves. That can add UI work when open, but is not needed for empty-project stutter.+- No evidence obtained here establishes an audio-thread stall, a broken WASAPI sample rate, or a Windows-only transport arithmetic error.++## Proposed Remediation++**Preferred**: give the moving playhead a presentation path driven by the visible window's animation frames (for example `TopLevel.RequestAnimationFrame`) and a bounded visual interpolation/extrapolation of authoritative engine transport snapshots. Keep meters, engine polling, remote servicing, automation and recording materialization on their existing service cadence unless independently justified. Merely repainting the same stale engine snapshot more often will still show audio-block steps at larger buffer sizes.++The engine remains the sole source of musical time (AR-9). Use a coherent transport snapshot and monotonic timing to place the visual cursor between authoritative updates; promptly reconcile start, stop, pause, seek, loop wraps, tempo changes, count-in, device restarts and stalled audio callbacks. If accurate block timestamps require additional native snapshot fields, expose them through the pure C ABI and publish them without allocation or locking on the audio thread. Do not generate a separate musical clock for engine or editing operations, or accidentally use a speculative visual position for paste/split/seek semantics.++**Alternative**: reducing the timer interval or raising its priority may make the symptom less severe, but still leaves animation asynchronous to display frames and audio blocks. Raising all existing tick work to frame rate also increases UI and interop load unnecessarily.++**Files likely to change**:++- `src/managed/Nota.App/MainWindow.axaml.cs` — frame callback ownership and lifecycle; separate presentation from service work.+- `src/managed/Nota.App/ArrangementView.cs` — accept a visual position without changing edit-operation semantics.+- A small presentation timing helper and related application port, if required by the chosen design.+- `src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs` — only as needed to separate snapshot delivery from existing polling.+- Native transport / ABI and managed interop only if coherent timing snapshots need extending.+- `CHANGELOG.md` for the eventual user-visible fix.++**Tests to add or update**:++- Deterministic tests of visual-position reconciliation for start/stop, seeks, loop wraps, tempo changes, long callback delays and stale transport snapshots. Use injected timestamps, not wall-clock timing thresholds in CI.+- Windows manual or instrumented validation of visible cursor frame intervals in an empty project at 60 Hz and higher refresh rates, with several WASAPI / ASIO buffer sizes. Compare against engine progression and dropout counts to distinguish visual jitter from audio stalls.+- Check minimization, detail-window visibility, window closing and export suspension so frame callbacks stop or detach correctly and never poll a disposed engine.+- Check editor cursors, Follow scrolling, split/paste position and recording alignment; add ABI smoke coverage if native snapshot data changes.++## Risks & Considerations++- The isolated timer measurement is not a full-application visual reproduction, and other processes, system load, windows being occluded and renderer configuration can affect observed cadence. Do not promise every Windows system runs at exactly 22 updates per second.+- A naive UI-only clock can drift from audible playback or overshoot stop/loop boundaries. Keep corrections authoritative and limit extrapolation when the audio backend stops advancing.+- A frame callback should update inexpensive moving layers; putting all current tick subscribers on it can increase cost and recreate stutter in larger projects.+- This assessment changes no production source. Diagnostic code and measurements are confined to this bug directory. No full build/smoke suite was run because no application behavior was changed.++## Open Questions++- [NEEDS CLARIFICATION: the affected Nota version, Windows version and display refresh rate.]+- [NEEDS CLARIFICATION: active WASAPI or ASIO backend, negotiated buffer size and whether audible playback also stutters or the dropout counter rises.]+- [NEEDS CLARIFICATION: visible frame timing in the complete application under the reporter's configuration; the timer timing has been reproduced independently.]++## Next Step++`/speckit-bug-fix slug=windows-playhead-stutter`diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj b/.specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csprojnew file mode 100644index 00000000..f6b53996--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj@@ -0,0 +1,17 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <UseAppHost>false</UseAppHost>+ <NotaBinaries>$(MSBuildThisFileDirectory)..\..\..\..\..\src\managed\Nota.App\bin\Release\net10.0</NotaBinaries>+ </PropertyGroup>+ <ItemGroup>+ <FrameworkReference Include="Microsoft.AspNetCore.App" />+ <Reference Include="$(NotaBinaries)\*.dll" Exclude="$(NotaBinaries)\nota_engine.dll" />+ <None Include="$(NotaBinaries)\nota_engine.dll;$(NotaBinaries)\runtimes\win-x64\native\*.dll" Link="%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />+ </ItemGroup>+</Project>diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/Program.cs b/.specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/Program.csnew file mode 100644index 00000000..f29e025f--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/Program.cs@@ -0,0 +1,212 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Diagnostics;+using System.Reflection;+using System.Text.Json;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Threading;+using Nota.App;+using Nota.Application;+using Nota.Presentation;++// Runs the actual Nota window and engine using a scratch data directory. "legacy"+// disables only its new frame loop, leaving the original service-tick cursor path.+internal static class Program+{+ [STAThread]+ private static int Main(string[] args)+ {+ try { Run(args); return 0; }+ catch (Exception e) { Console.Error.WriteLine(e); return 1; }+ }++ private static void Run(string[] args)+ {+ string mode = args[0], results = Path.GetFullPath(args[1]);+ Environment.SetEnvironmentVariable("NOTA_DATA_DIR", Path.Combine(Path.GetDirectoryName(results)!, "probe-data", Path.GetFileNameWithoutExtension(results)));+ AppBuilder.Configure<Nota.App.App>().UseWin32().UseSkia().UseHarfBuzz().WithNotaFonts().SetupWithoutStarting();+ var settings = (ISettingsService)App.Services.GetService(typeof(ISettingsService))!;+ settings.Current.ShowWelcomeOnStartup = false;+ settings.Current.CheckForUpdates = false;+ settings.Current.LastSeenVersion = AppInfo.Version;+ var vm = (MainWindowViewModel)App.Services.GetService(typeof(MainWindowViewModel))!;+ int requestedBuffer = args.Length > 2 ? int.Parse(args[2]) : 0;+ string requestedAsioDriver = args.Length > 3 ? args[3] : "";+ if (requestedBuffer > 0) vm.Engine.SetAudioBufferFrames(requestedBuffer);+ if (requestedAsioDriver.Length > 0)+ {+ var driver = vm.Engine.AsioDrivers().FirstOrDefault(d =>+ string.Equals(d.Name, requestedAsioDriver, StringComparison.OrdinalIgnoreCase)+ || string.Equals(d.Uid, requestedAsioDriver, StringComparison.OrdinalIgnoreCase));+ if (string.IsNullOrEmpty(driver.Uid)) throw new InvalidOperationException($"ASIO driver not found: {requestedAsioDriver}");+ vm.Engine.SetAudioSystem(AudioSystem.Asio);+ vm.Engine.SetAsioDriver(driver.Uid);+ }+ if (requestedBuffer > 0 || requestedAsioDriver.Length > 0) vm.ApplyAudioSettings();+ void RequireBackend()+ {+ if (requestedAsioDriver.Length == 0+ || (vm.Engine.ActiveAudioSystem == AudioSystem.Asio && vm.Engine.IsRunning)) return;+ var failure = new+ {+ status = "asio-unavailable", requestedAsioDriver,+ backend = vm.Engine.ActiveAudioSystem.ToString(),+ running = vm.Engine.IsRunning, fallbackReason = vm.Engine.AudioFallbackReason,+ driverId = vm.Engine.AsioDriver+ };+ File.WriteAllText(results, JsonSerializer.Serialize(failure, new JsonSerializerOptions { WriteIndented = true }));+ throw new InvalidOperationException($"Requested ASIO driver did not remain active: {vm.Engine.AudioFallbackReason}");+ }+ RequireBackend();+ var main = new MainWindow { DataContext = vm, WindowState = WindowState.Normal, Width = 1280, Height = 720 };+ const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;+ if (mode == "legacy") typeof(MainWindow).GetField("_playheadFramesClosed", Private)!.SetValue(main, true);+ var timeline = main.FindControl<ArrangementView>("Timeline")!;+ var display = typeof(ArrangementView).GetField("_displayPlayheadBeats", Private)!;+ using var stop = new CancellationTokenSource();+ var clock = Stopwatch.StartNew();+ var changedAt = new List<double>();+ var frameAt = new List<double>();+ double last = double.NaN;+ bool started = false;+ bool completed = false;+ main.Show();+ if (mode == "lifecycle") { RunLifecycle(main, vm, timeline, stop, results, RequireBackend, requestedAsioDriver); return; }+ Action<TimeSpan>? sample = null;+ sample = _ =>+ {+ RequireBackend();+ double now = clock.Elapsed.TotalMilliseconds;+ if (!started && now > 500)+ {+ // Opened applied the default template. Remove its tracks to test an empty project.+ while (vm.Engine.TrackCount > 0)+ {+ vm.Engine.TryGetTrackInfo(0, out var info);+ vm.Engine.RemoveTrack(info.Id);+ }+ timeline.Refresh();+ vm.Engine.SetCountIn(0); vm.Engine.SetMetronome(false); vm.Engine.Seek(0); vm.Engine.Play();+ started = true;+ }+ if (now >= 1500 && now < 6500)+ {+ frameAt.Add(now);+ double beat = (double)display.GetValue(timeline)!;+ if (beat != last) { changedAt.Add(now); last = beat; }+ }+ if (now >= 6500)+ {+ var gaps = changedAt.Zip(changedAt.Skip(1), (a, b) => b - a).Order().ToArray();+ var result = new+ {+ mode, platform = Environment.OSVersion.ToString(), backend = vm.Engine.ActiveAudioSystem.ToString(),+ requestedBuffer, requestedAsioDriver, driverId = vm.Engine.AsioDriver,+ fallbackReason = vm.Engine.AudioFallbackReason,+ sampleRate = vm.Engine.SampleRate, bufferFrames = vm.Engine.NegotiatedBufferFrames,+ observedFramesPerSecond = (frameAt.Count - 1) * 1000 / (frameAt[^1] - frameAt[0]),+ cursorUpdatesPerSecond = 1000 / gaps.Average(),+ medianCursorGapMs = gaps[gaps.Length / 2], p95CursorGapMs = gaps[(int)(gaps.Length * .95)],+ observedFrames = frameAt.Count, cursorUpdates = changedAt.Count,+ dropouts = vm.Engine.XrunCount, cursorChangeTimesMs = changedAt+ };+ File.WriteAllText(results, JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));+ completed = true;+ typeof(MainWindow).GetField("_closeConfirmed", Private)!.SetValue(main, true);+ main.Close();+ stop.Cancel();+ return;+ }+ main.RequestAnimationFrame(sample!);+ };+ main.RequestAnimationFrame(sample);+ // A separate watchdog prevents an occluded window from hanging the diagnostic.+ using var watchdog = new Timer(_ => Dispatcher.UIThread.Post(() => stop.Cancel()), null, 20000, Timeout.Infinite);+ Dispatcher.UIThread.MainLoop(stop.Token);+ if (!completed) throw new InvalidOperationException("No visible frame sample was collected before the watchdog expired.");+ }++ private static void RunLifecycle(MainWindow main, MainWindowViewModel vm, ArrangementView timeline,+ CancellationTokenSource stop, string results, Action requireBackend, string requestedAsioDriver)+ {+ const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;+ bool Active() => typeof(MainWindow).GetField("_playheadFrameOwner", Private)!.GetValue(main) is not null;+ double Display() => (double)typeof(ArrangementView).GetField("_displayPlayheadBeats", Private)!.GetValue(timeline)!;+ var checks = new List<string>();+ void Require(bool condition, string label)+ {+ if (!condition) throw new InvalidOperationException(label);+ checks.Add(label);+ }+ int step = 0;+ var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };+ timer.Tick += (_, _) =>+ {+ requireBackend();+ switch (step++)+ {+ case 0: vm.Engine.SetCountIn(0); vm.Engine.Play(); break;+ case 1:+ Require(Active() && Display() > 0, "play starts frame callbacks");+ vm.SuspendEnginePolling = true;+ break;+ case 2:+ Require(!Active(), "export suspension stops frame callbacks");+ vm.Engine.Stop();+ vm.Engine.RenderOffline(new float[1024], 512);+ vm.Engine.Start();+ vm.SuspendEnginePolling = false;+ vm.Engine.Play();+ break;+ case 3:+ Require(Active(), "device restart and export resume restart frame callbacks");+ main.WindowState = WindowState.Minimized;+ break;+ case 4:+ Require(!Active(), "minimization stops frame callbacks");+ main.WindowState = WindowState.Normal;+ break;+ case 5:+ Require(Active(), "restoring the window restarts frame callbacks");+ vm.Engine.Seek(8);+ break;+ case 6:+ Require(Display() >= 8 && Display() < 10, "seek immediately replaces the display block");+ vm.Engine.SetLoop(true, 8, 8.25);+ break;+ case 7:+ Require(Display() >= 8 && Display() <= 8.25, "repeated short loops keep the display inside the loop");+ vm.Engine.SetLoop(false, 0, 0); vm.Engine.SetBpm(90); vm.Engine.Seek(12);+ break;+ case 8:+ Require(vm.Engine.TryGetTransportSnapshot(out var s) && s.Bpm == 90 && Display() >= 12 && Display() < 14,+ "tempo change and forward seek reconcile together");+ vm.Engine.StopTransport();+ break;+ case 9:+ Require(!Active() && Math.Abs(Display() - 12) < 1e-8, "stop returns to the launch anchor and ends animation");+ vm.Engine.Play();+ break;+ default:+ Require(Active(), "play restarts after stop");+ var device = new { requestedAsioDriver, driverId = vm.Engine.AsioDriver,+ backend = vm.Engine.ActiveAudioSystem.ToString(), sampleRate = vm.Engine.SampleRate,+ bufferFrames = vm.Engine.NegotiatedBufferFrames, fallbackReason = vm.Engine.AudioFallbackReason,+ dropouts = vm.Engine.XrunCount };+ int queuedGeneration = (int)typeof(MainWindow).GetField("_playheadFrameGeneration", Private)!.GetValue(main)!;+ typeof(MainWindow).GetField("_closeConfirmed", Private)!.SetValue(main, true);+ main.Close();+ Require(!Active(), "closing detaches the frame owner before disposing the engine");+ typeof(MainWindow).GetMethod("OnPlayheadFrame", Private)!.Invoke(main, new object[] { queuedGeneration });+ checks.Add("a late frame callback after close does not access the disposed engine");+ File.WriteAllText(results, JsonSerializer.Serialize(new { device, checks }, new JsonSerializerOptions { WriteIndented = true }));+ timer.Stop(); stop.Cancel();+ break;+ }+ };+ timer.Start();+ Dispatcher.UIThread.MainLoop(stop.Token);+ }+}diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/.gitignore b/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/.gitignorenew file mode 100644index 00000000..97047286--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/.gitignore@@ -0,0 +1,4 @@+bin/+obj/+probe-data/+*.logdiff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/MeterProbe.csproj b/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/MeterProbe.csprojnew file mode 100644index 00000000..f6b53996--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/MeterProbe.csproj@@ -0,0 +1,17 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <UseAppHost>false</UseAppHost>+ <NotaBinaries>$(MSBuildThisFileDirectory)..\..\..\..\..\src\managed\Nota.App\bin\Release\net10.0</NotaBinaries>+ </PropertyGroup>+ <ItemGroup>+ <FrameworkReference Include="Microsoft.AspNetCore.App" />+ <Reference Include="$(NotaBinaries)\*.dll" Exclude="$(NotaBinaries)\nota_engine.dll" />+ <None Include="$(NotaBinaries)\nota_engine.dll;$(NotaBinaries)\runtimes\win-x64\native\*.dll" Link="%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />+ </ItemGroup>+</Project>diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/Program.cs b/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/Program.csnew file mode 100644index 00000000..196d53d5--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/Program.cs@@ -0,0 +1,191 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Collections;+using System.Diagnostics;+using System.Reflection;+using System.Text.Json;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.ApplicationLifetimes;+using Avalonia.Rendering.Composition;+using Avalonia.Threading;+using Nota.App;+using Nota.Application;+using Nota.Presentation;++// Measures production meter state and retained draw-list updates without changing app code.+// Neither animation callbacks nor draw-list changes prove physical screen presentation.+internal static class Program+{+ const BindingFlags Hidden = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;+ static object? Field(object o, string name) => o.GetType().GetField(name, Hidden)!.GetValue(o);+ static void Call(object o, string name) => o.GetType().GetMethod(name, Hidden)!.Invoke(o, null);+ static object? DrawList(Control c)+ {+ var v = ElementComposition.GetElementVisual(c);+ return v?.GetType().GetProperty("DrawList", Hidden)?.GetValue(v);+ }+ sealed class MeterSample(string name, Func<MeterBar> getControl)+ {+ public readonly string Name = name;+ public MeterBar Control => getControl();+ public readonly List<double> Changes = new(), Draws = new();+ double _lastL = double.NaN, _lastR = double.NaN;+ object? _lastDraw;+ MeterBar? _lastControl;+ public int RebuiltControls;+ public double Min = double.PositiveInfinity, Max = 0;+ public void Sample(double now)+ {+ var control = Control;+ if (_lastControl is not null && !ReferenceEquals(_lastControl, control))+ {+ RebuiltControls++; _lastL = double.NaN; _lastDraw = null;+ }+ _lastControl = control;+ double l = (double)Field(control, "_levelL")!, r = (double)Field(control, "_levelR")!;+ Min = Math.Min(Min, Math.Min(l, r)); Max = Math.Max(Max, Math.Max(l, r));+ if (!double.IsNaN(_lastL) && (l != _lastL || r != _lastR)) Changes.Add(now);+ _lastL = l; _lastR = r;+ var draw = DrawList(control);+ if (draw is null) throw new InvalidOperationException(Name + " has no composition draw list; bounds=" + control.Bounds);+ if (_lastDraw is not null && !ReferenceEquals(draw, _lastDraw)) Draws.Add(now);+ _lastDraw = draw;+ }+ public object Result() => new { name = Name, effectivelyVisible = Control.IsEffectivelyVisible,+ rebuiltControls = RebuiltControls, stateChanges = Stats(Changes), drawListChanges = Stats(Draws), minNormalizedLevel = Min, maxNormalizedLevel = Max };+ }+ static object Stats(List<double> times)+ {+ var gaps = times.Zip(times.Skip(1), (a,b) => b-a).Order().ToArray();+ return new { count = times.Count, updatesPerSecond = gaps.Length == 0 ? (double?)null : 1000/gaps.Average(),+ medianGapMs = gaps.Length == 0 ? (double?)null : gaps[gaps.Length/2],+ p95GapMs = gaps.Length == 0 ? (double?)null : gaps[(int)(gaps.Length*.95)],+ maxGapMs = gaps.Length == 0 ? (double?)null : gaps[^1] };+ }+ [STAThread]+ static int Main(string[] args)+ {+ try { Run(args); return 0; }+ catch (Exception e) { Console.Error.WriteLine(e); return 1; }+ }+ static void Run(string[] args)+ {+ string output = Path.GetFullPath(args[0]), asio = args.Length > 1 ? args[1] : "";+ string scratch = Path.Combine(Path.GetDirectoryName(output)!, "probe-data", Path.GetFileNameWithoutExtension(output));+ Directory.CreateDirectory(scratch);+ Environment.SetEnvironmentVariable("NOTA_DATA_DIR", scratch);+ var lifetime = new ClassicDesktopStyleApplicationLifetime { ShutdownMode = ShutdownMode.OnExplicitShutdown };+ AppBuilder.Configure<Nota.App.App>().UseWin32().UseSkia().UseHarfBuzz().WithNotaFonts().SetupWithLifetime(lifetime);+ var settings = (ISettingsService)App.Services.GetService(typeof(ISettingsService))!;+ settings.Current.ShowWelcomeOnStartup = false; settings.Current.CheckForUpdates = false;+ settings.Current.LastSeenVersion = AppInfo.Version;+ var vm = (MainWindowViewModel)App.Services.GetService(typeof(MainWindowViewModel))!;+ if (asio.Length > 0)+ {+ var driver = vm.Engine.AsioDrivers().Single(d => d.Name == asio);+ vm.Engine.SetAudioSystem(AudioSystem.Asio); vm.Engine.SetAsioDriver(driver.Uid); vm.ApplyAudioSettings();+ }+ if (!vm.Engine.IsRunning || (asio.Length > 0 && vm.Engine.ActiveAudioSystem != AudioSystem.Asio))+ throw new InvalidOperationException("Requested backend unavailable: " + vm.Engine.AudioFallbackReason);+ using var stop = new CancellationTokenSource();+ Exception? error = null; bool completed = false;+ DispatcherTimer.RunOnce(() =>+ {+ try+ {+ var main = (MainWindow)lifetime.MainWindow!;+ main.Width = 1400; main.Height = 960; main.WindowState = WindowState.Normal;+ while (vm.Engine.TrackCount > 0) { vm.Engine.TryGetTrackInfo(0, out var info); vm.Engine.RemoveTrack(info.Id); }+ string wave = Path.Combine(scratch, "meter-test.wav"); WriteSignal(wave);+ int track = vm.Engine.AddAudioTrack();+ if (vm.Engine.AddAudioClip(track, wave, 0) < 0) throw new InvalidOperationException("Could not import generated signal");+ vm.Engine.SetTrackName(track, "Meter cadence test");+ var timeline = main.FindControl<ArrangementView>("Timeline")!;+ timeline.Refresh(); timeline.SelectTrackFromOutside(track);+ Call(main, "ShowMixer");+ var mixer = (MixerView)Field(main, "_mixer")!; mixer.Refresh();+ var meters = new List<MeterSample> {+ new("transport master", () => (MeterBar)Field(main, "_masterMeter")!),+ new("arrangement track", () => ((Dictionary<int, MeterBar>)Field(timeline, "_meters")!)[track]),+ new("arrangement master", () => (MeterBar)Field(timeline, "_masterRowMeter")!)+ };+ foreach (var value in (IEnumerable)Field(mixer, "_meters")!)+ {+ int id = (int)value.GetType().GetField("Item1")!.GetValue(value)!;+ meters.Add(new(id < 0 ? "mixer master" : "mixer track",+ () => ((List<(int, MeterBar)>)Field(mixer, "_meters")!).Single(m => m.Item1 == id).Item2));+ }+ if (meters.Count != 5) throw new InvalidOperationException("Expected five meter instances");+ main.IsEnabled = false; // isolate automatic updates from real hover/zoom/edit input+ vm.Engine.SetCountIn(0); vm.Engine.SetMetronome(false); vm.Engine.Seek(0); vm.Engine.Play();+ var clock = Stopwatch.StartNew();+ var frames = new List<double>(); var ticks = new List<double>();+ var xrunStart = vm.Engine.XrunCount;+ void Tick(double _) { double t = clock.Elapsed.TotalMilliseconds; if (t >= 1000 && t < 11000) ticks.Add(t); }+ vm.PlayheadUpdated += Tick;+ Action<TimeSpan>? sample = null;+ sample = _ =>+ {+ try+ {+ double now = clock.Elapsed.TotalMilliseconds;+ if (now >= 1000 && now < 11000)+ {+ frames.Add(now);+ foreach (var meter in meters)+ {+ if (!meter.Control.IsEffectivelyVisible) throw new InvalidOperationException("Hidden meter: " + meter.Name);+ meter.Sample(now);+ }+ }+ if (now >= 11000)+ {+ if (meters.Any(m => m.Changes.Count < 10 || m.Max <= m.Min))+ throw new InvalidOperationException("Test signal failed to produce varying meter readings");+ if (asio.Length > 0 && vm.Engine.ActiveAudioSystem != AudioSystem.Asio)+ throw new InvalidOperationException("ASIO fell back during measurement");+ var result = new { platform = Environment.OSVersion.ToString(),+ backend = vm.Engine.ActiveAudioSystem.ToString(), requestedAsioDriver = asio,+ sampleRate = vm.Engine.SampleRate, bufferFrames = vm.Engine.NegotiatedBufferFrames,+ measuredSeconds = 10, animationCallbacks = Stats(frames), serviceTicks = Stats(ticks),+ meters = meters.Select(m => m.Result()).ToArray(), dropouts = vm.Engine.XrunCount - xrunStart };+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);+ File.WriteAllText(output, JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));+ vm.PlayheadUpdated -= Tick;+ typeof(MainWindow).GetField("_closeConfirmed", Hidden)!.SetValue(main, true);+ main.Close(); completed = true; stop.Cancel(); return;+ }+ main.RequestAnimationFrame(sample!);+ }+ catch (Exception e) { error = e; stop.Cancel(); }+ };+ main.RequestAnimationFrame(sample);+ }+ catch (Exception e) { error = e; stop.Cancel(); }+ }, TimeSpan.FromMilliseconds(800));+ using var watchdog = new Timer(_ => Dispatcher.UIThread.Post(() => stop.Cancel()), null, 25000, Timeout.Infinite);+ Dispatcher.UIThread.MainLoop(stop.Token);+ if (error is not null) throw error;+ if (!completed) throw new InvalidOperationException("Timed out before measurement completed");+ Console.WriteLine(File.ReadAllText(output));+ }+ static void WriteSignal(string path)+ {+ const int rate = 48000, samples = rate * 20;+ using var w = new BinaryWriter(File.Create(path));+ void Tag(string s) => w.Write(System.Text.Encoding.ASCII.GetBytes(s));+ Tag("RIFF"); w.Write(36 + samples * 4); Tag("WAVE"); Tag("fmt ");+ w.Write(16); w.Write((short)1); w.Write((short)2); w.Write(rate); w.Write(rate * 4);+ w.Write((short)4); w.Write((short)16); Tag("data"); w.Write(samples * 4);+ for (int i = 0; i < samples; i++)+ {+ double t = (double)i / rate;+ double ampL = .003 + .012 * (.5 + .5 * Math.Sin(2 * Math.PI * 1.71 * t));+ double ampR = .003 + .012 * (.5 + .5 * Math.Sin(2 * Math.PI * 2.37 * t + .4));+ w.Write((short)(32767 * ampL * Math.Sin(2 * Math.PI * 440 * t)));+ w.Write((short)(32767 * ampR * Math.Sin(2 * Math.PI * 660 * t)));+ }+ }+}diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/Program.cs b/.specify/bugs/windows-playhead-stutter/diagnostics/Program.csnew file mode 100644index 00000000..68daf5f5--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/Program.cs@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Diagnostics;+using System.Text.Json;+using System.Runtime.InteropServices;+using Avalonia;+using Avalonia.Threading;+using Nota.App;++internal static class Program+{+ [STAThread]+ private static void Main(string[] args)+ {+ // Loading the native DLL also runs JUCE's Windows timer-period initializer.+ if (args.Length > 0) NativeLibrary.Load(Path.GetFullPath(args[0]));+ // Initialize the Windows dispatcher without creating an application window.+ AppBuilder.Configure<Avalonia.Application>().UseWin32().UseSkia().UseHarfBuzz().SetupWithoutStarting();+ using var stop = new CancellationTokenSource();+ var clock = Stopwatch.StartNew();+ var ticks = new List<double>();+ using var timer = new AvaloniaPeriodicTimerFactory().Create(TimeSpan.FromMilliseconds(33), () =>+ {+ ticks.Add(clock.Elapsed.TotalMilliseconds);+ if (ticks.Count == 121) stop.Cancel();+ });+ timer.Start();+ Dispatcher.UIThread.MainLoop(stop.Token);+ var intervals = ticks.Zip(ticks.Skip(1), (a, b) => b - a).ToArray();+ var sorted = intervals.Order().ToArray();+ Console.WriteLine(JsonSerializer.Serialize(new+ {+ platform = Environment.OSVersion.ToString(),+ engineLoaded = args.Length > 0,+ requestedMs = 33,+ samples = intervals.Length,+ meanMs = intervals.Average(),+ minMs = sorted[0],+ p50Ms = sorted[sorted.Length / 2],+ p95Ms = sorted[(int)(sorted.Length * .95)],+ maxMs = sorted[^1],+ updatesPerSecond = 1000 / intervals.Average(),+ intervalsMs = intervals+ }, new JsonSerializerOptions { WriteIndented = true }));+ }+}diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/README.md b/.specify/bugs/windows-playhead-stutter/diagnostics/README.mdnew file mode 100644index 00000000..cb4f483a--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/README.md@@ -0,0 +1,74 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Windows playhead diagnostics++Run from the repository root after a Windows Release build. Both diagnostic projects+reference the existing application binaries; they add no application dependencies.++The original windowless timer measurement:++```powershell+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/TimerProbe.csproj -- src/managed/Nota.App/bin/Release/net10.0/nota_engine.dll+```++The real-window comparison (each run opens and closes a Nota window):++```powershell+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj -- legacy .specify/bugs/windows-playhead-stutter/diagnostics/app-legacy-results.json+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj -- frames .specify/bugs/windows-playhead-stutter/diagnostics/app-frames-final-results.json+```++`legacy` disables only the new frame loop through reflection. The real window's existing+service tick then sets the cursor directly, reproducing its old scheduling behavior.+`frames` uses the actual frame callback implementation. The probe starts the real engine,+removes the default template's tracks, plays an empty project, and samples changes in the+Arrangement's display position on frame callbacks for five seconds. The counters measure+UI property changes observed on those callbacks, not compositor presentation or physical+screen refresh. This is an integration harness, not a packaged application launch.++Append a buffer-size request, e.g. `64` or `2048`, after the result path. Inspect the+reported **negotiated** buffer size: this Windows shared-mode device negotiates a 480-frame+hardware period when 64 client frames are requested.++To test an installed ASIO driver, pass `0` for the buffer request and its exact name+as a fourth argument. ASIO uses the driver's existing buffer setting:++```powershell+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj -- frames .specify/bugs/windows-playhead-stutter/diagnostics/app-asio-yamaha-frames-results.json 0 "Yamaha Steinberg USB ASIO"+```++The probe requires the actual running backend to stay ASIO throughout the check.+If driver startup fails or the device falls back to WASAPI, it records the failure+and exits unsuccessfully; the result cannot be mistaken for ASIO verification.+Driver identity, negotiated rate/buffer and fallback reason are included in the JSON.+The same fourth argument works with `legacy` and `lifecycle` modes.++`lifecycle` instead checks play/stop, export suspension, backend restart, minimize/restore,+seek, short loops, tempo changes and closing with a pending frame callback:++```powershell+dotnet run --project .specify/bugs/windows-playhead-stutter/diagnostics/AppFrameProbe/AppFrameProbe.csproj -- lifecycle .specify/bugs/windows-playhead-stutter/diagnostics/app-lifecycle-final-results.json+```++Settings, logs and generated presets go under `probe-data/` beside the requested results;+this ignored directory isolates the probe from the user's Nota configuration. Welcome+dialogs and update checks are disabled. The harness changes no production source.++Deterministic display math and native snapshot ABI checks are part of the smoke suite,+and can also run independently:++```powershell+dotnet run --project tests/Nota.SmokeTest -c Release -- --transport-display+```++Timing results depend on the display, audio backend, foreground/occluded window state,+and system load. Keep wall-clock cadence measurements out of CI pass/fail assertions.++## Recorded results++The JSON measurements named by the assessment/fix/verification reports are preserved+on [pr-assets](https://github.com/thoi1/nota/tree/pr-assets/issue-423/historical-results/windows-playhead-stutter/diagnostics),+including the WASAPI, Yamaha ASIO, lifecycle and meter-cadence samples. Generated+measurements are ignored locally so benchmark output stays out of the code branch.+The commands above regenerate the same local output paths.diff --git a/.specify/bugs/windows-playhead-stutter/diagnostics/TimerProbe.csproj b/.specify/bugs/windows-playhead-stutter/diagnostics/TimerProbe.csprojnew file mode 100644index 00000000..f861418b--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/diagnostics/TimerProbe.csproj@@ -0,0 +1,28 @@++<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <UseAppHost>false</UseAppHost>+ <NotaBinaries>$(MSBuildThisFileDirectory)..\..\..\..\src\managed\Nota.App\bin\Release\net10.0</NotaBinaries>+ <EnableDefaultCompileItems>false</EnableDefaultCompileItems>+ </PropertyGroup>++ <ItemGroup>+ <Reference Include="$(NotaBinaries)\Avalonia*.dll" />+ <Reference Include="$(NotaBinaries)\SkiaSharp.dll" />+ <Reference Include="$(NotaBinaries)\HarfBuzzSharp.dll" />+ <None Include="$(NotaBinaries)\runtimes\win-x64\native\*.dll"+ Link="%(Filename)%(Extension)"+ CopyToOutputDirectory="PreserveNewest" />+ <Compile Include="..\..\..\..\src\managed\Nota.App\AvaloniaPeriodicTimer.cs"+ Link="AvaloniaPeriodicTimer.cs" />+ <Compile Include="..\..\..\..\src\managed\Nota.Application\Ports\IPeriodicTimer.cs"+ Link="IPeriodicTimer.cs" />+ <Compile Include="Program.cs" />+ </ItemGroup>+</Project>diff --git a/.specify/bugs/windows-playhead-stutter/fix.md b/.specify/bugs/windows-playhead-stutter/fix.mdnew file mode 100644index 00000000..07dc4dd0--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/fix.md@@ -0,0 +1,112 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Bug Fix: Windows playhead stutters even in an empty project++- **Slug**: windows-playhead-stutter (explicit user request)+- **Fixed**: 2026-11-01+- **Assessment**: ./assessment.md+- **Status**: applied++## Summary++The Arrangement cursor now updates on the visible window's animation frames, interpolating+an authoritative, timestamped engine transport snapshot. Engine polling, meters, recording+materialization and other service work retain their existing timer cadence. The audio clip+editor's existing playhead overlay also uses the frame position; the piano roll retains its+existing service cadence because moving it to every frame would repaint its full grid.++Display interpolation is bounded by audio already rendered. It stops at the rendered+endpoint if callbacks stall, handles loop wraps, and resets its history on seek, start/stop,+tempo, loop configuration and device sample-rate setup. Small client callbacks batched by+WASAPI are represented by a rendered window up to the negotiated hardware period, avoiding+new pauses between those callbacks. Fractional-sample loop boundaries are re-anchored to+the real transport each block so rounding errors cannot accumulate.++## Changes++| File | Change | Notes |+|------|--------|-------|+| `src/native/nota.engine/include/nota/nota_engine.h` | additive API | `NotaTransportSnapshot` and `nota_transport_snapshot`, a 64-byte POD contract |+| `src/native/nota.engine/src/engine/Transport.{h,cpp}` | snapshot publication | Lock-free atomic payload and bounded coherent reads; native monotonic timestamp; rendered-window history |+| `src/native/nota.engine/src/engine/Engine_Render.cpp` | block publication | Records the playing portion, including a leading count-in, and publishes once per completed block |+| `src/native/nota.engine/src/engine/Engine.h`, `src/native/nota.engine/src/abi/nota_engine_core.cpp` | ABI bridge | Exposes the snapshot without allocation or waiting |+| `src/managed/Nota.Application/Engine/NotaTransportSnapshot.cs`, `IAudioEngine.cs` | contract | Blittable snapshot and engine-port query |+| `src/managed/Nota.Infrastructure/Interop/{NativeMethods,NotaEngine}.cs` | interop | One native call fetches a coherent snapshot |+| `src/managed/Nota.Presentation/ViewModels/TransportDisplayPosition.cs` | display math | Stateless interpolation, endpoint hold and loop mapping |+| `src/managed/Nota.App/MainWindow.Playhead.cs`, `MainWindow.axaml.cs` | frame lifecycle | Separate frame loop, export/minimize/close guards, visible detail-window fallback; existing service subscriptions stay on their timer |+| `src/managed/Nota.App/ArrangementView*.cs` | display separation | Ruler, overlays, overview and Follow use the display position; split/paste/section commands continue to use the authoritative position |+| `tests/Nota.SmokeTest/TransportDisplayTests.cs`, `Program.cs` | regression tests | Deterministic display math, native ABI, concurrent publication and fractional-loop drift; focused `--transport-display` option |+| `CHANGELOG.md` | release note | Records the Windows playback-cursor fix |+| `diagnostics/` in this bug directory | integration evidence | Windowless timer probe, actual Nota-window comparison and lifecycle checks with scratch settings |++The audio publisher performs no allocation, locking, I/O or reader wait. Its payload+atomics are compile-time checked for lock freedom. The reader makes at most three+attempts and skips an overlapping publication instead of waiting on the audio writer.+The pure C ABI and Transport's ownership of musical time are preserved (AR-6/7/9).++## Tests Added or Updated++`TransportDisplayTests.Run()` covers interpolation between callbacks; stopped, stalled,+late and zero-duration snapshots; seek/tempo changes; leading count-in; loop seams,+pre-loop playback and invalid ranges; the ABI layout and endpoint values; a block ending+its count-in; 2,000 blocks across fractional-sample loop boundaries; and concurrent readers+over 4,000 offline blocks. It runs in the standard smoke suite.++The diagnostic uses the real `App`, `MainWindow`, engine and Arrangement control. Its+`legacy` mode disables only the new frame loop, exercising the original service-tick+cursor path. `lifecycle` checks actual window minimize/restore, export suspension, device+restart, seek, loops, tempo, stop and closing with a queued callback.++## Local Verification++- **Windows build**: `pwsh scripts/build-win.ps1` under the installed Visual Studio x64+ developer environment — exit 0, `SMOKE TEST PASSED`, `SCAN SCALE PASSED`; scanner+ self-tests, design/architecture checks and render-pool performance guards passed.+ Log: `diagnostics/build-win-final.log` (ignored local build output).+- **Focused tests**: `dotnet tests/Nota.SmokeTest/bin/Release/net10.0/Nota.SmokeTest.dll --transport-display`+ passed before the final full run; the final full run also includes the added+ fractional-loop drift guard.+- **Real-window measurements**, Windows build 26300, WASAPI, 48 kHz:++ | Path | Negotiated hardware frames | Cursor updates/s | Median gap | 95th percentile | Dropouts |+ |------|---------------------------:|-----------------:|-----------:|----------------:|---------:|+ | Original service-tick path | 480 | 21.47 | 47.75 ms | 48.79 ms | 0 |+ | Final frame path, device default | 480 | 238.80 | 4.16 ms | 4.42 ms | 0 |+ | Final frame path, 64 client frames requested | 480 | 237.79 | 4.16 ms | 4.36 ms | 0 |+ | Final frame path, 2048 requested | 2048 | 213.38 | 4.16 ms | 4.60 ms | 0 |++ These count cursor property changes observed on animation callbacks over five seconds,+ not physical compositor presentations. Final default and small-buffer runs changed the+ cursor on every observed frame callback. Raw results and reproduction commands are+ under `diagnostics/`; timing assertions are deliberately excluded from CI.+- **Lifecycle integration**: all twelve checks passed, including invoking a late callback+ after the window closed and disposed the engine. See `diagnostics/app-lifecycle-final-results.json`.+- `git diff --check` — clean.++## Deviations from Assessment++- The additive native snapshot was needed to interpolate from a coherent audio-owned+ timestamp rather than inventing an independent UI musical clock. This was explicitly+ allowed by the assessment; its implementation adds native/managed ABI files to scope.+- Real-device testing exposed batching when 64 client frames were requested: the actual+ Windows device period was 480 frames. The snapshot therefore spans a bounded rendered+ history up to that period, rather than just the most recent small callback.+- The existing audio-editor overlay follows frames as well. The piano roll's full-grid+ rendering remains on its prior cadence to avoid multiplying its rendering cost.+- The assessment's missing full-application evidence was addressed with the actual-window+ integration harness. Its original text was left untouched.++An initial smoke run failed two new count-in assertions because the test requested Play+before applying the queued Stop. The test now drains Stop/Seek before requesting count-in,+matching the existing count-in tests. The final full Windows run passed.++## Follow-ups++- ASIO, macOS and Linux were not exercised for this change. Validate those configurations+ during review; no claim of cross-platform visual verification is made.+- A dedicated 60 Hz display, popped-out audio clip editor and content-heavy Follow scrolling+ were not instrumented here. Existing piano-roll and content-rendering performance issues+ are outside the empty-project cursor fix.+- Next workflow step: `/speckit-bug-test slug=windows-playhead-stutter` (verification results+ can be recorded from the checks above).diff --git a/.specify/bugs/windows-playhead-stutter/meter-test.md b/.specify/bugs/windows-playhead-stutter/meter-test.mdnew file mode 100644index 00000000..c491b60e--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/meter-test.md@@ -0,0 +1,87 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Audio level-meter update cadence++- **Tested**: 2026-11-01, Windows x64, current Release binaries+- **Scope**: measurement only; no production code or settings changes+- **Result**: all five observed level meters update at approximately 30 Hz++## Results++Actual App, normal main window and docked mixer, one audio track with a generated+quiet stereo amplitude-modulated signal; 1 second warmup, 10 second sample per backend.+Scratch settings/audio data are confined to diagnostics/MeterProbe/probe-data/.++| Measurement | WASAPI, 48 kHz / 480 frames | Yamaha Steinberg USB ASIO, 48 kHz / 64 frames |+|-------------|---------------------------:|------------------------------------------:|+| Animation callbacks per second | 238.00 | 237.49 |+| Existing service ticks per second | 29.93 | 29.75 |+| Transport master meter level changes/s | 29.92 | 29.75 |+| Arrangement track meter level changes/s | 29.92 | 29.75 |+| Arrangement master meter level changes/s | 29.92 | 29.75 |+| Mixer track meter level changes/s | 29.92 | 29.75 |+| Mixer master meter level changes/s | 29.92 | 29.75 |+| Meter drawing updates/s (all five) | 29.92 | 29.75 |+| Median level-change interval | 33.34 ms | 33.34 ms |+| 95th-percentile level-change interval | 33.77 ms | 37.52 ms |+| Reported audio dropouts during sample | 0 | 0 |++The backend comparison is two short sequential samples, not evidence that one backend+has worse scheduling. Every meter remained visible and no meter controls were rebuilt+during either measured interval. Input was disabled in the temporary probe window to+isolate automatic drawing from real hover, scrolling and editing.++## Why meters differ from the fixed playheads++MainWindowViewModel creates a 33 ms service clock in its constructor. OnTick raises+PlayheadUpdated, whose MainWindow.axaml.cs handler feeds the transport master meter,+ArrangementView.UpdateMeters and MixerView.UpdateMeters. The previous playhead fixes+moved cursor presentation to RequestAnimationFrame while deliberately retaining meter+polling on this service cadence. MeterBar.Push takes readings immediately and only+invalidates when the level or held peak changes; there is no separate meter animation.++Thus the current primary level meters have approximately 30 fresh readings/drawing+updates per second, even when display-frame callbacks arrive around 238 times/second.+Repeatedly repainting an unchanged meter would not provide additional audio readings.+No implementation change was requested or made by this test.++## Method and checks++- Probe builds against the existing Release assemblies, using no additional dependencies.+- Starts the real App, imports a generated 20-second stereo PCM WAV into one audio track,+ and opens the app's existing docked MixerView through its normal routing.+- Samples MeterBar's left/right level fields on actual window animation callbacks;+ counts changes, rather than mistaking steady-level suppression for missed updates.+- Separately counts composition draw-list replacements to observe drawing updates.+- Records the existing service event cadence without calling UpdateMeters itself.+- Follows current control instances, since startup can rebuild arrangement headers.+ An initial diagnostic failed because it retained a detached startup meter; the probe+ was corrected before either final measurement. No app code changed in response.+- Requires visible controls, existing composition draw lists and varying nonzero levels;+ verifies ASIO remains the active backend, without silently accepting WASAPI fallback.+- Diagnostic build: passed, zero warnings/errors. Both final runs: exit 0.+- git diff --check: passed. Full smoke suite was not repeated for this measurement-only+ task; the prior piano-roll build/smoke/scanner validation remains unchanged.++## Reproduce++From the repository root after a Windows Release build:++```powershell+dotnet build .specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/MeterProbe.csproj+dotnet .specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/bin/Debug/net10.0/MeterProbe.dll .specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/wasapi-results.json+dotnet .specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/bin/Debug/net10.0/MeterProbe.dll .specify/bugs/windows-playhead-stutter/diagnostics/MeterProbe/yamaha-results.json "Yamaha Steinberg USB ASIO"+```++Raw results: [WASAPI](diagnostics/MeterProbe/wasapi-results.json),+[Yamaha ASIO](diagnostics/MeterProbe/yamaha-results.json).+Diagnostic source: [Program.cs](diagnostics/MeterProbe/Program.cs).++## Limits++Animation callbacks and composition draw-list changes are UI-side measurements, not+physical display/compositor presentation. This test covers the transport, arrangement+and docked mixer MeterBar controls on this machine; it does not measure device-card+meters, Session meters, floating-mixer/minimization behavior or heavy sessions. The+generated signal keeps levels varying specifically to measure the UI update ceiling.diff --git a/.specify/bugs/windows-playhead-stutter/test.md b/.specify/bugs/windows-playhead-stutter/test.mdnew file mode 100644index 00000000..47befbf1--- /dev/null+++ b/.specify/bugs/windows-playhead-stutter/test.md@@ -0,0 +1,84 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Bug Verification: Windows playhead stutters even in an empty project++- **Slug**: windows-playhead-stutter (from the current bug-fix context)+- **Tested**: 2026-11-01+- **Assessment**: ./assessment.md+- **Fix**: ./fix.md+- **Result**: verified on the tested Windows/WASAPI configuration++## Summary++The actual Nota-window integration harness reproduces the empty-project cursor's original+roughly 21 Hz service-timer stepping. With the final fix, the default-device run changes the+cursor on every observed animation callback, about 239 times per second on this machine,+with no reported audio dropouts. The complete Windows build and smoke suite pass.++## Checks Performed++| Check | Command / Action | Result | Notes |+|-------|------------------|--------|-------|+| Original symptom, automated equivalent | `AppFrameProbe legacy .../app-legacy-results.json` | pass | Real App, MainWindow, engine and Arrangement; only the new frame loop is disabled to exercise the original timer path |+| Final fix, default WASAPI device | `AppFrameProbe frames .../app-frames-final-results.json` | pass | Fresh scratch settings; empty project; 48 kHz, 480 hardware frames; 1,194 observed frame callbacks and 1,194 cursor changes in the sample |+| Small WASAPI client buffer | `AppFrameProbe frames .../app-frames-64-final-results.json 64` | pass | 64 requested, 480 hardware frames negotiated; 1,189 callbacks and 1,189 cursor changes |+| Larger WASAPI buffer | `AppFrameProbe frames .../app-frames-2048-final-results.json 2048` | pass | 2048 hardware frames; median cursor gap remains 4.16 ms; occasional endpoint holds are bounded rather than extrapolating beyond rendered audio |+| Window and transport lifecycle | `AppFrameProbe lifecycle .../app-lifecycle-final-results.json` | pass | All 12 checks, including export suspension, device restart, minimize/restore, seek, loops, tempo, stop and a callback after engine disposal |+| Deterministic display and native ABI regressions | `dotnet tests/Nota.SmokeTest/bin/Release/net10.0/Nota.SmokeTest.dll --transport-display` | pass | All 21 transport-display/snapshot assertions; also includes design/architecture checks before the focused branch |+| Full Windows build and regression suite | `pwsh scripts/build-win.ps1` in the Visual Studio x64 developer environment | pass | Exit 0; native and managed build, scanner self-tests, smoke tests, render-pool guards and large-folder scanner check |+| Whitespace | `git diff --check` | pass | No errors |+| ASIO and other OSes | Not run | not-run | No visual-verification claim for those configurations |++Builds used the installed Visual Studio toolchain and .NET 10; Avalonia is the project's+existing 12.1.4 dependency. The GUI harness uses ignored scratch configuration and disables+welcome dialogs and update checks. It does not modify production sources. Its commands+and measurement definitions are in `diagnostics/README.md`.++## Measured Cursor Cadence++| Path | Cursor changes/s | Median gap | 95th percentile | Reported dropouts |+|------|-----------------:|-----------:|----------------:|------------------:|+| Original timer path | 21.47 | 47.75 ms | 48.79 ms | 0 |+| Final default-device path | 238.80 | 4.16 ms | 4.42 ms | 0 |+| Final 64-client-frame request | 237.79 | 4.16 ms | 4.36 ms | 0 |+| Final 2048-frame request | 213.38 | 4.16 ms | 4.60 ms | 0 |++These are changes to the actual Arrangement display-position property sampled on animation+callbacks over five seconds. They are not direct physical screen-refresh or compositor+presentation measurements. The original and final default-device paths both negotiated+480 frames at 48 kHz. Raw timestamps are retained in the four JSON files above.++## Output Excerpts++```text+[PASS] transport display: stalled audio or a delayed UI frame holds the exact rendered endpoint+[PASS] transport snapshot: fractional-sample loop lengths do not accumulate display drift+[PASS] transport snapshot: concurrent reads never mix two published blocks+SMOKE TEST PASSED+SCAN SCALE PASSED+```++Local build/check logs are `diagnostics/build-win-final.log` and+`diagnostics/transport-tests-final.log`; generated logs and scratch application data are+ignored so they do not inflate the change. Initial test setup failures and the WASAPI+batching refinement are documented in `fix.md`.++## Residual Risks++- Verification covers Windows build 26300 and this machine's WASAPI device. A dedicated+ 60 Hz display, ASIO, macOS and Linux were not tested.+- The integration harness creates the real window after App setup, rather than launching+ the packaged splash/startup sequence. It exercises the production frame lifecycle and+ native backend but does not measure the physical display or DAC clock.+- The audio clip editor shares the frame position, but its popped-out configuration was+ not instrumented. The piano-roll cursor intentionally retains its prior cadence to+ avoid moving full-grid repaints to display rate.+- Content-heavy Follow scrolling still repaints waveform content. That performance path+ is separate from the reported empty-project stutter and was not benchmarked here.++## Recommendation++The empty-project Arrangement cursor fix is verified on Windows/WASAPI and ready for+review. Keep the platform and editor coverage limits above in the review notes; no+additional implementation is required for the tested empty-project symptom.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c2d05b51..69a99cec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -148,6 +148,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.returns, then the master.### Fixed+- **Piano-roll playback cursor**: arrangement MIDI clips now follow the same smooth+ display-frame position as the arrangement. Cursor movement redraws lightweight+ overlays instead of repainting all notes and ruler labels.+- **Windows playback cursor**: the Arrangement playhead now follows display frames,+ interpolating the engine's rendered blocks instead of jumping on the UI polling timer.+ Editing positions and audio timing remain tied to the engine transport.- **An armed audio track meters its input with monitoring off** (nota-daw/nota#352): arm atrack and its meter shows the level coming in (hardware input, or the source track itrecords from) before and during a take, without hearing it. The meter reads the inputdiff --git a/src/managed/Nota.App/ArrangementView.Controls.cs b/src/managed/Nota.App/ArrangementView.Controls.csindex 9ba920f3..e89fc2d1 100644--- a/src/managed/Nota.App/ArrangementView.Controls.cs+++ b/src/managed/Nota.App/ArrangementView.Controls.cs@@ -236,7 +236,7 @@ public sealed partial class ArrangementViewprivate void RenderPlayheadAndReadout(DrawingContext ctx, double w, double h){// Playhead flag: a 7×5 brass triangle at the top of the ruler.- double px = _o.BeatToX(_o._playheadBeats);+ double px = _o.BeatToX(_o._displayPlayheadBeats);if (px >= -5 && px <= w + 5){var tri = new StreamGeometry();@@ -502,7 +502,7 @@ public sealed partial class ArrangementView}// Playhead across the footer lanes: a 1px brass line.- double px = _o.BeatToX(_o._playheadBeats);+ double px = _o.BeatToX(_o._displayPlayheadBeats);if (px >= 0 && px <= w){ctx.DrawLine(PlayheadPen, new Point(px, 0), new Point(px, h));diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex 726405bc..77371ced 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -1837,7 +1837,7 @@ public sealed partial class ArrangementView}// Playhead across all lanes: brass line with a soft glow.- double px = _o.BeatToX(_o._playheadBeats);+ double px = _o.BeatToX(_o._displayPlayheadBeats);if (px >= 0 && px <= w){ctx.DrawLine(PlayheadPen, new Point(px, 0), new Point(px, h));diff --git a/src/managed/Nota.App/ArrangementView.Overview.cs b/src/managed/Nota.App/ArrangementView.Overview.csindex 13a43383..35f54e2f 100644--- a/src/managed/Nota.App/ArrangementView.Overview.cs+++ b/src/managed/Nota.App/ArrangementView.Overview.cs@@ -127,7 +127,7 @@ public sealed partial class ArrangementViewif (!_overviewRow.IsVisible) return;double w = _overview.Bounds.Width;if (w <= 0) return;- int px = (int)(_playheadBeats / OverviewSpan * w);+ int px = (int)(_displayPlayheadBeats / OverviewSpan * w);if (px == _ovPlayheadPx) return;_ovPlayheadPx = px;_overview.InvalidateVisual();@@ -354,7 +354,7 @@ public sealed partial class ArrangementView}// Playhead over the whole project.- double px = BeatToX(_o._playheadBeats);+ double px = BeatToX(_o._displayPlayheadBeats);if (px >= 0 && px <= w) ctx.DrawLine(PlayheadPen, new Point(px, 0), new Point(px, h));}diff --git a/src/managed/Nota.App/ArrangementView.Sections.cs b/src/managed/Nota.App/ArrangementView.Sections.csindex effca678..a5ce0b5d 100644--- a/src/managed/Nota.App/ArrangementView.Sections.cs+++ b/src/managed/Nota.App/ArrangementView.Sections.cs@@ -462,7 +462,7 @@ public sealed partial class ArrangementView}// Playhead tick, so the lane and the ruler read as one instrument.- double px = _o.BeatToX(_o._playheadBeats);+ double px = _o.BeatToX(_o._displayPlayheadBeats);if (px >= 0 && px <= w) ctx.DrawLine(PlayheadPen, new Point(px, 0), new Point(px, h));}}diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex 75d71fcd..740e1588 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -39,6 +39,7 @@ public sealed partial class ArrangementView : UserControlprivate double _pixelsPerBeat = 28;private double _scrollBeats;private double _playheadBeats;+ private double _displayPlayheadBeats; // paint/follow only; edits keep using _playheadBeatsprivate double _totalBeats = 64;private int _beatsPerBar = 4;private ResolvedGrid _lastGrid; // what the snap chip last showed (GridChanged)@@ -642,9 +643,9 @@ public sealed partial class ArrangementView : UserControldouble laneWidth = _lanes.Bounds.Width;if (laneWidth <= 0 || _pixelsPerBeat <= 0) return false;double viewportBeats = laneWidth / _pixelsPerBeat;- double rel = _playheadBeats - _scrollBeats, margin = viewportBeats * 0.05;+ double rel = _displayPlayheadBeats - _scrollBeats, margin = viewportBeats * 0.05;if (rel >= margin && rel <= viewportBeats - margin) return false;- double target = Math.Clamp(_playheadBeats - viewportBeats * 0.25, 0, Math.Max(0, _hScroll.Maximum));+ double target = Math.Clamp(_displayPlayheadBeats - viewportBeats * 0.25, 0, Math.Max(0, _hScroll.Maximum));if (Math.Abs(target - _scrollBeats) < 1e-6) return false;_scrollBeats = target;_hScroll.Value = target;@@ -656,7 +657,7 @@ public sealed partial class ArrangementView : UserControl/// of it, 0 on screen (the ruler draws an arrow at that edge, #105).</summary>internal int PlayheadOffscreen(){- double x = BeatToX(_playheadBeats), w = _lanes.Bounds.Width;+ double x = BeatToX(_displayPlayheadBeats), w = _lanes.Bounds.Width;return w <= 0 ? 0 : x < 0 ? -1 : x > w ? 1 : 0;}@@ -684,25 +685,17 @@ public sealed partial class ArrangementView : UserControldouble laneWidth = _lanes.Bounds.Width;if (laneWidth <= 0 || _pixelsPerBeat <= 0) return false;double viewportBeats = laneWidth / _pixelsPerBeat;- double target = Math.Clamp(_playheadBeats - viewportBeats / 2.0, 0, Math.Max(0, _hScroll.Maximum));+ double target = Math.Clamp(_displayPlayheadBeats - viewportBeats / 2.0, 0, Math.Max(0, _hScroll.Maximum));if (Math.Abs(target - _scrollBeats) < 1e-6) return false;_scrollBeats = target;_hScroll.Value = target; // the InvalidateVisual calls below repaint with the new scrollreturn true;}- public void SetPlayhead(double beats)+ public void SetPlayhead(double beats, bool preserveDisplay = false){- bool moved = beats != _playheadBeats;_playheadBeats = beats;- // While following, the view scrolls under the playhead — the lane surface (clips /- // waveforms) must repaint along with the ruler+overlay, not just the overlay.- // Every Play starts Follow afresh, even when the last run left it paused.bool playing = _engine is { IsPlaying: true };- if (playing && !_wasPlaying) SetFollowSuspended(false);- _wasPlaying = playing;- bool scrolled = _followPlayhead && !FollowSuspended && playing && !_lanes.IsGesturing && !_footerLanes.IsGesturing && CenterOnPlayhead();- if (scrolled) _lanes.InvalidateVisual();// Converge the loop highlight with the engine (~30 Hz) so transport-bar// toggles/changes reflect here too — except mid-drag, where we show a preview.bool loopChanged = false;@@ -716,6 +709,25 @@ public sealed partial class ArrangementView : UserControl// follow a knob turned in the device. Redraw the lanes only when a visible empty lane's// baseline actually changed (params with points are automation-driven — no baseline).if (_automationMode) RefreshAutoBaselines();+ UpdatePlayheadDisplay(preserveDisplay && playing ? _displayPlayheadBeats : beats, playing, loopChanged);+ }++ /// <summary>Frame-rate display update; does no meter, automation or loop polling.</summary>+ public void SetPlayheadFrame(double positionBeats, double displayBeats, bool playing)+ {+ _playheadBeats = positionBeats;+ UpdatePlayheadDisplay(displayBeats, playing, false);+ }++ private void UpdatePlayheadDisplay(double beats, bool playing, bool loopChanged)+ {+ bool moved = beats != _displayPlayheadBeats;+ _displayPlayheadBeats = beats;+ if (playing && !_wasPlaying) SetFollowSuspended(false);+ _wasPlaying = playing;+ // Follow must repaint the content as well as the moving overlay.+ bool scrolled = _followPlayhead && !FollowSuspended && playing && !_lanes.IsGesturing && !_footerLanes.IsGesturing && CenterOnPlayhead();+ if (scrolled) _lanes.InvalidateVisual();// Stopped with nothing moving: the playhead chrome is already right — repainting it// every tick kept the whole window redrawing ~30×/s while idle (#55).if (!moved && !scrolled && !loopChanged) return;diff --git a/src/managed/Nota.App/MainWindow.Playhead.cs b/src/managed/Nota.App/MainWindow.Playhead.csnew file mode 100644index 00000000..3ce180b5--- /dev/null+++ b/src/managed/Nota.App/MainWindow.Playhead.cs@@ -0,0 +1,74 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System;+using Avalonia.Controls;+using Nota.Presentation;++namespace Nota.App;++public partial class MainWindow+{+ private Window? _playheadFrameOwner;+ private Action<TimeSpan>? _playheadFrameCallback;+ private bool _playheadFramePending;+ private bool _playheadFramesClosed;+ private int _playheadFrameGeneration;++ private Window? VisiblePlayheadWindow()+ => IsVisible && WindowState != WindowState.Minimized ? this+ : _detailWindow is { IsVisible: true, WindowState: not WindowState.Minimized } detail ? detail : null;++ // The 30 Hz service tick wakes this loop. Only the cursor runs on display frames;+ // recording materialization, meters and device polling retain their own cadence.+ private void EnsurePlayheadFrames()+ {+ var vm = _vm;+ Window? owner = !_playheadFramesClosed && vm is { SuspendEnginePolling: false }+ && vm.Engine.IsRunning && vm.Engine.IsPlaying ? VisiblePlayheadWindow() : null;+ if (!ReferenceEquals(owner, _playheadFrameOwner))+ {+ _playheadFrameOwner = owner;+ _playheadFramePending = false;+ int generation = ++_playheadFrameGeneration;+ _playheadFrameCallback = owner is null ? null : _ => OnPlayheadFrame(generation);+ }+ if (owner is null || _playheadFramePending) return;+ _playheadFramePending = true;+ owner.RequestAnimationFrame(_playheadFrameCallback!);+ }++ private void OnPlayheadFrame(int generation)+ {+ if (_playheadFramesClosed || generation != _playheadFrameGeneration) return;+ _playheadFramePending = false;+ var vm = _vm;+ if (vm is null || vm.SuspendEnginePolling) { StopPlayheadFrames(); return; }+ // A minimize, docking or export may have happened since this frame was queued.+ if (!ReferenceEquals(VisiblePlayheadWindow(), _playheadFrameOwner) || !vm.Engine.IsRunning)+ {+ EnsurePlayheadFrames();+ return;+ }+ if (vm.Engine.TryGetTransportSnapshot(out var snapshot))+ {+ double displayBeats = TransportDisplayPosition.At(snapshot);+ if (IsVisible && WindowState != WindowState.Minimized)+ Timeline.SetPlayheadFrame(snapshot.PositionBeats, displayBeats, snapshot.IsPlaying);+ // Editor cursors use cheap overlays too, including in the floating detail window.+ if (_audioEditor is { IsEffectivelyVisible: true })+ _audioEditor.OnPlayhead(displayBeats, snapshot.IsPlaying);+ if (_clipEditor is { IsEffectivelyVisible: true } && _editorRoll is not null && _editorTrackId > 0)+ _editorRoll.SetPlayhead(displayBeats - _editorRoll.Origin, true);+ }+ EnsurePlayheadFrames(); // stops once the engine reports stop; no idle animation loop+ }++ private void StopPlayheadFrames()+ {+ ++_playheadFrameGeneration; // invalidate queued callbacks before disposing the engine+ _playheadFrameOwner = null;+ _playheadFrameCallback = null;+ _playheadFramePending = false;+ }+}diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex d25aa4b1..a1a37161 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -296,12 +296,13 @@ public partial class MainWindow : Window{_learn?.Tick(); // apply incoming MIDI mappings / capture a learn messageSyncSceneTempo(); // a launched scene set tempo / signature+ EnsurePlayheadFrames();// Nothing of the window can be seen: keep servicing MIDI and scenes, skip the// meters, playheads and live knobs — they'd redraw ~30×/s for nobody (#55).if (WindowState == WindowState.Minimized&& _detailWindow is not { IsVisible: true, WindowState: not WindowState.Minimized }) return;LearnOverlay.Refresh(); // keep highlights over rebuilt cards while armed- Timeline.SetPlayhead(beats);+ Timeline.SetPlayhead(beats, preserveDisplay: _playheadFrameOwner is not null);_masterMeter?.Push(vm.Engine.MasterMeter());Timeline.UpdateMeters(); // per-track headers (M6-2)Timeline.RefreshAutomationLive(); // show writes live (M9-C)@@ -313,7 +314,7 @@ public partial class MainWindow : Window// Detail contents update wherever they're shown — docked panel or the floating// Devices/Clip window — so key off IsEffectivelyVisible, not the docked panel.if (_deviceChain is { IsEffectivelyVisible: true }) _deviceChain.RefreshSynthLive(); // synth graphs follow automation- if (_audioEditor is { IsEffectivelyVisible: true })+ if (_audioEditor is { IsEffectivelyVisible: true } && _playheadFrameOwner is null)_audioEditor.OnPlayhead(beats, vm.Engine.IsPlaying); // live clip playback cursor// Piano-roll playback cursor: map the global beat to clip-local time for the// open arrangement MIDI clip, shown stopped too, where play will start (#50); a@@ -323,7 +324,8 @@ public partial class MainWindow : Windowif (_editorTrackId > 0){// Editor beats count from the open clips' origin (the clip's start for one).- if (Engine.TryGetClipInfo(_editorTrackId, _editorClipIndex, out var pci) && pci.IsMidi)+ if (_playheadFrameOwner is null+ && Engine.TryGetClipInfo(_editorTrackId, _editorClipIndex, out var pci) && pci.IsMidi)_editorRoll.SetPlayhead(beats - _editorRoll.Origin, true);}else if (_sessionSlotTrack > 0 && _sessionSlotScene >= 0)@@ -567,7 +569,12 @@ public partial class MainWindow : WindowSetUpAudioFormatButton();DropoutButton.Click += (_, _) => vm.ResetDropouts(); // count again from zero (#271)- Closed += (_, _) => vm.Dispose();+ Closed += (_, _) =>+ {+ _playheadFramesClosed = true;+ StopPlayheadFrames();+ vm.Dispose();+ };SetUpCpuTip(vm.Engine);// MCP server: MCP tool edits redraw the arrangement + device panel; start the server ifdiff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex 30fe02b7..611d5e2b 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -226,7 +226,7 @@ public sealed partial class PianoRollView : UserControl}private bool IsRoot(int pitch) => _scaleOn && ((((pitch - _scaleRoot) % 12) + 12) % 12) == 0;- // Live playback cursor in clip-local beats; < 0 = hidden. Set by the host each tick.+ // Live display cursor in clip-local beats; < 0 = hidden. Updated on display frames.private double _playheadBeat = -1;// Note clipboard, shared across clips (copy here, paste into another clip): each note at@@ -269,6 +269,8 @@ public sealed partial class PianoRollView : UserControlpublic Func<int, int, string?>? ClipNameOf { get; set; }private readonly KeysColumn _keys;private readonly NoteGrid _gridControl;+ private readonly PlayheadLayer _gridPlayhead;+ private readonly PlayheadLayer _rulerPlayhead;private readonly VelocityLane _vel;private readonly Border _velHost;private readonly Border _overlayHost = new() { IsVisible = false, ClipToBounds = true };@@ -378,7 +380,7 @@ public sealed partial class PianoRollView : UserControl// Scale rows are a neutral lift, not the accent: a key at rest is neither live nor chosen.private static readonly IBrush InScaleTint = NotaPalette.Wash(NotaPalette.VizInk, 0x0C);private static readonly IBrush RootTint = NotaPalette.Wash(NotaPalette.VizInk, 0x1E);- private static readonly IPen PlayheadPen = new Pen(NotaPalette.Accent, 1); // the playhead: 1px accent+ private static readonly IPen PlayheadPen = new Pen(NotaPalette.Accent, 1); // the playhead: 1px live cursorprivate static readonly IBrush KeyHover = NotaPalette.Wash(NotaPalette.AccentBright, 0x66);// Played-key highlight (currently-pressed keyboard / MIDI note): a solid key tint + a faint row wash.private static readonly IBrush HeldKeyFill = NotaPalette.Accent;@@ -416,6 +418,8 @@ public sealed partial class PianoRollView : UserControl_strip = new ClipStrip(this) { ClipToBounds = true, IsVisible = false, Height = ClipStrip.RowH };_keys = new KeysColumn(this) { Height = RangeH };_gridControl = new NoteGrid(this) { Height = RangeH, ClipToBounds = true };+ _gridPlayhead = new PlayheadLayer(this);+ _rulerPlayhead = new PlayheadLayer(this);_vel = new VelocityLane(this) { ClipToBounds = true };_expr = new ExpressionLane(this) { ClipToBounds = true };_ctlLane = new ControllerLane(this) { ClipToBounds = true, Focusable = true };@@ -428,6 +432,8 @@ public sealed partial class PianoRollView : UserControlbody.Children.Add(_keys);Avalonia.Controls.Grid.SetColumn(_gridControl, 1);body.Children.Add(_gridControl);+ Avalonia.Controls.Grid.SetColumn(_gridPlayhead, 1);+ body.Children.Add(_gridPlayhead);_bodyScroll = new ScrollViewer{Content = body,@@ -443,6 +449,8 @@ public sealed partial class PianoRollView : UserControlrulerRow.Children.Add(corner);Avalonia.Controls.Grid.SetColumn(_ruler, 1);rulerRow.Children.Add(_ruler);+ Avalonia.Controls.Grid.SetColumn(_rulerPlayhead, 1);+ rulerRow.Children.Add(_rulerPlayhead);// The clip strip (several clips open): corner + strip, under the ruler.var stripRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*") };@@ -1233,15 +1241,40 @@ public sealed partial class PianoRollView : UserControl}/// <summary>Live playback cursor in editor beats (clip-local for one clip); playing=false- /// or an out-of-range beat hides it. Cheap: repaints only the grid + ruler, not the whole roll.</summary>+ /// or an out-of-range beat hides it. Repaints only the two cursor overlays.</summary>public void SetPlayhead(double clipLocalBeat, bool playing){double b = (playing && clipLocalBeat >= 0 && clipLocalBeat <= _lengthBeats) ? clipLocalBeat : -1;bool wasHidden = _playheadBeat < 0;if (Math.Abs(b - _playheadBeat) < 1e-6 && (b < 0) == wasHidden) return;_playheadBeat = b;- _gridControl.InvalidateVisual();- _ruler.InvalidateVisual();+ InvalidatePlayhead();+ }++ private void InvalidatePlayhead()+ {+ _gridPlayhead.InvalidateVisual();+ _rulerPlayhead.InvalidateVisual();+ }++ // Separate render nodes retain the grid's notes and ruler labels between cursor frames.+ // Being siblings in their existing cells keeps clipping, scroll and pointer routing intact.+ private sealed class PlayheadLayer : Control+ {+ private readonly PianoRollView _o;+ public PlayheadLayer(PianoRollView o)+ {+ _o = o;+ IsHitTestVisible = false;+ ClipToBounds = true;+ }+ public override void Render(DrawingContext ctx)+ {+ if (_o._playheadBeat < 0) return;+ double x = _o.BeatToX(_o._playheadBeat);+ if (x >= 0 && x <= Bounds.Width)+ ctx.DrawLine(PlayheadPen, new Point(x, 0), new Point(x, Bounds.Height));+ }}/// <summary>Copies the selected notes to the shared clipboard, each with the clip it came@@ -1591,6 +1624,7 @@ public sealed partial class PianoRollView : UserControlprivate void Invalidate(){if (_fold) RebuildRows(); // notes, scale or pads may have moved the folded rows+ InvalidatePlayhead();_overlayHost.Child?.InvalidateVisual();_ruler.InvalidateVisual();_strip.InvalidateVisual();@@ -1819,11 +1853,6 @@ public sealed partial class PianoRollView : UserControl}}_o.DrawOutsideClip(ctx, w, h);- if (_o._playheadBeat >= 0)- {- double px = _o.BeatToX(_o._playheadBeat);- if (px >= 0 && px <= w) ctx.DrawLine(PlayheadPen, new Point(px, 0), new Point(px, h));- }}}@@ -2187,11 +2216,6 @@ public sealed partial class PianoRollView : UserControl: new SolidColorBrush(Color.FromArgb((byte)(255 * (0.45 + 0.55 * Math.Clamp(hn.Velocity, 0, 1))), c.R, c.G, c.B)), hr, 2);}_o.DrawOutsideClip(ctx, w, h);- if (_o._playheadBeat >= 0)- {- double px = BeatToX(_o._playheadBeat);- if (px >= 0 && px <= w) ctx.DrawLine(PlayheadPen, new Point(px, 0), new Point(px, h));- }if (_drag == Mode.Marquee){var r = RectOf(_marqueeA, _marqueeB);diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 5ae04203..99c9e844 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -44,6 +44,8 @@ public interface IAudioEngine : IDisposablevoid SetMetronome(bool enabled);void Seek(double beat);double PositionBeats { get; }+ /// <summary>Display-only rendered-block snapshot. False before rendering or during publication.</summary>+ bool TryGetTransportSnapshot(out NotaTransportSnapshot snapshot);bool IsPlaying { get; }/// <summary>Loop region mirror (for UI display + toggling).</summary>bool LoopEnabled { get; }diff --git a/src/managed/Nota.Application/Engine/NotaTransportSnapshot.cs b/src/managed/Nota.Application/Engine/NotaTransportSnapshot.csnew file mode 100644index 00000000..7952de1d--- /dev/null+++ b/src/managed/Nota.Application/Engine/NotaTransportSnapshot.cs@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Runtime.InteropServices;++namespace Nota.Application;++/// <summary>A coherent rendered block for display interpolation. Mirrors NotaTransportSnapshot+/// in the C ABI; elapsed time is measured by the engine's monotonic clock.</summary>+[StructLayout(LayoutKind.Sequential)]+public struct NotaTransportSnapshot+{+ public double StartBeat;+ public double PositionBeats;+ public double Bpm;+ public double LoopStart;+ public double LoopEnd;+ public double DurationSeconds;+ public double ElapsedSeconds;+ public int Playing;+ public int Looping;++ public readonly bool IsPlaying => Playing != 0;+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex c97c13e5..3aabd6f4 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -102,6 +102,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_transport_position_beats")]internal static partial double PositionBeats(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_transport_snapshot")]+ internal static partial int TransportSnapshot(IntPtr engine, out NotaTransportSnapshot snapshot);+[LibraryImport(Lib, EntryPoint = "nota_transport_is_playing")]internal static partial int IsPlaying(IntPtr engine);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex 0296d9af..1ecf3814 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -102,6 +102,11 @@ public sealed partial class NotaEngine : IAudioEngine/// <summary>Current playhead position in beats (lock-free UI read).</summary>public double PositionBeats { get { ThrowIfDisposed(); return NativeMethods.PositionBeats(_handle); } }+ public bool TryGetTransportSnapshot(out NotaTransportSnapshot snapshot)+ {+ ThrowIfDisposed();+ return NativeMethods.TransportSnapshot(_handle, out snapshot) != 0;+ }public bool IsPlaying { get { ThrowIfDisposed(); return NativeMethods.IsPlaying(_handle) != 0; } }/// <summary>Loop region mirror (for UI display + toggling).</summary>diff --git a/src/managed/Nota.Presentation/ViewModels/TransportDisplayPosition.cs b/src/managed/Nota.Presentation/ViewModels/TransportDisplayPosition.csnew file mode 100644index 00000000..084a6fdb--- /dev/null+++ b/src/managed/Nota.Presentation/ViewModels/TransportDisplayPosition.cs@@ -0,0 +1,25 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using Nota.Application;++namespace Nota.Presentation;++/// <summary>Places a display cursor within the last rendered block (AR-9). It never+/// runs past that block if audio stalls, and its result is never an editing position.</summary>+public static class TransportDisplayPosition+{+ public static double At(in NotaTransportSnapshot snapshot)+ {+ if (!snapshot.IsPlaying || snapshot.DurationSeconds <= 0 || snapshot.Bpm <= 0+ || !double.IsFinite(snapshot.ElapsedSeconds)) return snapshot.PositionBeats;++ // Use the exact endpoint once the block has elapsed, including rounding at a seam.+ double beat = snapshot.ElapsedSeconds >= snapshot.DurationSeconds+ ? snapshot.PositionBeats+ : snapshot.StartBeat + Math.Max(0, snapshot.ElapsedSeconds) * snapshot.Bpm / 60;+ if (snapshot.Looping != 0 && snapshot.LoopEnd > snapshot.LoopStart && beat >= snapshot.LoopEnd)+ beat = snapshot.LoopStart + (beat - snapshot.LoopStart) % (snapshot.LoopEnd - snapshot.LoopStart);+ return beat;+ }+}diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 22990dc6..0a7f14c5 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -539,6 +539,27 @@ NOTA_API NotaResult nota_transport_seek(NotaEngine* engine, double beat);/* UI polls these (lock-free reads of the mirrored transport state). */NOTA_API double nota_transport_position_beats(const NotaEngine* engine);NOTA_API int32_t nota_transport_is_playing(const NotaEngine* engine);+/* Coherent display-only snapshot of the last rendered audio window (at most one+ * hardware period or client block, and never before the latest seek/start/tempo+ * change). This covers WASAPI's batching of small client buffers. elapsed_seconds is+ * measured on the native monotonic clock, relative to the start of its playing+ * portion (negative during a leading count-in). Interpolate start_beat at bpm for+ * clamp(elapsed_seconds, 0, duration_seconds), wrapping at the loop end. Never+ * extrapolate beyond that block or use the visual result for editing commands.+ * Returns 1 on success, 0 before the first block or if publication is in progress;+ * on failure out_snapshot is untouched. No allocation, locks or waiting. */+typedef struct NotaTransportSnapshot {+ double start_beat;+ double position_beats;+ double bpm;+ double loop_start;+ double loop_end;+ double duration_seconds;+ double elapsed_seconds;+ int32_t playing;+ int32_t looping;+} NotaTransportSnapshot;+NOTA_API int32_t nota_transport_snapshot(const NotaEngine* engine, NotaTransportSnapshot* out_snapshot);/* Loop region (message-thread mirror) for UI display + toggling. */NOTA_API int32_t nota_transport_loop_enabled(const NotaEngine* engine);NOTA_API double nota_transport_loop_start(const NotaEngine* engine);diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cppindex 8e1dbaff..4b68e66f 100644--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp@@ -208,6 +208,9 @@ NotaResult nota_transport_seek(NotaEngine* e, double beat) {double nota_transport_position_beats(const NotaEngine* e) {return e ? CENG(e)->positionBeats() : 0.0;}+int32_t nota_transport_snapshot(const NotaEngine* e, NotaTransportSnapshot* out_snapshot) {+ return e && out_snapshot && CENG(e)->transportSnapshot(*out_snapshot) ? 1 : 0;+}int32_t nota_transport_is_playing(const NotaEngine* e) {return (e && CENG(e)->isPlaying()) ? 1 : 0;}diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex dbd5a3bd..5d2d67a0 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -354,6 +354,7 @@ class Engine {void setMetronome(bool on);void seekBeats(double beat);double positionBeats() const { return transport_.uiPositionBeats(); }+ bool transportSnapshot(NotaTransportSnapshot& out) const { return transport_.presentationSnapshot(out); }bool isPlaying() const { return transport_.uiIsPlaying(); }// Message-thread mirror of the loop region (for UI display; the audio thread// gets the range via the command queue).diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex 2ac5c7be..d94788ce 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -1801,6 +1801,8 @@ void Engine::processBlock(float* out, int32_t numFrames) {int32_t done = 0;int32_t loopSeams[16];int32_t nLoopSeams = 0; // block offsets where the loop wrapped+ double presentationStart = transport_.playheadSamples();+ int32_t presentationFrames = 0, presentationLead = 0;while (done < numFrames) {if (playing && transport_.isLooping() && transport_.playheadSamples() >= transport_.loopEndSamples() - 0.5) {// No voice flush here: clip notes crossing the loop end get note-offs in the next@@ -1823,6 +1825,10 @@ void Engine::processBlock(float* out, int32_t numFrames) {if (left < seg) seg = std::max(1, static_cast<int32_t>(std::lround(left)));}const double segStart = transport_.playheadSamples();+ if (playing) {+ if (presentationFrames == 0) { presentationStart = segStart; presentationLead = done; }+ presentationFrames += seg;+ }chaseNotes_ = chase;if (g && sr > 0.0) mixGraph(g, out + done * 2, seg, segStart, playing, spb);chaseNotes_ = chase = seamOffs_ = false;@@ -1914,6 +1920,8 @@ void Engine::processBlock(float* out, int32_t numFrames) {stereoBlockStep(numFrames, transport_.sampleRate()));masterPeakL_.store(mpkL, std::memory_order_relaxed);masterPeakR_.store(mpkR, std::memory_order_relaxed);+ transport_.publishPresentation(presentationStart, presentationFrames, presentationLead,+ deviceBlock_ && backend_ ? std::max(numFrames, backend_->bufferFrames()) : numFrames);masterRmsL_.store(numFrames ? static_cast<float>(std::sqrt(msqL / numFrames)) : 0.0f, std::memory_order_relaxed);masterRmsR_.store(numFrames ? static_cast<float>(std::sqrt(msqR / numFrames)) : 0.0f, std::memory_order_relaxed);}diff --git a/src/native/nota.engine/src/engine/Transport.cpp b/src/native/nota.engine/src/engine/Transport.cppindex 19c32eb8..a1fa4a86 100644--- a/src/native/nota.engine/src/engine/Transport.cpp+++ b/src/native/nota.engine/src/engine/Transport.cpp@@ -3,9 +3,14 @@#include "Transport.h"+#include <chrono>+#include <algorithm>+#include <cmath>+namespace nota {void Transport::setLoop(bool enabled, double startBeat, double endBeat) {+ ++presentationEpoch_;loopEnabled_ = enabled && endBeat > startBeat;loopStartBeat_ = startBeat;loopEndBeat_ = endBeat;@@ -37,4 +42,72 @@ void Transport::publish() {uiPlaying_.store(playing_, std::memory_order_relaxed);}+static int64_t presentationNow() {+ return std::chrono::duration_cast<std::chrono::nanoseconds>(+ std::chrono::steady_clock::now().time_since_epoch()).count();+}++void Transport::publishPresentation(double startSamples, int32_t playingFrames, int32_t leadingFrames, int32_t windowFrames) {+ static_assert(std::atomic<double>::is_always_lock_free && std::atomic<int64_t>::is_always_lock_free+ && std::atomic<uint32_t>::is_always_lock_free && std::atomic<int32_t>::is_always_lock_free);+ if (presentationPublishedEpoch_ != presentationEpoch_ || !playing_) {+ presentationPublishedEpoch_ = presentationEpoch_;+ presentationFrames_ = 0;+ presentationOrigin_ = startSamples;+ }+ // Loop seams round to whole samples. Re-anchor the history at each real block+ // start so fractional-sample loop lengths cannot accumulate display drift.+ if (presentationFrames_ > 0 && playingFrames > 0) {+ double predicted = (presentationOrigin_ + presentationFrames_) / samplesPerBeat();+ const double actual = startSamples / samplesPerBeat();+ if (loopEnabled_ && predicted >= loopEndBeat_)+ predicted = loopStartBeat_ + std::fmod(predicted - loopStartBeat_, loopEndBeat_ - loopStartBeat_);+ double correction = actual - predicted;+ if (loopEnabled_ && actual >= loopStartBeat_ && predicted >= loopStartBeat_)+ correction = std::remainder(correction, loopEndBeat_ - loopStartBeat_);+ presentationOrigin_ += correction * samplesPerBeat();+ }+ presentationFrames_ += playingFrames;+ const auto span = std::min<int64_t>(presentationFrames_, std::max(windowFrames, playingFrames));+ double startBeat = (presentationOrigin_ + (presentationFrames_ - span)) / samplesPerBeat();+ if (loopEnabled_ && startBeat >= loopEndBeat_)+ startBeat = loopStartBeat_ + std::fmod(startBeat - loopStartBeat_, loopEndBeat_ - loopStartBeat_);+ presentationSequence_.fetch_add(1, std::memory_order_relaxed);+ presentationStart_.store(startBeat, std::memory_order_release);+ presentationEnd_.store(positionBeats(), std::memory_order_release);+ presentationBpm_.store(bpm_, std::memory_order_release);+ presentationLoopStart_.store(loopStartBeat_, std::memory_order_release);+ presentationLoopEnd_.store(loopEndBeat_, std::memory_order_release);+ presentationDuration_.store(sampleRate_ > 0 ? span / sampleRate_ : 0.0, std::memory_order_release);+ presentationDelay_.store(sampleRate_ > 0 ? leadingFrames / sampleRate_ : 0.0, std::memory_order_release);+ presentationPlaying_.store(playing_ ? 1 : 0, std::memory_order_release);+ presentationLooping_.store(loopEnabled_ ? 1 : 0, std::memory_order_release);+ presentationStamp_.store(presentationNow(), std::memory_order_release);+ presentationSequence_.fetch_add(1, std::memory_order_release);+}++bool Transport::presentationSnapshot(NotaTransportSnapshot& out) const {+ for (int attempt = 0; attempt < 3; ++attempt) {+ const auto before = presentationSequence_.load(std::memory_order_acquire);+ if (before & 1) continue;+ NotaTransportSnapshot s{};+ s.start_beat = presentationStart_.load(std::memory_order_acquire);+ s.position_beats = presentationEnd_.load(std::memory_order_acquire);+ s.bpm = presentationBpm_.load(std::memory_order_acquire);+ s.loop_start = presentationLoopStart_.load(std::memory_order_acquire);+ s.loop_end = presentationLoopEnd_.load(std::memory_order_acquire);+ s.duration_seconds = presentationDuration_.load(std::memory_order_acquire);+ const auto delay = presentationDelay_.load(std::memory_order_acquire);+ s.playing = presentationPlaying_.load(std::memory_order_acquire);+ s.looping = presentationLooping_.load(std::memory_order_acquire);+ const auto stamp = presentationStamp_.load(std::memory_order_acquire);+ if (before != presentationSequence_.load(std::memory_order_acquire)) continue;+ if (stamp == 0) return false;+ s.elapsed_seconds = (presentationNow() - stamp) * 1.0e-9 - delay;+ out = s;+ return true;+ }+ return false;+}+} // namespace notadiff --git a/src/native/nota.engine/src/engine/Transport.h b/src/native/nota.engine/src/engine/Transport.hindex b4794025..1d94c0eb 100644--- a/src/native/nota.engine/src/engine/Transport.h+++ b/src/native/nota.engine/src/engine/Transport.h@@ -11,16 +11,18 @@#include <cstdint>#include "TransportInfo.h"+#include "nota/nota_engine.h"namespace nota {class Transport {public:- void setSampleRate(double sr) { sampleRate_ = sr; }+ void setSampleRate(double sr) { sampleRate_ = sr; ++presentationEpoch_; }double sampleRate() const { return sampleRate_; }// --- control (applied on the audio thread) ---void play() {+ if (!playing_) ++presentationEpoch_;playing_ = true;publish();}@@ -28,12 +30,13 @@ class Transport {// position), so the next Play begins where the user launched from — not where it// happened to halt. Classic transport behaviour.void stop() {+ ++presentationEpoch_;playing_ = false;playheadSamples_ = startAnchorSamples_;publish();}void setBpm(double bpm) {- if (bpm > 0) bpm_ = bpm;+ if (bpm > 0 && bpm != bpm_) { bpm_ = bpm; ++presentationEpoch_; }publish();}double bpm() const { return bpm_; }@@ -48,6 +51,7 @@ class Transport {// Seeking sets the insert marker: the playhead moves here and this becomes the// start anchor that Stop rewinds to and the next Play launches from.void seekBeats(double beat) {+ ++presentationEpoch_;playheadSamples_ = beat * samplesPerBeat();startAnchorSamples_ = playheadSamples_;publish();@@ -85,6 +89,10 @@ class Transport {double uiPositionBeats() const { return uiBeats_.load(std::memory_order_relaxed); }bool uiIsPlaying() const { return uiPlaying_.load(std::memory_order_relaxed); }+ // Publish once per completed block; readers may skip a frame, never delay audio.+ void publishPresentation(double startSamples, int32_t playingFrames, int32_t leadingFrames, int32_t windowFrames);+ bool presentationSnapshot(NotaTransportSnapshot& out) const;+private:void publish();@@ -100,6 +108,21 @@ class Transport {std::atomic<double> uiBeats_{0.0};std::atomic<bool> uiPlaying_{false};++ // Atomic payloads avoid data races even when a reader overlaps the writer.+ // A bounded version check rejects mixed blocks. Release/acquire on each field+ // makes observing any new payload also expose the writer's odd sequence.+ std::atomic<uint32_t> presentationSequence_{0};+ std::atomic<double> presentationStart_{0.0}, presentationEnd_{0.0}, presentationBpm_{120.0};+ std::atomic<double> presentationLoopStart_{0.0}, presentationLoopEnd_{0.0};+ std::atomic<double> presentationDuration_{0.0}, presentationDelay_{0.0};+ std::atomic<int64_t> presentationStamp_{0};+ std::atomic<int32_t> presentationPlaying_{0}, presentationLooping_{0};+ // Audio-thread history spans a hardware period when WASAPI batches smaller+ // client callbacks. Control discontinuities reset it before any interpolation.+ uint64_t presentationEpoch_ = 0, presentationPublishedEpoch_ = 0;+ int64_t presentationFrames_ = 0;+ double presentationOrigin_ = 0.0;};} // namespace notadiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 65960960..7bdadd00 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -277,6 +277,13 @@ if (args.Length >= 1 && args[0] == "--bundle")return failures == 0 ? 0 : 1;}+// Deterministic display math and the transport-snapshot ABI, without the full DSP suite.+if (args.Length >= 1 && args[0] == "--transport-display")+{+ foreach (var (ok, label) in TransportDisplayTests.Run()) Check(ok, label);+ return failures == 0 ? 0 : 1;+}+// Render pool performance guards alone: `--perf`. Also part of the full run.if (args.Length >= 1 && args[0] == "--perf"){@@ -15388,6 +15395,9 @@ foreach (var (ok, label) in RenderPoolTests.Run()) Check(ok, label);Console.WriteLine("-- tap tempo --");foreach (var (ok, label) in TapTempoTests.Run()) Check(ok, label);+Console.WriteLine("-- transport display --");+foreach (var (ok, label) in TransportDisplayTests.Run()) Check(ok, label);+Console.WriteLine("-- velocity wheel --");foreach (var (ok, label) in VelocityWheelTests.Run()) Check(ok, label);Console.WriteLine("-- status bar audio format --");diff --git a/tests/Nota.SmokeTest/TransportDisplayTests.cs b/tests/Nota.SmokeTest/TransportDisplayTests.csnew file mode 100644index 00000000..e5cce1e8--- /dev/null+++ b/tests/Nota.SmokeTest/TransportDisplayTests.cs@@ -0,0 +1,102 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Runtime.InteropServices;+using Nota.Infrastructure;+using Nota.Presentation;++namespace Nota.SmokeTest;++internal static class TransportDisplayTests+{+ private static bool Near(double a, double b) => Math.Abs(a - b) < 1e-8;++ public static IEnumerable<(bool, string)> Run()+ {+ yield return (Marshal.SizeOf<NotaTransportSnapshot>() == 64, "transport display: snapshot ABI size is 64 bytes");+ var s = new NotaTransportSnapshot+ {+ StartBeat = 8, PositionBeats = 8.2, Bpm = 120, Playing = 1,+ DurationSeconds = .1, ElapsedSeconds = .025+ };+ yield return (Near(TransportDisplayPosition.At(s), 8.05), "transport display: interpolates a rendered block between engine updates");+ s.ElapsedSeconds = .075;+ yield return (Near(TransportDisplayPosition.At(s), 8.15), "transport display: later display frame advances within the same block");+ s.ElapsedSeconds = 5;+ yield return (Near(TransportDisplayPosition.At(s), 8.2), "transport display: stalled audio or a delayed UI frame holds the exact rendered endpoint");+ s.Playing = 0; s.PositionBeats = 3; s.ElapsedSeconds = .01;+ yield return (Near(TransportDisplayPosition.At(s), 3), "transport display: stop/pause uses the authoritative position immediately");+ s.Playing = 1; s.StartBeat = 100; s.PositionBeats = 100.1; s.Bpm = 60;+ yield return (Near(TransportDisplayPosition.At(s), 100.01), "transport display: seek and tempo changes use the new block without old clock drift");+ s.ElapsedSeconds = -.5;+ yield return (Near(TransportDisplayPosition.At(s), 100), "transport display: a leading count-in cannot move the cursor early");+ s.DurationSeconds = 0;+ yield return (Near(TransportDisplayPosition.At(s), 100.1), "transport display: a zero-length playing portion uses its exact position");++ s = new() { StartBeat = 3.9, PositionBeats = 3.3, Bpm = 120, Playing = 1, Looping = 1,+ LoopStart = 3, LoopEnd = 4, DurationSeconds = .2, ElapsedSeconds = .075 };+ yield return (Near(TransportDisplayPosition.At(s), 3.05), "transport display: interpolates across a loop seam");+ s.StartBeat = 2; s.PositionBeats = 2.4; s.ElapsedSeconds = .05;+ yield return (Near(TransportDisplayPosition.At(s), 2.1), "transport display: playback before the loop start stays outside the loop");+ s.StartBeat = 3.9; s.PositionBeats = 4; s.ElapsedSeconds = .2;+ yield return (Near(TransportDisplayPosition.At(s), 3), "transport display: an exact loop endpoint wraps to the loop start");+ s.LoopEnd = s.LoopStart;+ yield return (Near(TransportDisplayPosition.At(s), 4), "transport display: an invalid loop range never divides by zero");++ using var engine = new NotaEngine();+ yield return (!engine.TryGetTransportSnapshot(out _), "transport snapshot: unavailable before the first block");+ var buffer = new float[1024];+ engine.SetBpm(120); engine.Seek(8); engine.Play();+ engine.RenderOffline(buffer, 512);+ bool got = engine.TryGetTransportSnapshot(out var native);+ yield return (got && native.IsPlaying && Near(native.StartBeat, 8) && Near(native.Bpm, 120)+ && Near(native.DurationSeconds, 512.0 / 44100) && Near(native.PositionBeats, engine.PositionBeats)+ && double.IsFinite(native.ElapsedSeconds), "transport snapshot: C ABI returns a coherent rendered block and native clock age");+ engine.StopTransport(); engine.RenderOffline(buffer, 512);+ yield return (engine.TryGetTransportSnapshot(out native) && !native.IsPlaying && Near(native.PositionBeats, 8)+ && Near(TransportDisplayPosition.At(native), 8), "transport snapshot: stop rewinds to the authoritative launch anchor");+ engine.SetBpm(60); engine.Seek(12); engine.Play(); engine.RenderOffline(buffer, 512);+ yield return (engine.TryGetTransportSnapshot(out native) && Near(native.StartBeat, 12) && Near(native.Bpm, 60)+ && Near(native.PositionBeats, 12 + 512.0 / 44100), "transport snapshot: a seek and tempo change replace the old block together");+ engine.SetBpm(120); engine.SetLoop(true, 3, 4); engine.Seek(3.9);+ engine.RenderOffline(new float[22050], 11025);+ yield return (engine.TryGetTransportSnapshot(out native) && native.Looping == 1 && Near(native.StartBeat, 3.9)+ && Near(native.LoopStart, 3) && Near(native.LoopEnd, 4) && Near(native.PositionBeats, 3.4),+ "transport snapshot: a block split at a loop seam retains its original start and wrapped end");+ engine.SetLoop(true, 1, 1.25); engine.Seek(1); engine.RenderOffline(buffer, 512);+ bool noLoopDrift = true;+ for (int i = 0; i < 2000; ++i)+ {+ double before = engine.PositionBeats;+ if (before >= 1.25 - .5 / 22050) before = 1;+ engine.RenderOffline(buffer, 512);+ noLoopDrift &= engine.TryGetTransportSnapshot(out native) && Near(native.StartBeat, before);+ }+ yield return (noLoopDrift, "transport snapshot: fractional-sample loop lengths do not accumulate display drift");+ engine.SetLoop(false, 0, 0); engine.StopTransport(); engine.Seek(6); engine.SetCountIn(1);+ engine.RenderOffline(buffer, 512); // apply stop before PlayWithCountIn checks the UI mirror+ engine.PlayWithCountIn(); engine.RenderOffline(buffer, 512);+ yield return (engine.TryGetTransportSnapshot(out native) && !native.IsPlaying && Near(native.PositionBeats, 6),+ "transport snapshot: count-in leaves the transport cursor stationary");+ engine.RenderOffline(new float[44100 * 4], 44100 * 2);+ yield return (engine.TryGetTransportSnapshot(out native) && native.IsPlaying && Near(native.StartBeat, 6)+ && native.DurationSeconds > 0 && native.DurationSeconds < .02,+ "transport snapshot: a block ending its count-in publishes only the playing portion");++ // The UI can overlap publication without waiting on the audio writer. The+ // payload must always describe one block, even during rapid offline rendering.+ engine.StopTransport(); engine.Seek(0); engine.Play(); engine.RenderOffline(buffer, 512);+ bool coherent = true;+ int reads = 0;+ var writer = Task.Run(() => { for (int i = 0; i < 4000; ++i) engine.RenderOffline(buffer, 512); });+ do+ {+ if (!engine.TryGetTransportSnapshot(out native)) continue;+ ++reads;+ coherent &= native.IsPlaying && Near(native.Bpm, 120) && native.Looping == 0+ && Near(native.PositionBeats - native.StartBeat, 512.0 / 22050);+ } while (!writer.IsCompleted);+ writer.GetAwaiter().GetResult();+ yield return (reads > 0 && coherent, "transport snapshot: concurrent reads never mix two published blocks");+ }+}