Skip to content

armgit / nota

Public Imported from GitHub
0

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

(fix) Render hosted plug-in instruments once per block; free replaced engine graphs (#438)

Egor Khindikaynenc74d58034326
diff --git a/.specify/bugs/kontakt-cpu-dropouts/assessment.md b/.specify/bugs/kontakt-cpu-dropouts/assessment.md
new file mode 100644
index 00000000..a8c788f4
--- /dev/null
+++ b/.specify/bugs/kontakt-cpu-dropouts/assessment.md
@@ -0,0 +1,169 @@
+# Bug Assessment: high CPU and dropouts with four Kontakt instances
+
+- **Slug**: kontakt-cpu-dropouts
+- **Created**: 2026-11-02
+- **Source**: https://github.com/nota-daw/nota/issues/436 (host: github.com, allowlisted; issue written in this session from the user's report) + reproducing project `~/Documents/Nota Projects/kontakt_problem.nota`
+- **Verdict**: valid
+- **Severity**: high (hosting several heavy sampler plug-ins — a core DAW use case — drops out on a top-end machine; affects every hosted plug-in instrument, not only Kontakt)
+
+## Report (summarized)
+
+> **High CPU load and audio dropouts with four Kontakt instances** — With four instances of
+> Kontakt loaded (one per instrument track), CPU load climbs very high as soon as playback
+> starts and the audio drops out. Expected: four Kontakt instances play without dropouts, as
+> in other DAWs.
+
+Follow-up from the reporter: the dropouts do not start at once but after some time of playback.
+
+Environment: Nota 0.58.1 (develop), macOS 26.6.2, Apple M4 Max. `audio.json`: built-in
+speakers out, built-in microphone in, **64-frame buffer** at 44.1 kHz (period ≈ 1.45 ms).
+
+The project: four instrument tracks, each `AudioUnit-Kontakt 8`, each with one 16-beat clip of
+114 short notes (1/64 beat and up) on four pitches; two clips start at beat 0 and two at beat 1,
+so the tracks' events fall on different samples. Loop on, 120 BPM, all four tracks
+record-armed. Today's log (`~/Library/Application Support/Nota/logs/nota-20261102.log`) shows
+~100 `Audio dropout` warnings in 16:29–16:32, sparse at first, then several per second.
+
+## Symptom
+
+Playing the project, the audio callback overruns more and more often until there are several
+dropouts a second. Expected: four Kontakt instances at 64 frames on an M4 Max play cleanly.
+
+## Reproduction
+
+1. Set the audio buffer to 64 frames (Preferences → Audio).
+2. Open `kontakt_problem.nota` (four Kontakt 8 AU instances, dense short-note loops).
+3. Play with loop on; watch the CPU meter / dropout counter for a minute.
+4. Dropouts begin after a while and become frequent.
+
+[NEEDS CLARIFICATION: does it also happen at 256/512 frames, and with the tracks disarmed?]
+
+## Suspected Code Paths
+
+- `src/native/nota.engine/src/engine/Engine_Render.cpp:170` `playEvents()` — renders an
+ instrument in stretches between MIDI events: `renderTo(off)` → `inst.render(&dst[cursor*2],
+ to - cursor)` before every note-on/off and expression event. Right for built-in synths
+ (events land between sub-renders), but for a hosted plug-in each stretch is a whole
+ `processBlock` call.
+- `src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp:63` `render()` — one
+ `plugin_->processBlock(block, pending_)` per call; `noteOn/noteOff/controller` (`:37–60`)
+ add every event at sample 0 of the *next* call. So a 64-frame block with k events becomes up
+ to k+1 `processBlock` calls with buffers as small as 1 frame, each with the full per-call
+ overhead of the plug-in (Kontakt: voice/stream bookkeeping, internal threading, AU render
+ setup). The loops here put 2–4 events into many blocks.
+- `src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp:169` `prepare()` →
+ `enableEveryBus()` (`PluginCommon.cpp:32`) — every output bus of the plug-in is enabled, and
+ JUCE's AU wrapper (`juce_AudioUnitPluginFormatImpl.h:1329–1435`) copies the whole buffer and
+ runs one `AudioUnitRender` per enabled bus on *every* `processBlock`. For a multi-out
+ instrument (Kontakt exposes up to 16 stereo outs) each of the many sub-block calls above
+ renders all of them, though Nota only mixes the main bus.
+- `src/native/nota.engine/src/engine/Engine_Render.cpp:2341–2347` — leaves hosting a plug-in
+ (instrument or any un-bypassed plug-in device) are never `eligible` for the render pool
+ ("hosted plugin instances are not thread-safe across threads"). All four Kontakt instances
+ render serially on the CoreAudio callback thread, whatever the load, so their summed cost
+ must fit one 1.45 ms period. The render pool (`AudioThreadPool`, P-cores, adaptive
+ `rtParallel_` join) exists but does nothing for this project.
+- `src/native/nota.engine/src/engine/AudioThreadPool.cpp:49` — workers are plain
+ `std::thread`s: no `THREAD_TIME_CONSTRAINT` policy and no join to the device's
+ `os_workgroup` (`kAudioDevicePropertyIOThreadOSWorkgroup`); there's no use of either
+ anywhere in the engine. Relevant once plug-ins render on the pool: macOS may run
+ non-workgroup threads at low clocks / on E-cores, so pool work can miss a 1.45 ms deadline.
+
+Ruled out by reading the code (MIDI path traced end to end): no lost note-offs at the loop
+seam (`seamOffs_` emits offset-0 offs for notes crossing the seam, chase re-triggers sort
+after them), none for sub-block notes, no duplicated note-ons; nothing on the plug-in path
+allocates or grows per block while the tracks are only armed. Loop wraps send no
+`allNotesOff` by design (#29), so release tails ring across the seam — normal, but it feeds
+Kontakt's voice count. Recording (not just arming) would add a growing `clip.notes` scan per
+block; the report doesn't involve recording.
+
+## Root Cause Hypothesis
+
+Two compounding costs on a single real-time thread. (1) Every hosted plug-in instrument is
+called once per MIDI-event stretch instead of once per block, multiplying Kontakt's per-call
+overhead by the event density and feeding it sub-block buffers; (2) all plug-in tracks are
+excluded from the render pool, so four instances add up serially inside one 64-frame period.
+"After some time": Kontakt's per-call cost grows with the number of sounding voices (release
+tails of the dense loop accumulate, disk-streaming pre-load grows), so the serial sum starts
+under the period and creeps over it. Confidence: **high** for (1) and (2) being real and
+costly, **medium** that together they fully explain the report until measured.
+
+## Proposed Remediation
+
+**Preferred** — two independent changes, measured separately:
+
+1. *One `processBlock` per block for hosted plug-in instruments.* Add a block-MIDI path for
+ instruments that take sample-accurate events themselves (e.g.
+ `Instrument::takesTimedEvents()`; `PluginInstrument` returns true). In `playEvents`, for
+ such instruments send note-on/off, controllers and expression with their sample offset
+ (new offset-aware entry points, or the existing `MidiEv`/`ExprEv` arrays) into the
+ plug-in's `MidiBuffer`, keep the sustain-pedal bookkeeping (`sendNoteOn/Off`) intact, then
+ call `render(dst, frames)` once. `PluginInstrument` stores the offset in `addEvent(msg,
+ off)`; live/GUI events stay at 0. Bypass fade-out and the `live()` ordering (offset-0 notes
+ before live expression) keep their semantics. Built-in instruments are untouched.
+2. *Let plug-in tracks use the render pool.* A plug-in instance must not be processed by two
+ threads at once, but it may be processed by different threads in different blocks — every
+ major host does this (AU/VST3 make no same-thread guarantee for render). Make leaves whose
+ plug-ins are confined to that leaf eligible again; keep excluded the cases with real
+ cross-thread sharing (shared record queues, `midiFrom` routing, plug-in editor-driven
+ state if any is touched off the leaf). Give pool workers real-time scheduling: join the
+ output device's `os_workgroup` (macOS 11+) on each worker for the duration of a dispatch,
+ or at least set `THREAD_TIME_CONSTRAINT_POLICY` matching the period. Revisit the
+ `rtParallel_` join heuristic: plug-in work is far more variable than built-in DSP, so the
+ 1/16-smoothed single-thread estimate reacts late (dozens of late blocks) — consider
+ joining on the first late block when plug-in leaves are present.
+
+3. *Render only the buses Nota uses.* If the bus check (Open Questions) shows Kontakt with
+ many outputs enabled, enable the main output only, and further buses only when something
+ routes them. Cheap, and multiplies with (1).
+
+**Alternatives**:
+- Only (1): smallest, safest change; likely removes most of the overhead for dense MIDI, but
+ four heavy instances at 64 frames stay single-threaded — the CPU ceiling remains one core.
+- Larger internal block for plug-ins (render plug-ins at a fixed ≥128-frame block with added
+ latency): what some hosts do for "anticipative" processing, but adds latency and a big design
+ change; out of scope for this bug.
+
+**Files likely to change**:
+- `src/native/nota.engine/src/engine/Engine_Render.cpp` (`playEvents`, leaf eligibility)
+- `src/native/nota.engine/src/devices/Instrument.h` (timed-event capability)
+- `src/native/nota.engine/pluginhost/hosting/PluginInstrument.{h,cpp}` (offset-aware events)
+- `src/native/nota.engine/src/engine/AudioThreadPool.{h,cpp}`, `audio_io/macos/CoreAudioBackend.mm`
+ (workgroup / RT policy for workers)
+- `tests/Nota.SmokeTest/*` (new checks)
+
+**Tests to add or update**:
+- Engine test with a stub plug-in-like instrument that counts `render` calls and records
+ event offsets: a block with several notes → exactly one render call, offsets preserved,
+ note-off after note-on at the same offset, pedal holds still work.
+- Render-pool test: two plug-in-hosting leaves render on different workers and the mix is
+ bit-identical to the serial render.
+- Before/after benchmark (nota-pr evidence): N instances of a heavy AU/VST3 at 64 frames with
+ a dense loop, late blocks per minute and callback CPU.
+
+## Risks & Considerations
+
+- Plug-ins with thread-affinity assumptions (rare, but some older AU/VST2-era code) could
+ misbehave when rendered from pool threads; keep a per-plug-in opt-out (or a global
+ "render plug-ins on the audio thread" preference) as a safety valve.
+- Timed events change what a plug-in hears inside a block only by moving events from
+ "start of a sub-block" to their exact offset — audibly identical or better; but the
+ expression step (`kExprStep` 64-frame curves) now reaches the plug-in as CC/aftertouch
+ events with offsets rather than per-stretch values — check MPE/expression plug-ins.
+- `os_workgroup` join needs the device's workgroup re-fetched on device change; workers
+ must leave it when parked.
+- The 64-frame buffer is aggressive; even fixed, the reporter's setup may need 128 frames
+ for four Kontakt instances with heavy libraries — the benchmark will show where it lands.
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: reproduce at 128/256 frames — does it disappear?]
+- [NEEDS CLARIFICATION: does disarming the tracks change anything (rules out the
+ record/monitor path)?]
+- [NEEDS CLARIFICATION: Kontakt's own "Multiprocessor support" setting in these instances.]
+- [NEEDS CLARIFICATION: how many output buses these Kontakt 8 instances expose — run with
+ `NOTA_DEBUG_PLUGIN_BUSES=1`. If many, enable only the main bus unless a track actually
+ routes another one (a third, cheap fix).]
+- Out of scope, seen in passing: `Engine::publishRaw` appends every published graph to
+ `Engine::retired_` (`Engine.cpp:702`) and nothing erases it — memory grows with every edit
+ and every recording poll. Separate issue.
diff --git a/.specify/bugs/kontakt-cpu-dropouts/fix.md b/.specify/bugs/kontakt-cpu-dropouts/fix.md
new file mode 100644
index 00000000..0ca443a5
--- /dev/null
+++ b/.specify/bugs/kontakt-cpu-dropouts/fix.md
@@ -0,0 +1,119 @@
+# Bug Fix: high CPU and dropouts with four Kontakt instances
+
+- **Slug**: kontakt-cpu-dropouts
+- **Fixed**: 2026-11-02
+- **Assessment**: ./assessment.md
+- **Status**: partial (steps 1 and 2 applied — step 2 as workgroup join for pool workers and AUs, plug-ins still serial; step 3 follow-up; built-in Consort storm in demo21 still open)
+
+## Summary
+
+A hosted plug-in instrument is now rendered once per block, its notes, controllers and
+expression stamped with their sample offsets in the plug-in's `MidiBuffer`, instead of one
+`processBlock` per stretch between MIDI events. On the reporter's project this cuts the
+callback's tail (p99 −19 %, late 64-frame blocks 135 → 10 over three 40 s rounds). Also fixed,
+on the user's request in the same branch: replaced engine graphs were never freed.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/native/nota.engine/src/devices/Instrument.h` | modified | `takesTimedEvents()` (default false) + `eventOffset`, the offset of the event being delivered |
+| `src/native/nota.engine/src/engine/Engine_Render.cpp` | modified | `playEvents`: for a timed instrument, set `eventOffset` per event and render the block once; events on the block's end go after the render at offset 0 (as the segmented path); live expression still after the offset-0 notes. `timedEventsSelfTest()` |
+| `src/native/nota.engine/pluginhost/hosting/PluginInstrument.{h,cpp}` | modified | `takesTimedEvents() = true`; note/CC/pressure/wheel/aftertouch events go in at `eventOffset` |
+| `src/native/nota.engine/src/engine/Engine.{h,cpp}` | modified | leak: `retired_` + `liveGraph_` → `SnapshotHistory<Graph> graphHist_` (a replaced graph is freed two renders later, on the message thread); `graphRetireSelfTest()` |
+| `src/native/nota.engine/src/engine/Engine_Session.cpp` + `Engine.h` | modified | `recordSlotHold_` keeps the recording slot's `SessionPlayer` alive (the audio thread dereferences `recordSlotPlayer_`; it was only safe while graphs were never freed) |
+| `src/native/nota.engine/src/abi/nota_engine_{automation,core}.cpp`, `include/nota/nota_engine.h` | added | `nota_engine_timed_events_selftest`, `nota_engine_graph_retire_selftest` |
+| `src/managed/Nota.Infrastructure/Interop/{NativeMethods,NotaEngine}.cs` | added | bindings |
+| `tests/Nota.SmokeTest/Program.cs` | added test | both self-tests in the xrun section |
+| `CHANGELOG.md` | modified | two `Fixed` entries |
+
+## Diff Highlights
+
+```cpp
+if (timed) {
+ if (at >= frames) break; // after the render, at the next block's start (as segmented)
+ if (at > 0) liveAt0(); // live input sits after the offset-0 notes
+ inst.eventOffset = at;
+} else {
+ renderTo(at);
+}
+```
+
+## Tests Added or Updated
+
+- `nota_engine_timed_events_selftest` — a probe instrument: timed → exactly one 64-frame render,
+ events at offsets 0/10/10/20 in segmented order (off before on at a tie, live expression
+ after the offset-0 notes), the end-of-block note-off after the render at 0, `eventOffset`
+ back to 0; untimed → renders of 10/10/44 with every event at 0 (unchanged behaviour).
+- `nota_engine_graph_retire_selftest` — a published graph survives its replacement until two
+ renders have passed, then is freed at the next publish.
+
+## Local Verification
+
+- `scripts/build.sh` → engine + managed build; smoke test: 4778 PASS, 2 FAIL — both
+ `RenderPoolTests` "overloaded" checks (late blocks with render threads). They fail the same
+ way on an untouched `origin/develop` engine on this machine (75–111 late blocks), so they are
+ pre-existing / machine load, not this change. "adding and removing 48 tracks while blocks
+ render: no crash" passes with graphs now freed.
+- Bench (`/private/tmp/nota-bench-436/bench.cpp`): the four Kontakt 8 AU tracks with their saved
+ state and clips from `kontakt_problem.nota`, played through `nota_engine_render_device_block`
+ at 64 frames / 44.1 kHz (period 1.451 ms), paced like a device, 40 s per run, alternating:
+
+ | round | build | mean ms | p99 ms | p99.9 ms | late blocks |
+ |---|---|---|---|---|---|
+ | 1 | develop | 0.767 | 1.088 | 1.463 | 32 |
+ | 1 | fix | 0.697 | 0.881 | 1.029 | 0 |
+ | 2 | develop | 0.768 | 1.095 | 1.419 | 20 |
+ | 2 | fix | 0.710 | 0.896 | 1.201 | 10 |
+ | 3 | develop | 0.729 | 1.100 | 1.566 | 83 |
+ | 3 | fix | 0.705 | 0.870 | 0.957 | 0 |
+
+ One earlier 60 s pair run fix-first read 77 (fix) vs 67 (develop) late blocks — noise is real
+ at this load; the p99 drop held in every run. The mean also shows the "after a while" shape
+ from the report: ~0.59 ms in the first 10 s, ~0.77 ms after (Kontakt's voices / streaming
+ warming up), not a growth in Nota.
+- Not verified in the app with a live device; not measured with the leak fix in a long session.
+
+## Deviations from Assessment
+
+- Scope expanded on the user's request: the `Engine::retired_` leak (listed as out of scope in
+ the assessment) is fixed in the same branch, under its own approved issue #437.
+- The assessment guessed Kontakt's per-call overhead dominates; measured, the mean barely moves
+ (−3…−9 %) — the gain is in the tail (blocks with many events). Four instances still take
+ ~50 % of a 64-frame period on one thread, so remediation step 2 (plug-in tracks on the render
+ pool) is what removes the single-core ceiling.
+
+## Round 2: live test on `demo21.nota` (2026-11-03)
+
+The reporter tested the branch with a second project, `demo21.nota`, and got dropout storms. It
+has 4 built-in instrument tracks (Consort + Arp among them) plus Splice Bridge (VST3) and
+Maschine 2 (AU), with empty clips on the plug-in tracks. At 48 kHz / 64 frames the dropouts
+built up after about 10 s and lasted until Stop. The cause was found with `sample` on the
+live app's CoreAudio IO thread, then checked by muting tracks through MCP.
+
+| Finding | Evidence | Change |
+|---|---|---|
+| Splice Bridge calls JUCE `PluginHostType::getHostType()` every block. For a host JUCE doesn't know by path, that ends in `[[NSRunningApplication currentApplication] localizedName]`: a fresh object whose first property read is a synchronous LaunchServices XPC. | It took 21–52 % of the IO thread in profiles. Timed alone: median 67 µs, p99 6 ms, p99.9 31 ms. Muting the track cut dropouts from about 2600/30 s to 141/40 s. | `cacheCurrentApplication()` (PluginHost.cpp): `currentApplication` returns one retained instance, and its `localizedName` is a copy taken at plug-in host init. Other apps are untouched. Timed: median 0.08 µs. Profile: 0 LaunchServices frames. `dspLoad` 0.64 → 0.20. |
+| Maschine 2 waits inside its render for its own 9 `AudioWorker` threads, and Nota never handed AUs the device workgroup. | Probe: Maschine 2 and all Splice AUs offer `kAudioUnitProperty_RenderContextObserver`. | `CoreAudioBackend::ioWorkgroup()` (`kAudioDevicePropertyIOThreadOSWorkgroup`) → `setPluginAudioWorkgroup` → `WorkgroupLink` calls each AU's observer on the render thread when the workgroup changes. |
+| The render pool's workers were plain threads. Once `rtParallel_` joined, the callback spun in `dispatch` waiting for them: 37 % of the IO thread in one profile. | Profile of the branch bundle. | `AudioThreadPool::setWorkgroup`: workers take `THREAD_TIME_CONSTRAINT` for the buffer period and `os_workgroup_join` the device workgroup, leaving it when the device stops. The next profile had no dispatch spin. |
+| `PluginInstrument` / `PluginEffect` cleared every output channel for `maxBlock` samples each block. | About 10 % of Maschine's render in the first profile. | `storage_.clear(0, frames)`. |
+| Review P1 (Greptile): `recordSlotHold_` could free the previous `SessionPlayer` while a render still read it. | Valid. | `recordSlotHist_` (`SnapshotHistory<SessionPlayer>`) with a `RenderScope` around all of `processBlock`. Covered by `graphRetireSelfTest`. |
+
+**Not fixed here: the built-in Consort track.** With Splice fixed, the storm still built up over
+time. Muting track 4 (Consort + Arp + Delay/Chamber/Shutter/Reverb) cut it from about 500 to
+63 per 30 s, and process CPU halved. A headless render of the same project (device-block path,
+same rate and buffer) never showed it, so it needs its own issue and investigation.
+
+Tested on a bundle built with `NOTA_APP_DIR=/private/tmp/nota-branch-app scripts/bundle-mac.sh`.
+Running the app as a bare `dotnet Nota.App.dll` makes LaunchServices lookups much slower, so
+that is not a fair test of this.
+
+## Follow-ups
+
+- Step 2: let plug-in tracks render on the pool (one thread per instance per block), with the
+ pool workers joined to the device's `os_workgroup` / RT policy. Measure with the same bench.
+- Step 3: check `NOTA_DEBUG_PLUGIN_BUSES=1` for Kontakt's enabled outputs; enable only the main
+ bus unless something routes another.
+- Racks: a `PluginInstrument` inside an Instrument Rack chain is still driven by the rack in
+ segments — the rack could pass timed events through too.
+- Pre-existing flaky `RenderPoolTests` overload checks on this Mac.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7868cc7..e837817b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -182,6 +182,24 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
returns, then the master.
### Fixed
+- **Plug-in instruments use less CPU on busy MIDI** (#436): a hosted instrument (Kontakt,
+ Serum, any AU or VST3) is now processed once per audio block, with every note and controller
+ placed at its exact sample inside the block. Before, the block was cut at every MIDI event and
+ the plug-in was called once per piece — with dense, short notes several times a block, at
+ sizes down to a single sample — so a few heavy instances could run out of time and drop out.
+ Timing is unchanged: events still land on their own sample.
+- **Fewer dropouts with plug-ins on macOS** (#436):
+ - Some JUCE-built plug-ins (Splice Bridge among them) ask the host for its name on every audio
+ block, and for Nota that question went to a macOS system service, taking up to tens of
+ milliseconds now and then. Nota now answers it from a copy taken at startup.
+ - Audio Units that render on threads of their own (Maschine 2, Splice and others that ask)
+ now get the audio device's real-time workgroup, and so do Nota's own render threads, so
+ macOS schedules them against the audio deadline.
+ - A hosted plug-in's buffers are cleared only for the current block, not for their full
+ maximum size on every output.
+- **Memory no longer grows with every edit** (#437): the engine kept every past version of the
+ project's graph for the whole session. Replaced versions are now freed as soon as audio
+ can no longer be reading them (the undo history still keeps the ones it needs).
- **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.
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index 3aabd6f4..da451464 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -292,6 +292,12 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_xrun_selftest")]
internal static partial int XrunSelfTest(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_graph_retire_selftest")]
+ internal static partial int GraphRetireSelfTest(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_timed_events_selftest")]
+ internal static partial int TimedEventsSelfTest(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_cpu_load")]
internal static partial float CpuLoad(IntPtr engine);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index 1ecf3814..2784e275 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -309,6 +309,16 @@ public sealed partial class NotaEngine : IAudioEngine
public bool XrunSelfTest()
{ ThrowIfDisposed(); return NativeMethods.XrunSelfTest(_handle) != 0; }
+ /// <summary>Device-free self-test: a replaced engine graph is freed two renders later,
+ /// not kept for the whole session.</summary>
+ public bool GraphRetireSelfTest()
+ { ThrowIfDisposed(); return NativeMethods.GraphRetireSelfTest(_handle) != 0; }
+
+ /// <summary>Device-free self-test (#436): a hosted plug-in instrument renders once per block,
+ /// every event at its sample offset; a built-in still renders between events.</summary>
+ public bool TimedEventsSelfTest()
+ { ThrowIfDisposed(); return NativeMethods.TimedEventsSelfTest(_handle) != 0; }
+
/// <summary>Smoothed real-time DSP load, 0..1 (render time / block budget).</summary>
public float CpuLoad
{ get { ThrowIfDisposed(); return NativeMethods.CpuLoad(_handle); } }
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 0a7f14c5..5e9c4f3e 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -343,6 +343,9 @@ NOTA_API int32_t nota_engine_preview_cached_at(NotaEngine* engine, const char
* this each tick and surfaces a non-fatal message; playback never stops. */
NOTA_API int32_t nota_engine_xrun_count(const NotaEngine* engine);
NOTA_API int32_t nota_engine_xrun_selftest(NotaEngine* engine);
+/* Device-free: a replaced engine graph is freed once two renders have finished after it
+ * (engine stopped). */
+NOTA_API int32_t nota_engine_graph_retire_selftest(NotaEngine* engine);
/* ---- parameter automation (M9) ------------------------------------------
* Lanes are structural data on the track (snapshot + undo/redo, M6-6). A lane
@@ -362,6 +365,10 @@ NOTA_API int32_t nota_engine_rack_device_selftest(NotaEngine* engine);
/* Drum Rack: device-free check that notes route only to the matching pad chain
* and the pad note survives the blob round-trip. */
NOTA_API int32_t nota_engine_drum_rack_selftest(NotaEngine* engine);
+/* Hosted plug-in instruments (#436): device-free check that an instrument taking timed
+ * events renders once per block with every event at its sample offset, while a built-in
+ * still renders in segments between events. */
+NOTA_API int32_t nota_engine_timed_events_selftest(NotaEngine* engine);
/* Plugin-parameter automation (M9-B, target 3). Device-free structural self-test;
* the plugin-param introspection + lane-add C ABI arrives in B2. */
NOTA_API int32_t nota_engine_plugin_automation_selftest(NotaEngine* engine);
diff --git a/src/native/nota.engine/pluginhost/bridge/PluginHostBridge.h b/src/native/nota.engine/pluginhost/bridge/PluginHostBridge.h
index 5000f32b..e12a2200 100644
--- a/src/native/nota.engine/pluginhost/bridge/PluginHostBridge.h
+++ b/src/native/nota.engine/pluginhost/bridge/PluginHostBridge.h
@@ -28,4 +28,10 @@ std::shared_ptr<Instrument> createPluginInstrument(int32_t catalogIndex, double
// null on failure.
std::shared_ptr<Device> createPluginEffect(int32_t catalogIndex, double sampleRate, int32_t maxBlock);
+// The audio device's IO-thread workgroup (an os_workgroup_t on macOS 11+, null for none),
+// handed to hosted plug-ins that run real-time threads of their own: they join it so the OS
+// schedules those threads against the device's deadline. Set after the device starts, cleared
+// before it stops. Any thread; a no-op off macOS.
+void setPluginAudioWorkgroup(void* osWorkgroup);
+
} // namespace nota
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginCommon.h b/src/native/nota.engine/pluginhost/hosting/PluginCommon.h
index e2b2aa30..e0770c71 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginCommon.h
+++ b/src/native/nota.engine/pluginhost/hosting/PluginCommon.h
@@ -46,6 +46,24 @@ void enableEveryBus(juce::AudioPluginInstance& p);
// Bus layout on stderr when NOTA_DEBUG_PLUGIN_BUSES is set. Message thread.
void logBuses(const juce::AudioPluginInstance& p);
+// Hands the device workgroup (setPluginAudioWorkgroup) to one Audio Unit through its render
+// context observer (kAudioUnitProperty_RenderContextObserver, macOS 12+), the way Logic does:
+// on the render thread, before processing, whenever the workgroup changed. A plug-in without
+// an observer (VST3, an AU that doesn't ask) is left alone.
+class WorkgroupLink {
+ public:
+ WorkgroupLink() = default;
+ WorkgroupLink(const WorkgroupLink&) = delete;
+ WorkgroupLink& operator=(const WorkgroupLink&) = delete;
+ ~WorkgroupLink();
+ void bind(juce::AudioPluginInstance& p); // message thread, after prepareToPlay
+ void update(); // audio thread, right before processBlock
+
+ private:
+ void* observer_ = nullptr; // the AU's AURenderContextObserver block (copied)
+ uint32_t seen_ = 0; // generation of the workgroup last handed over
+};
+
// Opaque plugin state <-> byte vector (M3-5).
std::vector<uint8_t> readState(juce::AudioPluginInstance* p);
void writeState(juce::AudioPluginInstance* p, const uint8_t* data, int32_t size);
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp b/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp
index 24b3ad98..bd7e1a9f 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp
+++ b/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp
@@ -66,6 +66,7 @@ void PluginEffect::setSampleRate(double sr, int32_t maxBlock) {
scNumChans_ = plugin_->getBus(true, 1)->getNumberOfChannels();
}
plugin_->setPlayHead(&playHead_); // DAW transport sync
+ workgroup_.bind(*plugin_);
}
int32_t PluginEffect::latencySamples() const {
@@ -75,7 +76,7 @@ int32_t PluginEffect::latencySamples() const {
void PluginEffect::process(float* buf, int32_t frames) {
if (frames <= 0 || frames > maxBlock_ || plugin_ == nullptr) return;
const int nc = juce::jmin(storage_.getNumChannels(), kMaxChans);
- storage_.clear();
+ storage_.clear(0, frames); // only what this block uses: a multi-out plug-in has many channels
float* l = storage_.getWritePointer(0);
float* r = stereoIn_ ? storage_.getWritePointer(1) : spare_.data(); // mono main: drop R
simd_audio::deinterleaveStereo(l, r, buf, frames);
@@ -102,6 +103,7 @@ void PluginEffect::process(float* buf, int32_t frames) {
juce::AudioBuffer<float> block(
ptrs, pluginChannelPtrs(*plugin_, storage_, spare_.data(), frames, chanFloor_, ptrs), frames);
empty_.clear();
+ workgroup_.update();
plugin_->processBlock(block, empty_);
const float* ol = block.getReadPointer(0);
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginEffect.h b/src/native/nota.engine/pluginhost/hosting/PluginEffect.h
index 078c746b..b4020fb7 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginEffect.h
+++ b/src/native/nota.engine/pluginhost/hosting/PluginEffect.h
@@ -94,6 +94,7 @@ class PluginEffect : public nota::Device, private juce::AudioProcessorListener {
std::vector<float> spare_; // the channels past storage_ (see pluginChannelPtrs)
int chanFloor_ = 0; // pluginChannelPtrs floor (see minProcessChannels)
juce::MidiBuffer empty_;
+ WorkgroupLink workgroup_; // the device workgroup for the plug-in's own threads (#436)
int maxBlock_ = 0;
bool stereoIn_ = true, stereoOut_ = true; // main buses have a channel 1 (see setSampleRate)
EditorHost editor_; // declared last: destroyed before plugin_
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginHost.cpp b/src/native/nota.engine/pluginhost/hosting/PluginHost.cpp
index 227d1493..c832db15 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginHost.cpp
+++ b/src/native/nota.engine/pluginhost/hosting/PluginHost.cpp
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// PluginHost implementation — module lifetime, test window, Linux pump and
-// catalog factories. The scan
+// PluginHost implementation — module lifetime, test window, Linux pump, catalog
+// factories and the device workgroup hand-off. The scan
// section now lives in scanner/abi_pluginscanner.cpp and the adapters in
// PluginInstrument.cpp / PluginEffect.cpp.
@@ -16,7 +16,19 @@
#include <juce_audio_processors/juce_audio_processors.h>
#include <juce_gui_basics/juce_gui_basics.h>
+#include <algorithm>
+#include <atomic>
#include <memory>
+#include <mutex>
+#include <vector>
+
+#if JUCE_MAC
+#import <AppKit/AppKit.h>
+#include <AudioToolbox/AudioToolbox.h>
+#include <Block.h>
+#include <objc/runtime.h>
+#include <os/workgroup.h>
+#endif
namespace {
@@ -42,8 +54,41 @@ class SpikeWindow : public juce::DocumentWindow {
juce::ScopedJuceInitialiser_GUI* g_juceGui = nullptr;
std::unique_ptr<SpikeWindow> g_window;
+#if JUCE_MAC
+// JUCE plug-ins identify their host with PluginHostType::getHostType(). For a host it doesn't
+// know by path — Nota — that ends in [[NSRunningApplication currentApplication] localizedName]:
+// a fresh object whose first property read is a synchronous LaunchServices round trip
+// (measured: median 67 us, p99 6 ms, p99.9 31 ms). Some plug-ins ask on the audio thread every
+// block (Splice Bridge does), and those tails are dropouts at any small buffer (#436). So
+// currentApplication returns one instance, and its name is a copy taken here, once (median
+// 0.08 us); a long-lived instance alone still re-fetches its "dynamic" properties now and then.
+// Every other application is untouched.
+void cacheCurrentApplication() {
+ static std::once_flag once;
+ std::call_once(once, [] {
+ Class cls = [NSRunningApplication class];
+ Method current = class_getClassMethod(cls, @selector(currentApplication));
+ Method name = class_getInstanceMethod(cls, @selector(localizedName));
+ if (current == nullptr || name == nullptr) return;
+ using CurrentFn = NSRunningApplication* (*)(id, SEL);
+ using NameFn = NSString* (*)(id, SEL);
+ const auto originalCurrent = (CurrentFn)method_getImplementation(current);
+ static const auto originalName = (NameFn)method_getImplementation(name);
+ static NSRunningApplication* own = [originalCurrent(cls, @selector(currentApplication)) retain];
+ static NSString* ownName = [originalName(own, @selector(localizedName)) copy];
+ method_setImplementation(current, imp_implementationWithBlock(^NSRunningApplication*(id) { return own; }));
+ method_setImplementation(name, imp_implementationWithBlock(^NSString*(NSRunningApplication* app) {
+ return app == own ? ownName : originalName(app, @selector(localizedName));
+ }));
+ });
+}
+#endif
+
void ensureJuceGui() {
if (g_juceGui == nullptr) g_juceGui = new juce::ScopedJuceInitialiser_GUI();
+#if JUCE_MAC
+ cacheCurrentApplication(); // before any plug-in is created
+#endif
}
} // namespace
@@ -106,4 +151,83 @@ std::shared_ptr<Device> createPluginEffect(int32_t catalogIndex, double sr, int3
return std::make_shared<hosting::PluginEffect>(std::move(inst), sr, maxBlock);
}
+// ---- Device workgroup hand-off (#436) ---------------------------------------
+// A plug-in like Maschine renders on worker threads of its own and waits for them inside its
+// render call. Outside the device's workgroup the OS schedules those threads without the
+// deadline and, under sustained load, demotes them: dropouts that keep coming until the
+// transport stops. The current workgroup and a generation the render threads compare against.
+
+namespace {
+std::atomic<void*> gWorkgroup{nullptr};
+std::atomic<uint32_t> gWorkgroupGen{1}; // a link starts at 0, so its first render hands over
+} // namespace
+
+void setPluginAudioWorkgroup(void* osWorkgroup) {
+#if JUCE_MAC
+ if (osWorkgroup != nullptr) {
+ // Plug-in threads may still be joined to a workgroup after the device that owned it
+ // closed, so every one handed out stays retained (one per device start, never many).
+ static std::mutex mx;
+ static std::vector<void*> kept;
+ const std::lock_guard<std::mutex> lock(mx);
+ if (std::find(kept.begin(), kept.end(), osWorkgroup) == kept.end()) {
+ if (@available(macOS 11.0, *)) os_retain(static_cast<os_workgroup_t>(osWorkgroup));
+ kept.push_back(osWorkgroup);
+ }
+ }
+ gWorkgroup.store(osWorkgroup, std::memory_order_release);
+ gWorkgroupGen.fetch_add(1, std::memory_order_release);
+#else
+ (void)osWorkgroup;
+#endif
+}
+
+namespace hosting {
+
+WorkgroupLink::~WorkgroupLink() {
+#if JUCE_MAC
+ if (observer_) Block_release(observer_);
+#endif
+}
+
+void WorkgroupLink::bind(juce::AudioPluginInstance& p) {
+#if JUCE_MAC
+ if (observer_) {
+ Block_release(observer_);
+ observer_ = nullptr;
+ }
+ seen_ = 0;
+ const auto* client = p.getAudioUnitClient();
+ if (client == nullptr) return; // not an Audio Unit
+ if (@available(macOS 12.0, *)) {
+ AudioUnit au = client->getAudioUnitHandle();
+ if (au == nullptr) return;
+ AURenderContextObserver obs = nullptr;
+ UInt32 size = sizeof(obs);
+ if (AudioUnitGetProperty(au, kAudioUnitProperty_RenderContextObserver, kAudioUnitScope_Global, 0, &obs,
+ &size) == noErr &&
+ obs != nullptr)
+ observer_ = (void*)Block_copy(obs); // a block pointer kept untyped in the header
+ }
+#else
+ (void)p;
+#endif
+}
+
+void WorkgroupLink::update() {
+#if JUCE_MAC
+ if (observer_ == nullptr) return;
+ const uint32_t gen = gWorkgroupGen.load(std::memory_order_acquire);
+ if (gen == seen_) return;
+ seen_ = gen;
+ if (@available(macOS 12.0, *)) {
+ AudioUnitRenderContext ctx{};
+ ctx.workgroup = static_cast<os_workgroup_t>(gWorkgroup.load(std::memory_order_acquire));
+ ((AURenderContextObserver)observer_)(&ctx);
+ }
+#endif
+}
+
+} // namespace hosting
+
} // namespace nota
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
index ffbdb37a..0f32d8a1 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
+++ b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
@@ -35,29 +35,29 @@ void PluginInstrument::setSampleRate(double sr) {
}
void PluginInstrument::noteOn(int32_t pitch, float velocity) {
- pending_.addEvent(juce::MidiMessage::noteOn(1, pitch, (float)velocity), 0);
+ pending_.addEvent(juce::MidiMessage::noteOn(1, pitch, (float)velocity), eventOffset);
}
void PluginInstrument::noteOff(int32_t pitch) {
- pending_.addEvent(juce::MidiMessage::noteOff(1, pitch), 0);
+ pending_.addEvent(juce::MidiMessage::noteOff(1, pitch), eventOffset);
}
void PluginInstrument::allNotesOff() {
- pending_.addEvent(juce::MidiMessage::allNotesOff(1), 0);
+ pending_.addEvent(juce::MidiMessage::allNotesOff(1), eventOffset);
}
void PluginInstrument::noteExpression(int32_t pitch, int32_t dim, float value) {
- if (pitch >= 0 && dim == 1) pending_.addEvent(juce::MidiMessage::aftertouchChange(1, pitch, u7(value)), 0);
+ if (pitch >= 0 && dim == 1) pending_.addEvent(juce::MidiMessage::aftertouchChange(1, pitch, u7(value)), eventOffset);
}
void PluginInstrument::controller(int32_t ctl, float value) {
if (ctl == nota::kCtlPitchWheel)
pending_.addEvent(
- juce::MidiMessage::pitchWheel(1, juce::jlimit(0, 16383, (int)std::lround((value + 1.0f) * 8191.5f))), 0);
+ juce::MidiMessage::pitchWheel(1, juce::jlimit(0, 16383, (int)std::lround((value + 1.0f) * 8191.5f))), eventOffset);
else if (ctl == nota::kCtlChannelPressure)
- pending_.addEvent(juce::MidiMessage::channelPressureChange(1, u7(value)), 0);
+ pending_.addEvent(juce::MidiMessage::channelPressureChange(1, u7(value)), eventOffset);
else if (ctl >= 0 && ctl < 128)
- pending_.addEvent(juce::MidiMessage::controllerEvent(1, ctl, u7(value)), 0);
+ pending_.addEvent(juce::MidiMessage::controllerEvent(1, ctl, u7(value)), eventOffset);
}
void PluginInstrument::render(float* out, int32_t frames) {
@@ -67,10 +67,11 @@ void PluginInstrument::render(float* out, int32_t frames) {
for (GuiNote g; guiNotes_.pop(g);)
pending_.addEvent(
g.on ? juce::MidiMessage::noteOn(1, g.pitch, g.velocity) : juce::MidiMessage::noteOff(1, g.pitch), 0);
- storage_.clear();
+ storage_.clear(0, frames); // only what this block uses: a multi-out plug-in has many channels
float* ptrs[kMaxChans];
juce::AudioBuffer<float> block(
ptrs, pluginChannelPtrs(*plugin_, storage_, spare_.data(), frames, chanFloor_, ptrs), frames);
+ workgroup_.update();
plugin_->processBlock(block, pending_);
pending_.clear();
const float* l = block.getReadPointer(0);
@@ -171,6 +172,7 @@ void PluginInstrument::prepare(double sr) {
plugin_->setRateAndBufferSizeDetails(sr, maxBlock_);
plugin_->prepareToPlay(sr, maxBlock_);
plugin_->setPlayHead(&playHead_); // DAW transport sync
+ workgroup_.bind(*plugin_);
// In and out share the buffer, so it spans the wider side.
storage_.setSize(
juce::jmax(2, plugin_->getTotalNumInputChannels(), plugin_->getTotalNumOutputChannels()), maxBlock_);
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
index e8ede033..9110e61a 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
+++ b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
@@ -32,6 +32,7 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
const char* displayName() const override { return name_.empty() ? "Plugin" : name_.c_str(); }
bool handlesSustain() const override { return true; } // the plug-in gets CC64 itself
+ bool takesTimedEvents() const override { return true; } // one processBlock per block (#436)
void setSampleRate(double sr) override;
@@ -92,6 +93,7 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
std::vector<float> spare_; // the channels past storage_ (see pluginChannelPtrs)
int chanFloor_ = 0; // pluginChannelPtrs floor (see minProcessChannels)
juce::MidiBuffer pending_;
+ WorkgroupLink workgroup_; // the device workgroup for the plug-in's own threads (#436)
int maxBlock_;
bool stereoOut_ = true; // main output bus has a channel 1 (see prepare)
std::string name_; // cached plugin name for displayName()
diff --git a/src/native/nota.engine/src/abi/nota_engine_automation.cpp b/src/native/nota.engine/src/abi/nota_engine_automation.cpp
index bafd0094..8aee0b8d 100644
--- a/src/native/nota.engine/src/abi/nota_engine_automation.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_automation.cpp
@@ -26,6 +26,9 @@ int32_t nota_engine_rack_selftest(NotaEngine* e) {
int32_t nota_engine_rack_device_selftest(NotaEngine* e) {
return (e && ENG(e)->rackDeviceSelfTest()) ? 1 : 0;
}
+int32_t nota_engine_timed_events_selftest(NotaEngine* e) {
+ return (e && ENG(e)->timedEventsSelfTest()) ? 1 : 0;
+}
int32_t nota_engine_drum_rack_selftest(NotaEngine* e) {
return (e && ENG(e)->drumRackSelfTest()) ? 1 : 0;
}
diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cpp
index 4b68e66f..58c8db02 100644
--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp
@@ -128,6 +128,9 @@ int32_t nota_engine_xrun_count(const NotaEngine* e) {
int32_t nota_engine_xrun_selftest(NotaEngine* e) {
return (e && ENG(e)->xrunSelfTest()) ? 1 : 0;
}
+int32_t nota_engine_graph_retire_selftest(NotaEngine* e) {
+ return (e && ENG(e)->graphRetireSelfTest()) ? 1 : 0;
+}
float nota_engine_cpu_load(const NotaEngine* e) {
return e ? CENG(e)->cpuLoad() : 0.0f;
}
diff --git a/src/native/nota.engine/src/audio_io/AudioBackend.h b/src/native/nota.engine/src/audio_io/AudioBackend.h
index b04eda8c..a036a62f 100644
--- a/src/native/nota.engine/src/audio_io/AudioBackend.h
+++ b/src/native/nota.engine/src/audio_io/AudioBackend.h
@@ -99,6 +99,11 @@ class AudioBackend {
// True if the last start() asked for a sample rate the device refused and kept its own.
virtual bool sampleRateRefused() const { return false; }
+ // The device's IO-thread workgroup (macOS 11+: an os_workgroup_t, valid until stop()), or
+ // null. Plug-ins that run real-time threads of their own join it, so the OS schedules them
+ // against the device's deadline. Read after start() succeeds.
+ virtual void* ioWorkgroup() const { return nullptr; }
+
// After a reset-requested event: the rate the user picked in the device's own settings
// (0 = unchanged). The engine then stops requesting its saved rate, so a reopen keeps it.
virtual double deviceChangedRate() const { return 0.0; }
diff --git a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h
index 00c43f84..1bdf1f6b 100644
--- a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h
+++ b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.h
@@ -23,6 +23,7 @@ class CoreAudioBackend final : public AudioBackend {
int32_t bufferFrames() const override { return bufferFrames_; }
void setXrunCallback(std::function<void()> cb) override { onXrun_ = std::move(cb); }
bool isRunning() const override { return running_; }
+ void* ioWorkgroup() const override;
// Opaque to callers; public so the file-local CoreAudio callback can reach it.
struct Impl;
diff --git a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm
index 01900567..7c5e199f 100644
--- a/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm
+++ b/src/native/nota.engine/src/audio_io/macos/CoreAudioBackend.mm
@@ -7,6 +7,7 @@
#import <AudioToolbox/AudioToolbox.h>
#import <CoreAudio/CoreAudio.h>
+#include <os/workgroup.h>
#include <vector>
@@ -16,6 +17,7 @@ struct CoreAudioBackend::Impl {
AudioUnit outputUnit = nullptr;
RenderCallback render; // copied from the backend on start()
AudioDeviceID device = kAudioObjectUnknown; // for the overload listener (M7-8)
+ void* workgroup = nullptr; // os_workgroup_t of the device's IO thread (retained)
};
// CoreAudio fires this (off the RT thread) when the device drops a buffer /
@@ -215,6 +217,17 @@ bool CoreAudioBackend::start(RenderCallback render, const BackendConfig& cfg) {
return false;
}
+ // The IO thread's workgroup, for plug-ins with real-time threads of their own (#436).
+ if (@available(macOS 11.0, *)) {
+ if (dev != kAudioObjectUnknown) {
+ AudioObjectPropertyAddress a{kAudioDevicePropertyIOThreadOSWorkgroup, kAudioObjectPropertyScopeGlobal,
+ kAudioObjectPropertyElementMain};
+ os_workgroup_t wg = nullptr;
+ UInt32 sz = sizeof(wg);
+ if (AudioObjectGetPropertyData(dev, &a, 0, nullptr, &sz, &wg) == noErr && wg) impl_->workgroup = wg;
+ }
+ }
+
running_ = true;
return true;
}
@@ -230,9 +243,17 @@ void CoreAudioBackend::stop() {
AudioComponentInstanceDispose(impl_->outputUnit);
impl_->outputUnit = nullptr;
}
+ if (impl_->workgroup) { // the IO thread is gone with the unit
+ if (@available(macOS 11.0, *)) os_release(static_cast<os_workgroup_t>(impl_->workgroup));
+ impl_->workgroup = nullptr;
+ }
running_ = false;
}
+void* CoreAudioBackend::ioWorkgroup() const {
+ return impl_->workgroup;
+}
+
} // namespace nota
#endif // defined(__APPLE__)
diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.h
index 03d56f5a..f0252097 100644
--- a/src/native/nota.engine/src/devices/Instrument.h
+++ b/src/native/nota.engine/src/devices/Instrument.h
@@ -46,7 +46,15 @@ class Instrument {
bool /*playing*/) {}
virtual void midiTimeJump(double /*deltaBeats*/) {}
- // Note events (applied at segment boundaries by the engine for sample accuracy).
+ // A hosted plug-in places events inside a block itself (its MIDI buffer is sample-accurate)
+ // and pays a fixed cost per render call, so the engine renders it once per block instead of
+ // in segments between events (#436): before each event it sets eventOffset to the event's
+ // sample offset within the next render(). Outside that it stays 0. Audio thread only.
+ virtual bool takesTimedEvents() const { return false; }
+ int32_t eventOffset = 0;
+
+ // Note events (applied at segment boundaries by the engine for sample accuracy, or at
+ // eventOffset — see takesTimedEvents).
virtual void noteOn(int32_t pitch, float velocity) = 0;
virtual void noteOff(int32_t pitch) = 0;
virtual void allNotesOff() = 0;
diff --git a/src/native/nota.engine/src/engine/AudioThreadPool.cpp b/src/native/nota.engine/src/engine/AudioThreadPool.cpp
index 26425847..dc7cbb78 100644
--- a/src/native/nota.engine/src/engine/AudioThreadPool.cpp
+++ b/src/native/nota.engine/src/engine/AudioThreadPool.cpp
@@ -23,8 +23,14 @@
#include <windows.h>
#elif defined(__APPLE__)
#include <mach/mach.h>
+#include <mach/mach_time.h>
+#include <mach/thread_policy.h>
+#include <os/workgroup.h>
#include <pthread.h>
#include <sys/sysctl.h>
+
+#include <mutex>
+#include <vector>
#else
#include <pthread.h>
#include <time.h>
@@ -96,6 +102,70 @@ void AudioThreadPool::park(uint64_t seen) {
sleepers_.fetch_sub(1, std::memory_order_relaxed);
}
+void AudioThreadPool::setWorkgroup(void* osWorkgroup, double periodNs) {
+#if defined(__APPLE__)
+ if (osWorkgroup != nullptr) {
+ // Workers leave the old workgroup only when they next wake, so every one handed in
+ // stays retained (one per device start).
+ static std::mutex mx;
+ static std::vector<void*> kept;
+ const std::lock_guard<std::mutex> lock(mx);
+ if (std::find(kept.begin(), kept.end(), osWorkgroup) == kept.end()) {
+ if (__builtin_available(macOS 11.0, *)) os_retain(static_cast<os_workgroup_t>(osWorkgroup));
+ kept.push_back(osWorkgroup);
+ }
+ }
+ workgroupPeriodNs_.store(periodNs, std::memory_order_relaxed);
+ workgroup_.store(osWorkgroup, std::memory_order_relaxed);
+ workgroupGen_.fetch_add(1, std::memory_order_release);
+ // Parked workers follow on their next job; nothing to wake them for.
+#else
+ (void)osWorkgroup;
+ (void)periodNs;
+#endif
+}
+
+// Worker thread: catch up with setWorkgroup. `joined` is the workgroup this thread is in
+// (null for none) and `token` its join token (os_workgroup_join_token_s storage).
+void AudioThreadPool::followWorkgroup(uint32_t& seenGen, void*& joined, void* token) {
+#if defined(__APPLE__)
+ const uint32_t gen = workgroupGen_.load(std::memory_order_acquire);
+ if (gen == seenGen) return;
+ seenGen = gen;
+ if (__builtin_available(macOS 11.0, *)) {
+ auto* tok = static_cast<os_workgroup_join_token_s*>(token);
+ if (joined) {
+ os_workgroup_leave(static_cast<os_workgroup_t>(joined), tok);
+ joined = nullptr;
+ }
+ void* wg = workgroup_.load(std::memory_order_relaxed);
+ const double periodNs = workgroupPeriodNs_.load(std::memory_order_relaxed);
+ if (wg == nullptr || !(periodNs > 0.0)) { // no device: back to an ordinary thread
+ thread_standard_policy_data_t std{};
+ thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_STANDARD_POLICY, (thread_policy_t)&std,
+ THREAD_STANDARD_POLICY_COUNT);
+ return;
+ }
+ // A real-time thread for the device's period first: an audio workgroup takes those.
+ mach_timebase_info_data_t tb;
+ mach_timebase_info(&tb);
+ const double toAbs = (double)tb.denom / (double)tb.numer;
+ thread_time_constraint_policy_data_t pol;
+ pol.period = (uint32_t)(periodNs * toAbs);
+ pol.computation = (uint32_t)(periodNs * 0.5 * toAbs);
+ pol.constraint = (uint32_t)(periodNs * toAbs);
+ pol.preemptible = 1;
+ thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY,
+ (thread_policy_t)&pol, THREAD_TIME_CONSTRAINT_POLICY_COUNT);
+ if (os_workgroup_join(static_cast<os_workgroup_t>(wg), tok) == 0) joined = wg;
+ }
+#else
+ (void)seenGen;
+ (void)joined;
+ (void)token;
+#endif
+}
+
void AudioThreadPool::workerLoop(int id) {
// Pause-spins before parking, plus the linger dispatch() picked from the
// gap between jobs. With a live device the next job is a buffer period
@@ -107,6 +177,24 @@ void AudioThreadPool::workerLoop(int id) {
uint64_t seen = 0;
int spins = 0;
Clock::time_point idleSince{};
+ uint32_t wgSeen = 0;
+ void* wgJoined = nullptr;
+#if defined(__APPLE__)
+ os_workgroup_join_token_s wgToken{};
+#else
+ int wgToken = 0;
+#endif
+ struct LeaveOnExit { // a joined thread must leave before it ends
+ void*& wg;
+ void* token;
+ ~LeaveOnExit() {
+#if defined(__APPLE__)
+ if (wg)
+ if (__builtin_available(macOS 11.0, *))
+ os_workgroup_leave(static_cast<os_workgroup_t>(wg), static_cast<os_workgroup_join_token_s*>(token));
+#endif
+ }
+ } leaveOnExit{wgJoined, &wgToken};
for (;;) {
const uint64_t e = epoch_.load(std::memory_order_acquire);
if (e == seen) { // idle: brief pause-spin, then park on the futex word
@@ -127,6 +215,7 @@ void AudioThreadPool::workerLoop(int id) {
}
seen = e;
if (stop_.load(std::memory_order_relaxed)) return;
+ followWorkgroup(wgSeen, wgJoined, &wgToken); // one relaxed load unless the device changed
// Same check-then-CAS claim loop as the caller (see header
// comment): overshoot probes never consume, so a lagging probe
// can never eat the next job's head tickets.
diff --git a/src/native/nota.engine/src/engine/AudioThreadPool.h b/src/native/nota.engine/src/engine/AudioThreadPool.h
index 6c691424..0bd0c979 100644
--- a/src/native/nota.engine/src/engine/AudioThreadPool.h
+++ b/src/native/nota.engine/src/engine/AudioThreadPool.h
@@ -72,6 +72,13 @@ class AudioThreadPool {
// Dedicated threads (excludes the caller-helper slot).
int workerCount() const noexcept { return (int)workers_.size(); }
+ // The audio device's IO workgroup (an os_workgroup_t, macOS 11+) and its buffer period.
+ // Each worker, the next time it wakes, becomes a real-time thread for that period and
+ // joins the workgroup, so the OS schedules it against the device's deadline instead of
+ // as a background thread the callback then spins waiting for (#436). Null leaves it
+ // (offline renders have no deadline). Message thread; a no-op off macOS.
+ void setWorkgroup(void* osWorkgroup, double periodNs);
+
// Caller thread: whether the next job follows the previous one back-to-back
// (an offline render: no deadline, finish fast) rather than a buffer period
// later (a device callback: finish in time, spend little CPU).
@@ -205,6 +212,10 @@ class AudioThreadPool {
#endif
std::atomic<WakeWord> wake_{0};
std::atomic<int64_t> lingerNs_{0}; // set per dispatch (see dispatch())
+ std::atomic<void*> workgroup_{nullptr}; // see setWorkgroup
+ std::atomic<double> workgroupPeriodNs_{0.0};
+ std::atomic<uint32_t> workgroupGen_{0};
+ void followWorkgroup(uint32_t& seenGen, void*& joined, void* token); // worker thread
JobSlot slots_[kSlots]; // gen-indexed descriptors (see header comment)
uint64_t doneBase_ = 0; // caller-thread only (single audio thread)
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index f87921bb..d97ec1ab 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -38,8 +38,7 @@ Engine::Engine()
for (auto& s : routeSlotPart_) s.store(0, std::memory_order_relaxed);
silentKey_.assign(kMaxBlock * 2, 0.0f); // the key of a part that is gone (specs/050)
ensureRenderScratch(authoring_->tracks.size());
- liveGraph_.store(authoring_.get(), std::memory_order_release);
- retired_.push_back(authoring_);
+ graphHist_.publish(authoring_);
installRackPluginFactory(); // lets rack blobs rebuild hosted-plugin children on load
}
@@ -113,6 +112,13 @@ bool Engine::start() {
reconfigureAllWarpStreams(); // warp transpose + window sizes depend on the device SR
recomputePdc(); // latencies are known once plugins are prepared
}
+ // Plug-ins with real-time threads of their own, and the render pool, join the device's IO
+ // workgroup (#436).
+ void* const wg = ok ? backend_->ioWorkgroup() : nullptr;
+ setPluginAudioWorkgroup(wg);
+ const int32_t bf = ok ? backend_->bufferFrames() : 0;
+ if (pool_)
+ pool_->setWorkgroup(wg, wg && bf > 0 && backend_->sampleRate() > 0 ? 1e9 * bf / backend_->sampleRate() : 0.0);
renderSuspended_.store(false, std::memory_order_release);
if (ok) openMidiInput();
return ok;
@@ -193,6 +199,8 @@ int32_t Engine::gamepadAxisValues(int32_t pad, int32_t* out, int32_t max) const
void Engine::stop() {
if (midiInput_) midiInput_->close();
+ setPluginAudioWorkgroup(nullptr); // before the device (and its workgroup) goes
+ if (pool_) pool_->setWorkgroup(nullptr, 0.0);
if (backend_) backend_->stop();
}
@@ -441,6 +449,29 @@ bool Engine::xrunSelfTest() {
return xrunCount() == before + 1;
}
+// A replaced graph is freed once two renders have finished after it — not kept for the
+// session, and not before a render that may still be walking it is done.
+bool Engine::graphRetireSelfTest() {
+ if (isRunning() || !authoring_) return false;
+ std::vector<float> buf(64 * 2);
+ auto first = std::make_shared<Graph>(*authoring_); // a copy: no undo entry holds it
+ const std::weak_ptr<Graph> held = first;
+ publishRaw(std::move(first));
+ publishRaw(std::make_shared<Graph>(*authoring_)); // replaced, but no render has passed yet
+ // A recording slot's player outlives its track the same way (#438 review): the next take
+ // retires it, and a render that read the old pointer finishes before it goes.
+ auto player = std::make_shared<SessionPlayer>();
+ const std::weak_ptr<SessionPlayer> heldPlayer = player;
+ recordSlotHist_.publish(std::move(player)); // its track is gone: the history is the last owner
+ recordSlotHist_.publish(std::make_shared<SessionPlayer>());
+ if (held.expired() || heldPlayer.expired()) return false;
+ renderOffline(buf.data(), 64);
+ renderOffline(buf.data(), 64);
+ publishRaw(std::make_shared<Graph>(*authoring_)); // frees what the two renders moved past
+ recordSlotHist_.publish(std::make_shared<SessionPlayer>());
+ return held.expired() && heldPlayer.expired();
+}
+
bool Engine::previewSelfTest() {
// Synthetic 0.1 s stereo tone, previewed and rendered offline (no device).
auto buf = std::make_shared<SampleBuffer>();
@@ -699,7 +730,6 @@ void Engine::publishRaw(std::shared_ptr<Graph> g) {
for (auto& t : g->tracks)
if (static_cast<int32_t>(t->sessionSlots.size()) < g->sceneCount) t->sessionSlots.resize(g->sceneCount);
authoring_ = g;
- retired_.push_back(g);
if (g) ensureRenderScratch(g->tracks.size());
// Fresh track objects only: the audio thread never sees them change. Before any CC target
// exists their routes are complete as they are (empty): marking them so keeps an undo to
@@ -709,7 +739,7 @@ void Engine::publishRaw(std::shared_ptr<Graph> g) {
for (auto& t : g->tracks) t->ccRoutesDirty = false;
if (g->masterTrack) g->masterTrack->ccRoutesDirty = false;
}
- liveGraph_.store(g.get(), std::memory_order_release);
+ graphHist_.publish(g); // frees the graphs no render can still be walking
recomputeRouting(); // Phase B: refresh sidechain source-track → route-slot table
updateMonitorInput(); // a monitoring track may have come or gone (undo, delete, load)
}
@@ -1103,7 +1133,7 @@ void Engine::reset() {
void Engine::clearUndoHistory() {
// The stacks hold old authoring graphs only — never the live one — and every published
- // graph also sits in retired_ until the audio thread has moved past it, so dropping
+ // graph also stays in graphHist_ until the audio thread has moved past it, so dropping
// them here frees nothing the audio thread can still be reading.
undoStack_.clear();
redoStack_.clear();
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index 5d2d67a0..eb3e108e 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -153,6 +153,7 @@ class Engine {
void notifyXrun() { xruns_.fetch_add(1, std::memory_order_relaxed); }
int32_t xrunCount() const { return xruns_.load(std::memory_order_relaxed); }
bool xrunSelfTest(); // device-free: notifyXrun bumps the count by one
+ bool graphRetireSelfTest(); // device-free: a replaced graph is freed two renders later
// --- DSP load (Phase 11): RT render time / block budget, smoothed 0..1 ---
float cpuLoad() const { return cpuLoad_.load(std::memory_order_relaxed); }
@@ -214,6 +215,7 @@ class Engine {
bool modulationSelfTest();
bool rackSelfTest(); // Instrument Rack: chains sum, macros map, blob round-trips
bool rackDeviceSelfTest(); // Audio Effect Rack: pass-through, parallel sum, blob round-trips
+ bool timedEventsSelfTest(); // #436: a hosted plug-in renders once per block, events at their offsets
bool drumRackSelfTest(); // Drum Rack: notes route only to the matching pad chain
// Lane CRUD — structural (snapshot + undo). addAutomationLane returns the lane
// index, reusing an existing lane on the same target. get/set use the ABI point
@@ -1561,8 +1563,9 @@ class Engine {
Transport transport_;
std::shared_ptr<Graph> authoring_;
- std::vector<std::shared_ptr<Graph>> retired_;
- std::atomic<Graph*> liveGraph_{nullptr};
+ // The graph the audio thread renders. A replaced one is freed once two renders have
+ // finished after it, on the message thread (deleted tracks' plug-ins with it).
+ SnapshotHistory<Graph> graphHist_;
int32_t nextTrackId_ = 1;
int32_t nextTakeId_ = 0; // AudioTake::id (specs/067); never reused in a session
int32_t nextTakeGroup_ = 0; // AudioTake::group
@@ -1939,11 +1942,14 @@ class Engine {
// session-slot recording target (M5-4). recordSessionScene_ >= 0 selects slot
// mode; recordSlotPlayer_/recordSlotLen_ are read on the audio thread to time
// captured notes against the slot's own loop clock (SessionPlayer is stable
- // across snapshots, so the raw pointer stays valid while the track lives).
+ // across snapshots). recordSlotHist_ owns it, so a track deleted mid-take (freed with its
+ // graph) can't take it along: the next take retires it, and it is freed only once two
+ // renders have finished after that, so a block that read the old pointer is done with it.
int32_t recordSessionTrackId_ = 0;
int32_t recordSessionScene_ = -1;
bool recordSessionAudio_ = false; // audio take into slot (M5-4)
std::atomic<SessionPlayer*> recordSlotPlayer_{nullptr};
+ SnapshotHistory<SessionPlayer> recordSlotHist_; // lifetime only; read through recordSlotPlayer_
std::atomic<double> recordSlotLen_{4.0};
// audio-thread-owned state
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index d94788ce..a9696dab 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -14,6 +14,7 @@
#include "media/WarpStream.h"
#include <algorithm>
+#include <array>
#include <bit>
#include <chrono>
#include <cmath>
@@ -159,7 +160,8 @@ inline void deliverExpr(Instrument& inst, int32_t pitch, int32_t dim, float valu
// Drive an instrument through one block: note events and clip-note expression merged by
// sample offset (notes first at a shared offset, so a note's opening expression lands on it),
-// rendering the stretches in between. `live` runs once, before the first sample is rendered —
+// rendering the stretches in between (a hosted plug-in: the whole block at once, its events
+// stamped with their offsets — see Instrument::takesTimedEvents). `live` runs once, before the first sample is rendered —
// after the offset-0 notes, where live input sits — to apply the block's live expression.
// An instrument switched off (#148) renders its first block off once more, without the block's
// events, fading what was sounding to silence, then releases every voice and held controller;
@@ -186,25 +188,47 @@ void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs,
inst.render(&dst[cursor * 2], to - cursor);
cursor = to;
};
+ // An instrument that takes timed events renders once: each event is stamped with its
+ // offset instead of being rendered up to (#436). The order is the same either way.
+ const bool timed = inst.takesTimedEvents();
+ auto liveAt0 = [&] {
+ if (liveDone) return;
+ inst.eventOffset = 0;
+ live();
+ liveDone = true;
+ };
int k = 0, x = 0;
while (k < n || x < xn) {
const int32_t nOff = k < n ? std::clamp(evs[k].off, 0, frames) : INT32_MAX;
const int32_t xOff = x < xn ? std::clamp(xev[x].off, 0, frames) : INT32_MAX;
+ const int32_t at = std::min(nOff, xOff);
+ if (timed) {
+ if (at >= frames) break; // after the render, at the next block's start (as segmented)
+ if (at > 0) liveAt0(); // live input sits after the offset-0 notes
+ inst.eventOffset = at;
+ } else {
+ renderTo(at);
+ }
if (nOff <= xOff) {
- renderTo(nOff);
if (evs[k].on) sendNoteOn(inst, evs[k].pitch, evs[k].vel);
else
sendNoteOff(inst, evs[k].pitch);
++k;
} else {
- renderTo(xOff);
deliverExpr(inst, xev[x].pitch, xev[x].dim, xev[x].value);
++x;
}
}
- if (!liveDone) {
- live();
- liveDone = true;
+ liveAt0();
+ if (timed) {
+ inst.eventOffset = 0;
+ inst.render(dst, frames);
+ cursor = frames;
+ for (; k < n; ++k) // end-of-block events: offset 0 of the next render
+ if (evs[k].on) sendNoteOn(inst, evs[k].pitch, evs[k].vel);
+ else
+ sendNoteOff(inst, evs[k].pitch);
+ for (; x < xn; ++x) deliverExpr(inst, xev[x].pitch, xev[x].dim, xev[x].value);
}
renderTo(frames);
if (off) {
@@ -1740,6 +1764,9 @@ void Engine::triggerPassReplace() {
}
void Engine::processBlock(float* out, int32_t numFrames) {
+ // Every audio-thread read of recordSlotPlayer_ happens inside this block (count-in launch,
+ // live MIDI, capture), so this scope keeps the player it points at alive.
+ const SnapshotHistory<SessionPlayer>::RenderScope recordSlotScope(recordSlotHist_);
drainCommands();
for (int32_t i = 0; i < numFrames * 2; ++i) out[i] = 0.0f;
@@ -1749,9 +1776,10 @@ void Engine::processBlock(float* out, int32_t numFrames) {
drainLiveMidi(transport_.playheadSamples() / spb, playing);
- Graph* g = liveGraph_.load(std::memory_order_acquire);
- // This block's scratch, read after the graph: publishRaw publishes the scratch first, so
- // it always fits the graph seen here. Held until the scope ends the render epoch.
+ // The graph, then this block's scratch: publishRaw publishes the scratch first, so it
+ // always fits the graph seen here. Both held until their scopes end the render epoch.
+ const SnapshotHistory<Graph>::RenderScope graphScope(graphHist_);
+ Graph* g = graphHist_.live();
const SnapshotHistory<RenderScratch>::RenderScope scratchScope(scratchHist_);
rs_ = scratchHist_.live();
@@ -2816,4 +2844,48 @@ void Engine::renderTone(float* out, int32_t numFrames) {
}
}
+// #436: an instrument that takes timed events (a hosted plug-in) renders once per block, each
+// event stamped with its offset, in the same order the segmented render delivers them; an
+// instrument that doesn't is still rendered in segments with every event at offset 0.
+bool Engine::timedEventsSelfTest() {
+ struct Probe final : Instrument {
+ bool timed = false;
+ std::vector<int32_t> renders; // frames per render() call
+ std::vector<std::array<int32_t, 4>> events; // kind (1 on, 0 off, 2 ctl, 3 live), pitch, offset, renders so far
+ bool takesTimedEvents() const override { return timed; }
+ void setSampleRate(double) override {}
+ void noteOn(int32_t p, float) override { events.push_back({1, p, eventOffset, (int32_t)renders.size()}); }
+ void noteOff(int32_t p) override { events.push_back({0, p, eventOffset, (int32_t)renders.size()}); }
+ void allNotesOff() override {}
+ void controller(int32_t ctl, float) override {
+ events.push_back({2, ctl, eventOffset, (int32_t)renders.size()});
+ }
+ void render(float*, int32_t frames) override { renders.push_back(frames); }
+ };
+ constexpr int32_t frames = 64;
+ // Off before on at a shared offset (midiEvLess order); the last note-off sits on the block's end.
+ const MidiEv evs[] = {{0, true, 60, 1.0f}, {10, false, 60, 0.0f}, {10, true, 62, 1.0f}, {frames, false, 62, 0.0f}};
+ const ExprEv xev[] = {{20, -1, kCtlDimBase + 1, 0.5f}};
+ float dst[frames * 2] = {};
+ auto run = [&](Probe& p) {
+ playEvents(p, dst, frames, evs, 4, xev, 1, 0.0, 0.0, false,
+ [&] { p.events.push_back({3, -1, p.eventOffset, (int32_t)p.renders.size()}); });
+ };
+ using E = std::array<int32_t, 4>;
+
+ Probe timed;
+ timed.timed = true;
+ run(timed);
+ const std::vector<E> wantTimed = {
+ {1, 60, 0, 0}, {3, -1, 0, 0}, {0, 60, 10, 0}, {1, 62, 10, 0}, {2, 1, 20, 0}, {0, 62, 0, 1}};
+ if (timed.renders != std::vector<int32_t>{frames} || timed.events != wantTimed || timed.eventOffset != 0)
+ return false;
+
+ Probe seg;
+ run(seg);
+ const std::vector<E> wantSeg = {
+ {1, 60, 0, 0}, {3, -1, 0, 0}, {0, 60, 0, 1}, {1, 62, 0, 1}, {2, 1, 0, 2}, {0, 62, 0, 3}};
+ return seg.renders == std::vector<int32_t>{10, 10, 44} && seg.events == wantSeg;
+}
+
} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Engine_Session.cpp b/src/native/nota.engine/src/engine/Engine_Session.cpp
index 8dc754df..9a416a54 100644
--- a/src/native/nota.engine/src/engine/Engine_Session.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Session.cpp
@@ -334,6 +334,7 @@ void Engine::recordSessionSlot(int32_t trackId, int32_t scene) {
recordSessionTrackId_ = trackId;
recordSessionScene_ = scene;
recordSlotLen_.store(t->sessionSlots[scene].lengthBeats, std::memory_order_relaxed);
+ recordSlotHist_.publish(t->sessionPlayer); // the previous take's player waits out two renders
recordSlotPlayer_.store(t->sessionPlayer.get(), std::memory_order_release);
if (countIn && t->sessionPlayer) {
// The slot waits for the count-in: the audio thread launches it the moment the
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 0c7e3a66..b66569ec 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -9820,6 +9820,9 @@ Console.WriteLine("-- M7-8: xrun / dropout telemetry --");
Check(engine.XrunCount == 0, "xrun count starts at zero");
Check(engine.XrunSelfTest(), "notifying a dropout bumps the counter");
Check(engine.XrunCount == 1, "xrun count reflects the dropout");
+ Check(engine.TimedEventsSelfTest(),
+ "a hosted plug-in renders once per block with its events at their offsets (#436)");
+ Check(engine.GraphRetireSelfTest(), "a replaced engine graph is freed two renders later, not kept for the session");
}
// ===================== M9-A1: parameter automation (engine) ================