Compare commits

326 Commits

Author SHA1 Message Date
daniel 3eae942625 1.7.5 2026-08-06 09:50:21 -04:00
daniel 03f7fb5081 Merge branch 'omega-w3-t3-undo-collapse' into dev 2026-08-06 09:49:22 -04:00
daniel ab14ae769f Guard poll() against a mode-apply mid-flight; two doc corrections
Extends the OnTimer guard to skip session.poll() itself while modeApplyInProgress(), preventing an undo/redo or project-switch reload from replacing the view model under an in-flight applyMode.
2026-08-06 05:23:58 -04:00
daniel 2269fd80b6 Close the collapse's two dropped guarantees: latch applyMode against re-entrancy, pin its project once; correct three overclaiming doc lines 2026-08-06 05:07:31 -04:00
daniel 8c06383fe7 Collapse a Design View mode switch to ONE undo point: FX writes run inline in applyMode's block, deferred park queue deleted 2026-08-06 04:32:26 -04:00
daniel 8a7056d19d Fix undo-label misnomer, tighten drain-nesting/abort-path docs, mark inferred undo behavior as unverified
Renamed the drain's undo point to "Design View FX state" (it restores as often as it parks). Extended the nesting audit to cover a block opening inside the drain's own block. Marked post-fix undo behavior as inference pending DAW checks.
2026-08-05 20:54:31 -04:00
daniel 13c824c63d Collapse the FX-park drain's writes into one undo point instead of one per TrackFX_SetOffline 2026-08-05 20:40:45 -04:00
daniel bd86ede5b3 Merge FX-park snapshot guard: refuse to park when the pre-park truth is gone
A snapshot is never taken from a chain a park has touched, on either
half -- flags or per-FX offline. Stranded tracks are refused, named
once in the console, and left recoverable by hand.
2026-08-05 20:17:00 -04:00
daniel 4b306dd436 Name refused tracks before Undo_EndBlock2, not after; tighten the route-list doc; pin the refusal memo's gate
Fixes D (handle lifetime), C (ASCII dashes), G (comment compression), I (shouldReport extracted + tested); CLAUDE.md route list corrected per A/B/H. E pushed back -- cross-module GUID plumbing is architectural, not a targeted fix.
2026-08-05 17:34:49 -04:00
daniel 5376ab085c Extend the park trust test to the FX chain, name the refused tracks, and stop reprinting an unchanged refusal 2026-08-05 17:10:19 -04:00
daniel 67524206fb 2nd Pass Render 2026-08-05 16:21:17 -04:00
daniel 203961f41c Refuse to park a track whose pre-park snapshot is gone, rather than re-snapshotting the already-parked chain as the user's state 2026-08-03 18:30:40 -04:00
daniel 2f96dd3da5 Revert Ω-W2-T4: FX-park state stranded across save/reopen
Backs out the deferred park drain split. Forced synchronous FX-park
drains return, and with them the mode-switch hitch, until the
re-snapshot-after-discard fix lands.
2026-08-03 18:05:04 -04:00
daniel 098727e464 Merge panel polish: crosshair arrange-drop cue, Re-capture and Insert Conform to the overflow menu 2026-08-03 17:50:09 -04:00
daniel 0e6a0d3618 fix: use crosshair cursor for arrange-drop cue instead of I-beam
The I-beam read as a text-editing cursor rather than a timeline placement point.
2026-08-03 17:49:18 -04:00
daniel 8487833342 Revert "Merge Ω-W2-T4: split the deferred FX-park drain by kind"
This reverts commit 70bd29dc89, reversing
changes made to 84afd1b545.
2026-08-03 17:46:17 -04:00
daniel d22446ef7d Move Re-Capture and Insert Conform from the panel top bar to the overflow menu; re-pin action_bar width test to the new 4-button top bar. 2026-08-03 17:44:00 -04:00
daniel 4b19556513 Merge Insert as FX: load ReaSampler 9000 onto the selected track from the panel
# Conflicts:
#	src/shell/actions/CLAUDE.md
2026-08-03 16:46:40 -04:00
daniel a5febbd6aa Merge drag-out hand-off fix: keep the drag internal while the pointer is over REAPER 2026-08-03 16:45:14 -04:00
daniel 51c7505dc0 Fix Insert-as-FX review findings: id rename, selection-count drift, refusal tooltip, success msg, master-only, reserve test
Renames the permanent action id out of the placement family, makes the button's
painted state and pressed outcome share one selection count, surfaces
panel-known refusals in the tooltip, reports the target track on success,
distinguishes a master-only selection, and pins the overflow-reserve test to the
real bar spec.
2026-08-03 16:43:10 -04:00
daniel b71a05fbef Close the bridged-process hole in the drag-out hand-off gate
OsHandoff now needs the window-ownership proof AND a hit-test that named
nothing, so a bridged plugin's UI can't read as off-REAPER.
2026-08-03 16:42:59 -04:00
daniel aa87d81f1f Merge Ω-W2-T5: bound the waveform zero-crossing snap to a pixel radius
Single-cycle loop marks stop teleporting to the one interior crossing. Ctrl on a
marker drag defeats the snap, and no longer loses the grab to a coincident node.
2026-08-03 16:09:27 -04:00
daniel 70bd29dc89 Merge Ω-W2-T4: split the deferred FX-park drain by kind
Restores stay forced before the view model serializes; parks go one FX per idle
tick behind a 1s coalescing debounce, so a rapid A-B-A flip costs no plugin work.
2026-08-03 16:09:20 -04:00
daniel 84afd1b545 Merge Ω-W2-T2: throttle new-content enumeration off the 30/s timer tick
Extracts elapsedAtLeast to core/util with the GetTickCount wraparound asserted.
2026-08-03 16:09:12 -04:00
daniel f91054276b fix(instrument): stop Ctrl-before-click stealing a waveform mark grab from a coincident node
Ctrl held before mouse-down forced the node/toggle win over a smaller cap or
column regardless of area; now it defers to the ordinary smallest-area
arbitration like a plain click. Also amends product docs, VERIFICATION.md, and
adds sparse-material/narrow-overlay test fixtures.
2026-08-03 16:07:49 -04:00
daniel fcd1ed022c feat(panel): add Insert as FX — ReaSampler 9000 onto the selected track, preloaded with the focused capture, over the existing instrument-drop body 2026-08-03 16:06:22 -04:00
daniel 9599e96e0c Fix drag-out giving live drags to OLE: prove the pointer left REAPER
OffReaper leaves the surface vocabulary; OsHandoff now gates on a window-ownership
proof resolved in the shell, so no in-REAPER surface can reach DoDragDrop.
2026-08-03 15:50:25 -04:00
daniel 761125d0fe view: assert the FX-park coalescing delay's debounce; correct four overclaiming doc/comment claims
Extracts parkReadyAt/parkIsReady as a tested pure fold per PLAN.md's phase
criterion; the rest is wording fixes — hitch bound, hazard width, forced-drain
scope, progressive CPU reclaim.
2026-08-03 15:50:07 -04:00
daniel 5042e2709b docs: cascade rulings R2 (band-limiting in scope) and R3 (the Omega snap fence yields)
R2 closes fork F6 IN: complex waveforms must be supported purely, so band-limited
playback enters the near-term scope alongside the loop-grid recalibration. Re-derives
the three post-R1 reliefs it spends — it reaches process(), reopens a parameter door,
and recontends the deck headroom — and mints F9-F12 for the shape it deliberately
does not rule. R3 makes the snap-radius work Phase Omega's own W2-T5 and supersedes
the zero-crossing-snap criterion at its three sites, recording that W1-T5 met it.
2026-08-03 15:37:16 -04:00
daniel d5280687f3 docs: record Daniel's static-captures ruling on the wavetable direction
R1 (2026-08-03) closes F5 — no frame-indexed wavetables yet — deferring W1 with
"yet" preserved as scope rather than rejection, and confirming W3 out. Near-term
scope narrows to W0 alone. Cascades the consequences: F1's threshold amended
(static does not mean one-cycle, so detection classifies nothing now), F2
simplified, F3 and F7 firmed, F8 narrowed to a binary. F6/band-limiting left
open and explicitly not pre-ruled. PLAN.md item 4 updated to match.
2026-08-03 15:21:03 -04:00
daniel b7b7e88195 fix(instrument): bound the waveform zero-crossing snap to a pixel radius so single-cycle loop marks stop teleporting
Ctrl during a marker drag defeats the snap outright. nearestZeroCrossing keeps its
unbounded contract; snapToZeroCrossing is the decision a drag applies.
2026-08-03 15:15:25 -04:00
daniel 59837abd00 docs: register single-cycle-and-wavetable.md in the product-doc list 2026-08-03 15:14:08 -04:00
daniel cca7d1a538 docs: frame the single-cycle / wavetable direction, eight forks open
Where the instrument's loop grid, crossfade and pitch handling stop making
sense as a capture shrinks toward one cycle, and what "wavetable synth" would
mean here. Two structural results: the pre-seam crossfade is the identity map
at one-period loop lengths, and YIN cannot detect a single cycle, so the period
is declared rather than detected there. Four candidate shapes, W3 recommended
out. PLAN.md gets a pointer under "Flagged for awareness" only.
2026-08-03 15:08:11 -04:00
daniel 6e2128e937 view: split the deferred FX-park drain by kind — restores stay forced, parks go one FX per idle tick behind a 1s coalescing delay
A rapid A→B→A flip now costs no plugin work: the restore cancels the still-pending
park outright. A park that has already written one FX carries a `partial` flag and is
superseded by its inverse rather than cancelled, so a half-parked chain is never stranded.
2026-08-03 15:00:40 -04:00
daniel 32c7e959ae Extract elapsedAtLeast to core/util, dedupe the throttle rationale, and correct the alloc-count/PLAN citations 2026-08-03 14:58:33 -04:00
daniel 170b2e4994 Throttle new-content enumeration to 500ms, off the 30/s OnTimer tick 2026-08-03 14:40:50 -04:00
daniel 1159d364c2 Merge Phase Ω-W1: mode-switch responsiveness and the control surface's second pass
Five tracks: deferred FX park with honest undo mask and synchronous drain
before persist; narrowed mode-switch persist; master meter on its own 60 FPS
timer with dirty-rect paint; deck reflow with single-button toggles and
click-to-focus overlays; one overlay-to-waveform coordinate mapping.
2026-08-03 14:33:33 -04:00
daniel 93d6fd0271 Merge Ω-W1-T4: deck reflow, focus-by-click overlay selection, single-button toggles 2026-08-03 14:30:59 -04:00
daniel d16df67eed Merge branch 'omega-w1-t3-meter-rate' into phase-omega 2026-08-03 14:21:44 -04:00
daniel c8e08a7670 Merge branch 'omega-w1-t1-mode-switch-responsiveness' into phase-omega 2026-08-03 14:21:36 -04:00
daniel c9af821eae Merge Ω-W1-T2: narrow the mode switch's persist to the one key it changes 2026-08-03 14:19:09 -04:00
daniel d278c38370 Merge Ω-W1-T5: one overlay↔waveform mapping, loop marks honest about their mode 2026-08-03 14:19:03 -04:00
daniel 78e5f06928 Drain deferred FX parks before the view model is serialized; re-validate track handles per intent; pin the restore-plan round trip 2026-08-03 14:08:28 -04:00
daniel 07b51dcabf Ω-W1-T3 remediation: meter stays live and washed under the curve popup, not frozen 2026-08-03 14:04:14 -04:00
daniel 84905e6bd1 fix(instrument-ui): raise Disabled-cue contrast, fix stale 1.2 MASTER row, close hover/focus minors 2026-08-03 14:04:00 -04:00
daniel 3137c05961 Ω-W1-T5: fix two stale comments in test_waveform_view.cpp (retired proportional-round model; sweep's structural-not-behavioural role) 2026-08-03 14:00:16 -04:00
daniel 73c69f689c fix(instrument-ui): distinguish Disabled from Off, add hover cue to mode toggles, close review minors
Adds a hairline outline for Disabled chrome buttons, resolves Hover on the four
mode-selector single-buttons, re-measures the control-surface doc's 1.2 layout
table post-reflow, and adds a structural test pinning every enable/mode toggle
to a derived segment.
2026-08-03 13:43:38 -04:00
daniel 7169d7f22b Clear the park snapshot where the restore is planned, not where it drains; make the drain re-entrant and reload-aware 2026-08-03 13:35:30 -04:00
daniel dd067a192e Ω-W1-T3 review fixes: skip meter invalidate when covered; push fast-path predicates into core
Fixes the critical finding — Browse/curve-popup no longer trigger 60 Hz
whole-client repaints when the meter is invisible. Pushes the fast-path and
self-containment geometry into master_meter with tests; batches the four minor
findings.
2026-08-03 13:31:50 -04:00
daniel e714df80f8 Ω-W1-T5 review fixes: unify the drag frame resolve onto frameToX/xToFrame; honest comments on grabbableMarks and the grey-loop-mark contrast trade 2026-08-03 13:26:44 -04:00
daniel 450559f155 deck: filter mod moves to FILTER ENV, cell runs centre in their reserves, two-segment toggles become single buttons, deck focuses its overlay 2026-08-03 13:12:28 -04:00
daniel a3853231a7 Ω-W1-T5: one overlay↔waveform mapping, and loop marks that tell the truth about their mode 2026-08-03 12:39:41 -04:00
daniel 4320bfdb08 Ω-W1-T3: run the master meter on its own 60 FPS timer, and make a meter frame cost one rect 2026-08-03 12:39:36 -04:00
daniel 82a8d51004 Narrow the mode switch's persist to the one key it changes
A switch wrote all seven ext-state keys to record that view_state moved,
re-serializing the bank book and the tracking ledger for nothing. Both entry
surfaces now take saveViewStateOnly; every other caller keeps the full save.
2026-08-03 12:39:28 -04:00
daniel a4a1c3860f Defer Design View's per-FX park to an idle tick; honest undo mask, compare-before-write, PreventUIRefresh bracket, O(1) handle resolve 2026-08-03 12:39:22 -04:00
daniel 0eb2c67875 docs: spec Phase Omega — mode-switch responsiveness and the control surface's second pass
Eight tracks across two waves, from Daniel's seven-item list of 2026-08-03; all
six forks ruled, none open. Amends instrument-control-surface.md 6.3(d) and 6.4,
both reversed by Omega-F2.
2026-08-03 11:43:28 -04:00
daniel 3376f3eaa1 Merge version bump: ReaSampler 1.6.0 2026-08-02 23:13:16 -04:00
daniel 8c1fccf450 Bump ReaSampler to 1.6.0
Phase Gamma landed the instrument's master bus, a real time-stretcher, a reflowed deck, and 44 host-automatable VST3 parameters — a user-visible capability increment, which versioning-and-release.md assigns to MINOR.
2026-08-02 23:12:58 -04:00
daniel cbc4a4c53e docs: give Phase Gamma's DAW obligations a home in VERIFICATION.md 2026-08-02 23:12:51 -04:00
daniel 27712b7573 docs: retire Phase Gamma from PLAN.md; repair stale line/symbol citations across PLAN, the Lambda build-toolchain audit note, and root CLAUDE.md 2026-08-02 22:31:54 -04:00
daniel 2ee984ed16 Merge Phase Gamma: the ReaSampler 9000 instrument grows a master bus, a real time-stretcher, a reflowed deck, and 44 host-automatable parameters
Four waves, fifteen tracks. dev's Phase E/P work was merged in first and resolved on the branch; this bubble lands the combined tree. In-DAW verification still outstanding.
2026-08-02 22:14:06 -04:00
daniel 77eb7c6680 Merge dev into phase-g: Phase Ε/Ρ and the 1.5.0 bump meet Phase Gamma's instrument work; 120/120 green
The per-directory CLAUDE.md count is re-derived at twenty-seven rather than
carried from either side. The "Decouple the instrument reload from VST3
activation" TODO entry does not survive: Γ-W3-T1 landed it, and COMPLETED.md
carries the discharge.
2026-08-02 21:57:47 -04:00
daniel 53e7d35178 docs: record the bake-prints-limiter track and close Phase Gamma 2026-08-02 21:32:04 -04:00
daniel 3313ac6b96 Merge Γ-W3-T3: the bake prints the limiter through its master stage, with the lookahead compensated so an engaged bake returns the sound the user approved and a bypassed one is byte-for-byte unchanged 2026-08-02 21:24:13 -04:00
daniel a3698972db docs: close three review nits — the build-shape index, a redundant header restatement, and the CMake guard comment
Bump the product doc's track count and list for T3; trim the header's
pre-limiter restatement now that bake_render.cpp carries it; add limiter
to the extension's not-linked enumeration.
2026-08-02 21:24:00 -04:00
daniel 0d316b7b9e Print the limiter through the bake's master stage, compensating its lookahead so an engaged bake is the approved sound and a bypassed one is unchanged 2026-08-02 20:57:29 -04:00
daniel b584fa4da9 docs: anchor the product-doc citations to symbols, not line numbers
Ten more were already pointing at unrelated code. Vendor SDK and SWELL citations left alone — those files don't move.
2026-08-02 20:46:28 -04:00
daniel 00afa9ba2e docs: anchor the checklist citations to headings and symbols, not line numbers
Line numbers rot silently. Ten were already broken, including all eight Precision invariants pointers. Vendor citations left alone.
2026-08-02 20:33:35 -04:00
daniel a9c166b8c2 docs: record Phase Gamma Wave 4's landed track and collapse the wave to it 2026-08-02 20:30:04 -04:00
daniel d3f5e6ec17 Merge Γ-W4-T1: the instrument's 44 automatable parameters under a frozen id table, both VST3 delivery channels serviced, and a stated authority model bounding a lane's authority to the window the model has not caught up on 2026-08-02 20:21:02 -04:00
daniel de34fbafdb Close two defeatable ReleaseProof guards and fix the static-lane skip's dead comparison
ReleaseProof{} and copy-reuse both compiled under this project's C++17;
user-provided ctor, deleted copy ctor and friend close them. The skip now
compares stored values, not norms, so it actually fires. Abort downgraded
to a debug assert.
2026-08-02 20:20:48 -04:00
daniel 4c6545e0d3 docs: give Phase Rho's DAW obligations a home in VERIFICATION.md 2026-08-02 20:15:56 -04:00
daniel bd7d6857e5 docs: retire the bake mono collapse and FX-GUID keying entries, file what they left behind
Both landed with accepted consequences rather than avoided ones, so COMPLETED
carries the identity move and the offline-FX degrade. Two line-ceiling entries
and the DAW-unverified GUID stability are now tracked.
2026-08-02 20:10:01 -04:00
daniel 430faff230 Merge Design View FX-GUID keying: parked FX-offline state follows the plugin, not the slot 2026-08-02 20:02:53 -04:00
daniel b5a820ed8a Merge the bake's mono collapse: a dead-center resample bake lands one channel, like every other capture 2026-08-02 20:02:47 -04:00
daniel 037707e517 docs: repoint the preamble at COMPLETED.md where the retired sections used to be 2026-08-02 19:58:48 -04:00
daniel 6787e1725c docs: the product-docs index was six files behind, including Epsilon's own spec 2026-08-02 19:52:07 -04:00
daniel 056c60c8e1 Make the automation release's publish-ordering rule a compile-time guard, not an assert
The assert compiled out under Release's NDEBUG and ran in no test target.
AutomationChannel::release now requires a ReleaseProof that only
publishLiveParams() or noRepublishNeeded() can mint.
2026-08-02 19:36:32 -04:00
daniel d5ed4f6e53 Split unidentified from missing FX in Design View drop report, fix message + console pop
Distinguish no-GUID-at-capture from identity-no-longer-live; rewrite the drop
message to state the real recovery step; mark FX-GUID stability [verify — DAW];
guard mismatched fx/fxOffline lengths; the report never force-opens now.
2026-08-02 18:51:41 -04:00
daniel 90b9d4527c Trim bake_landing comments: one-home the collapse rationale, fix a ragged header wrap
Also notes why staged.collapsed goes unread at its read site, so a future
reader won't file it as a bug.
2026-08-02 18:51:38 -04:00
daniel 5f6efb7cc3 Key Design View's parked FX-offline state to the FX's own GUID, not its slot
view_state v2 writes identities beside the v1 slot array, so a downgrade keeps
what it had. An FX gone at restore time is dropped and reported, never restored
onto whatever took its place.
2026-08-02 18:31:08 -04:00
daniel 425b9f708c Collapse a dual-mono resample bake to one channel, like every other capture
prepareLanding takes the shared collapse on the staged buffer before the hash
and the channel-count read, so hash, entry and file all derive from one buffer.
A true-stereo bake stays byte-identical.
2026-08-02 18:31:05 -04:00
daniel 02319041e3 docs: retire Phases Theta, Xi, Psi and Epsilon from the plan
All four are landed in full. Their narratives live in COMPLETED.md; the plan now carries only Gamma and Lambda. Cross-references and VERIFICATION.md citations repointed.
2026-08-02 18:27:54 -04:00
daniel 9b5393098b Close pass four: undetented host curve read, LiveValues guard, ordering assert, static-lane fix, docs
Points toPlain's exponent arm at the undetented curve map so host reads
match the editor; adds a sizeof guard plus field-poison test for
LiveValues::operator==; skips the model write when an automation value
hasn't moved; corrects five stale doc citations.
2026-08-02 18:22:21 -04:00
daniel 4231b2321c Merge version bump: ReaSampler 1.5.0 2026-08-02 17:40:40 -04:00
daniel 163c091f55 Bump ReaSampler to 1.5.0
Retires the 1.4.003 zero-padding experiment; project() and README version banner now agree at 1.5.0.
2026-08-02 17:40:30 -04:00
daniel beaf527bc6 Merge Phase Ε: the .rsbank bank package — pure codec, filesystem shell, both verbs, and the frozen compatibility corpus
# Conflicts:
#	docs/COMPLETED.md
2026-08-02 17:33:44 -04:00
daniel fa69b6c547 docs: record the millisecond floor as located and closed, and split what stayed open
The retired custom-bounds premise is corrected wherever it was encoded: the tail
bit is the time selection's, not custom bounds'.
2026-08-02 17:22:20 -04:00
daniel f33ef9af37 docs: give Phase E's DAW obligations a home in VERIFICATION.md 2026-08-02 17:19:57 -04:00
daniel a2ee5ff69d docs: the picker was never a deviation, it was a regex miss in the plan 2026-08-02 17:19:57 -04:00
daniel 24569956cf docs: record Ε-W3 as landed and Phase Ε as complete 2026-08-02 17:19:57 -04:00
daniel c0c56ab2a7 Merge Ε-W3-T1: the frozen package compatibility corpus and the harness over it 2026-08-02 17:19:57 -04:00
daniel b99027bc4c docs: collapse the landed Phase E track specs to Landed form
Five tracks across W1 and W2 now point at COMPLETED.md. W3 and the phase
header stay live.
2026-08-02 17:19:57 -04:00
daniel 3fd3214ff8 Remediate Ε-W3-T1 package-compat-fixtures review findings
Freeze *.rsbank as binary via .gitattributes; add a truncated additive_forward fixture proving the exact-size proof beats TooNew; enumerate the fixture dir to catch orphaned files; make fixture-size checks fatal instead of just logged; pin fixture version asserts as literals, not build-relative.
2026-08-02 17:19:57 -04:00
daniel 1005c943a2 docs: record Phase E waves 1 and 2 as landed
Backfills W1, which was skipped when it merged, and adds W2's two verbs.
Notes the picker deviation: GetUserFileName both directions, not the
spec'd Win32/SWELL split.
2026-08-02 17:19:57 -04:00
daniel 9521b5339f Freeze the package compatibility corpus: real .rsbank bytes proving both ladder directions, every truncation site, and the round trip 2026-08-02 17:19:57 -04:00
daniel 2069ae8086 docs: point the three bumpBankGeneration citations at the right line
A prior pass corrected session.h:108 to :114, but :114 is the read accessor;
the bump is at :121. Also corrects a module count in the package doc.
2026-08-02 17:19:57 -04:00
daniel f9b191bd36 Merge Ε-W2: bank export and bank import, both verbs and both panel rows
Union of two parallel tracks. Both action rows, both menu rows, both link
edges survive; the two package CLAUDE.md files now describe the post-merge
reality rather than either side's pre-merge scope.
2026-08-02 17:19:57 -04:00
daniel 01481350e6 Merge Ε-W2-T1: the bank export verb, its pure planner, and the .rsbank writer 2026-08-02 17:19:30 -04:00
daniel f8dde16a7e import: remediate review findings — ledger gate, docs, message split
Delegates the refuse-gate to ledgerDegraded(), lifts its console message into a
pure testable fold, fixes stale doc line citations and an inaccurate outcome-enum
comment, and splits the rename counter into collision-vs-sanitize.
2026-08-02 17:19:30 -04:00
daniel 33ea95078d docs: add the two package directories to the architecture table
Also adds the missing core/instrument/engine/loop row and corrects the
per-directory CLAUDE.md count from twenty-three to twenty-six.
2026-08-02 17:19:30 -04:00
daniel 454f67b3bc Close bank-export review findings: name-cap underflow, double overwrite prompt, test scope
Clamps insertSuffix's underflow, floors uniqueEntryName's validity guard, suppresses
the redundant overwrite confirm via a picker out-param, adds a PayloadBuffer
high-water mark, and corrects stale CLAUDE.md/CMake claims.
2026-08-02 17:19:30 -04:00
daniel a927dad2f4 import: a .rsbank lands as a new bank, whole or not at all
Four collisions answered explicitly: ids reminted, names never overwritten,
content deduped before the write, bank name auto-suffixed. Degraded ledger
refuses before the picker.
2026-08-02 17:19:30 -04:00
daniel 752d3413f8 Merge Ε-W1-T2: the package filesystem shell, pickers, and rollback journal 2026-08-02 17:19:30 -04:00
daniel 081b6f1028 package: one bank leaves the project as one .rsbank, or the export refuses and says why
Pure planner classifies missing/unreadable/unrepresentable and repairs transport
names; the verb digests, streams and commits atomically over a const session.
2026-08-02 17:19:30 -04:00
daniel f87ea3d3d7 Merge Ε-W1-T1: the pure RSBK package format, ladder, and manifest codec 2026-08-02 17:19:30 -04:00
daniel f188846370 docs(package): record known gaps and correct stale claims
Notes the export verb's overwrite-consent obligation post-append, the append's
extension-divergence behavior, and readFilePayload's 4GiB blind spot; fixes a
stale u8string() reference and marks the 4GiB guard as accepted-unexercised.
2026-08-02 17:19:29 -04:00
daniel ff65371eb6 Merge Ε-W1-T3: OriginKind::PackageImport for the file-tracking ledger 2026-08-02 17:19:29 -04:00
daniel 181b4f2edb Record parseSlots exemption and fix stale package doc comments
Documents why parseSlots skips repeat-key rejection, corrects two drifted doc
lines (naming-rule count, Malformed-after-header header validity), and records
two forward obligations for import_plan in CLAUDE.md.
2026-08-02 17:19:29 -04:00
daniel 655159ceac Close package fs review findings: readRange bounds, picker ext, non-ASCII tests
Cap readRange's allocation and reject size_t overflow instead of truncating;
re-append .rsbank when the export picker omits it; add cafe coverage for
writeFileExclusive and writeLandedFile; loop write() on EINTR.
2026-08-02 17:19:29 -04:00
daniel a197ff7d68 docs: fix overclaiming OriginKind comment and trim restated test comments
Enum comment claimed package-id lookup that no persisted field supports; reworded
to the real distinction. Trimmed CLAUDE.md-duplicated test comments and the header.
2026-08-02 17:19:29 -04:00
daniel 3909b1072c Close the RSBK name-collision class: ASCII case folding, UTF-8 well-formedness, nested-path traversal
All three are format-locked and validated on encode and decode. Repeated known
keys now reject at the root and inside an entry rather than last-wins.
2026-08-02 17:19:29 -04:00
daniel edfd7ead4d Fix the package fs seam: UTF-8 paths, GetUserFileName pickers, exclusive-create landing, rollback arm/disarm
Both pickers now ride GetUserFileName (mode 0/1); the "no save picker" premise was false.
Landing uses O_EXCL so the create is the existence check, not a TOCTOU pair.
2026-08-02 17:19:29 -04:00
daniel 35b2a3a151 tracking: append OriginKind::PackageImport as value 5
An appended field-vocabulary value, so kLedgerVersion stays 2 — pinned by a
test. Unknown kinds still degrade to Unknown with the ledger Loaded.
2026-08-02 17:19:29 -04:00
daniel 1aebf51938 Relabel post-manifest-parse failure as TooNew; refuse zero-length package entries at encode
An additively-tagged newer package that fails to parse now reports TooNew (with
writer semver) instead of unactionable Malformed. Format layer also refuses encoding
a zero-length entry, honoring the shell's appendPayload contract; both test-covered.
2026-08-02 17:19:29 -04:00
daniel 41a3016e63 Land the package filesystem shell: streaming atomic package_io, journaled rollback carve-out, asymmetric platform pickers 2026-08-02 17:19:29 -04:00
daniel e0b4ec2e21 Tighten RSBK package-format validation for review remediation
Reject NUL/control bytes and Windows-hostile names in entry names, relax
the over-broad ".." substring ban to component-only, close the
trailing-garbage gap on empty manifests, and relocate the package
CMake subdirectory to its ladder home.
2026-08-02 17:19:29 -04:00
daniel 043558a54d Land src/core/package: the pure RSBK container — format ladder, JSON manifest, framing/layout codec
Two-integer ladder (formatVersion/minReaderVersion), bare-name-only entries
validated on encode and decode, prefix decode that proves exact file size
without ever reading a payload.
2026-08-02 17:19:29 -04:00
daniel 1fd38bbd57 Bound the automation hold to the window the model has not caught up on, and make that authority model stated, enforced and tested 2026-08-02 17:16:02 -04:00
daniel 09a9ef838f 1.4.003 (Θ/Ξ/Ψ/Ρ) 2026-08-02 17:14:49 -04:00
daniel ec95aac274 Merge the settled bounds channel: the time selection is the only window REAPER is handed, and the experiment that proved it is gone 2026-08-02 17:09:46 -04:00
daniel 4c7e0507a1 Fix vacuous bounds test and stale/circular comments from the settle
Replace the self-comparing render-window loop with a genuinely discriminating
floor-vs-exact check; correct two stale claims; mark the Auto/Manual floor-parity
premise as unverified; drop the STARTPOS/ENDPOS comment's circular justification.
2026-08-02 17:08:11 -04:00
daniel 8331df2e91 Settle the render window on the time selection and delete the experiment that proved it
The millisecond floor lives in the custom-bounds field, not the engine, so
RENDER_BOUNDSFLAG=2 is now the only bounds mode: the two-position type, the
console verdict and the STARTPOS/ENDPOS drift probe all go. capture.cpp 697 -> 622.
2026-08-02 16:55:12 -04:00
daniel d85e50c143 Merge render-bounds channel experiment: hand the window over on a switchable channel, and print a verdict that is proof only when no floored model fits 2026-08-02 16:23:51 -04:00
daniel de5654fb6f Service both VST3 parameter channels, and promote pitch key-track and Trigger length so all 44 ids issue
The SDK's own single-component sample drains inputParameterChanges in
process() and implements setParamNormalized; automation was reading the
GUI channel alone. The audio thread now patches a block it solely owns.
2026-08-02 16:22:17 -04:00
daniel bcdf97d6c4 Fix render-bounds EXACT verdict: enumerate floored models instead of trusting grid membership
Grid-ness of an edge was a proxy for "no floor could explain this count," not
the test itself — equal remainders on both edges cancel under a full floor. Now
checks all three floored models directly and corrects the SHORT/LONG
floor-signature docs.
2026-08-02 16:21:46 -04:00
daniel 5f971e60cd Close three critical review findings on the render-bounds-channel verdict
Verdict can no longer print a false EXACT on an on-grid end, no longer names a
bounds channel a content-derived render never consulted, and the grid-align doc
premise is corrected without implementing it.
2026-08-02 15:56:57 -04:00
daniel bfaa0f2614 Report the instrument's automatable parameters to the host under a frozen id table, in signal-flow order, with real units
42 of 44 ids issued: pitch key-track and Trigger length stay reserved
pending a live path. Master gain reclassified Live — it never reloaded.
2026-08-02 15:14:16 -04:00
daniel 51b13304ee docs: retire Phase Rho from the plan, record it as landed 2026-08-02 15:04:19 -04:00
daniel b400384a4f Merge Phase Rho: render in place, a track's output to a new sibling with the source parked on the bench 2026-08-02 14:55:11 -04:00
daniel 7c43e55435 docs: make render_bounds_gate bullet destination-aware
Phase P split Bank-move vs ProjectMedia-leave-in-place behavior in render_bounds_gate.h but missed updating this CLAUDE.md bullet.
2026-08-02 14:54:58 -04:00
daniel d7e5c59547 Remediate Phase P render-in-place review findings
Fix the ProjectMedia refusal path's false bank claims and file relocation, an unreachable-undo idiom, and eight comment/doc accuracy issues.
2026-08-02 14:51:55 -04:00
daniel 5c0f5f1591 Render in place: a track's output to a new sibling, source to the bench 2026-08-02 14:47:59 -04:00
daniel a0fd931dcb Merge render-bounds diagnostics: prove the window at the boundary it crosses, on every tail mode 2026-08-02 14:47:19 -04:00
daniel 0ab4673887 Fix eight review findings on the render-bounds diagnostics
Corrects a false comment example, fixes two tests that couldn't detect their
own regressions, adds two more read-back checkpoints around Main_OnCommand so
a drift report self-locates, guards a spurious zero-vs-zero coincidence match,
and softens two sentences that overclaimed cause or defect.
2026-08-02 14:45:42 -04:00
daniel 292d14d14c Prove the render bounds at the boundary they cross, and name a short render whose count is exactly a millisecond-floored window
No truncation exists on our side of that boundary, so the read-back is the
only evidence available for whether REAPER kept the window — and it fires on
every tail mode, where only None was ever judged.
2026-08-02 14:28:03 -04:00
daniel c7afa3a80f docs: collapse Phase Gamma Wave 3 to its landed record, open bake-prints-limiter 2026-08-02 14:06:38 -04:00
daniel e87d044042 docs: record Phase Gamma Wave 3's two landed tracks in COMPLETED 2026-08-02 14:06:38 -04:00
daniel 5236c58838 Merge Γ-W3-T1: two categorical deck rows and a double-height MASTER bus deck, an exact filter tie-line at a 1028 row block, and the instrument reload decoupled from VST3 activation 2026-08-02 14:06:38 -04:00
daniel 7c473bce73 Merge Γ-W3-T2: the bake's reset list verified complete by construction, and the limiter's exclusion from the printed master stage recorded 2026-08-02 14:06:38 -04:00
daniel da14509ab5 Restore the bank fold and usage publish to the resume path, guard setActive against repeats, and make the meter fold's bound literal
The resume also hands back to a full reload when the fold moves the loaded capture's decode source, so the refs table and the audio cannot skew.
2026-08-02 14:06:37 -04:00
daniel 5c6525fb91 Decouple the instrument reload from VST3 activation, and make the master meter's accumulate exact 2026-08-02 14:02:26 -04:00
daniel 4b0b03d8d5 Fix stale post-widen deck-reflow figures (90/144/1190px) across docs and tests, and split test_deck_groups.cpp's width-budget fixtures into a new file. 2026-08-02 13:59:35 -04:00
daniel b956fe0d5a Commit the limiter's audible state on the click and defer only the host's latency restart
setInstrumentParams now arms a sticky pending restart that flushLatencyRestart drains from the sync tick; setState and the bake's adopt flush at their own tails.
2026-08-02 13:59:34 -04:00
daniel 41876674e4 Fix deck-UI review findings: right-anchor MASTER's meter column, correct stale/overclaiming comments, split test_deck_groups.cpp on its commit-tier/overlay seam, and pin two width-ceiling assertions. 2026-08-02 13:56:16 -04:00
daniel df10ddacc2 Widen the deck row block to 1028 so the filter tie-line is exact, and accumulate the meter's block peaks instead of sampling one in 47 2026-08-02 13:56:15 -04:00
daniel 0627398bbb Reflow the deck into two categorical rows plus a double-height MASTER bus deck
Row membership is now the group's own property, not a wrap outcome. FILTER's Band|Notch moves to its caption slack, which is what makes the sound row fit. MASTER gains the limiter toggle, the output meter and the GR lamp.
2026-08-02 13:52:33 -04:00
daniel f60c05c042 docs: collapse Phase Gamma Wave 2 to its landed record, and correct five spec claims the implementation disproved 2026-08-02 13:52:32 -04:00
daniel 1490c25250 Close Γ-W3-T2 review remediation: widen the bake-reset test's per-parameter coverage, correct four overclaiming comments, state the stage-time ceiling's disposition, and fix a missing include
Dials and asserts pitch-env/filter-env/trigEnv fields the sweep previously skipped in both fixtures; no reset behavior changed.
2026-08-02 13:52:32 -04:00
daniel bf7840020e docs: record Phase Gamma Wave 2's two landed tracks in COMPLETED 2026-08-02 13:52:32 -04:00
daniel e2981e83ee Bake reset: assert the limiter and bake Hold land neutral, prove the loop returns parked, and baseline the render's identity path
resetAfterBake is unchanged — every value already resets by construction. The render prints master gain but not the limiter, so §3.4's rationale is wrong; the invariant is corrected.
2026-08-02 13:52:32 -04:00
daniel 782f50c859 Merge Γ-W2-T2: an explicit loop enable, four named marks with grabbable caps, and the crossfade painted where it is heard 2026-08-02 13:52:32 -04:00
daniel d4acb3feb5 Merge Γ-W2-T1: Rate and Pitch compound into one read increment, on a three-state commit predicate and payload v16 2026-08-02 13:52:32 -04:00
daniel 1b4d0e67b7 Loop-crossfade-ux review fixes: parked-drag no longer fakes LOOP OFF, waveform label contrast fixed, hover memoizes its bank read
Also corrects the cap-area, em-dash, glyph-overhang and heuristic-comment findings noted in review.
2026-08-02 13:52:32 -04:00
daniel 56bf26d8b6 docs: collapse Phase Gamma Wave 1 to its landed record, and correct T7's superseded status 2026-08-02 13:52:32 -04:00
daniel a7c3c7a828 Loop: an explicit enable, four named marks with grabbable caps, and the crossfade painted where it is actually heard
hasLoop becomes user-owned with the gestures as shortcuts onto it; no format change. START uses overlay/trace, not accent/primary, which is the waveform's own fill.
2026-08-02 13:52:32 -04:00
daniel 35ab59d7f9 docs: record Phase Gamma Wave 1's seven landed tracks in COMPLETED, including T6 which never had a plan entry 2026-08-02 13:52:32 -04:00
daniel fefd169d5b Merge Γ-W1-T7 re-review closeout: the cadence math follows the splice jump, and the collapse band is measured rather than assumed 2026-08-02 13:52:32 -04:00
daniel cbe2369037 Bake window: derive it from the rate the voice actually reads at, so a dialled Rate or downward Pitch no longer truncates the file 2026-08-02 13:52:31 -04:00
daniel ef59265e7a Merge Γ-W1-T7 detect findings: the agreement denominator counts probes that carried signal, so an overlapping straddle can no longer turn a two-and-two split into an accept 2026-08-02 13:52:31 -04:00
daniel f1168e16eb Close Γ-W1-T7 re-review: pitch-sync cadence math, floor-model regression check, evidence-count fix, one-home comments
New cadence-collapse-band test at P=1470 shows PSOLA eliminates the corner rather than regressing it (18.52% -> 0.00%).
2026-08-02 13:52:31 -04:00
daniel 248f2f3842 PITCH/RATE deck: Rate and Pitch knobs compounded into one read increment, on a three-state commit predicate and payload v16 2026-08-02 13:52:31 -04:00
daniel d35a55ec8e docs: correct the Gamma-W1 track count and table, and name T7 as a Rate prerequisite 2026-08-02 13:52:31 -04:00
daniel 91bd6f51a2 Period detection: silence is not dissent but an absent period is — the agreement denominator is the probes that carried signal 2026-08-02 13:52:31 -04:00
daniel cc4967d21d docs: drop the findings count from T7's open-questions bullet, it drifts as remediation lands 2026-08-02 13:52:31 -04:00
daniel 3e4ba628c3 docs: record Gamma-W1-T7 in PLAN.md, the track that landed without an entry 2026-08-02 13:52:31 -04:00
daniel 048673eb75 Merge Γ-W1-T7: Preserve's splices go pitch-synchronous — the period is detected once at load, over the loop the voice actually plays 2026-08-02 13:52:31 -04:00
daniel e7d7e70201 docs: fix stale Gamma payload-rung numbers in instrument-control-surface (v14/v15 -> v15/v16) 2026-08-02 13:52:31 -04:00
daniel 79189bd316 docs: fix stale v14 limiter rung in shell/instrument/CLAUDE.md to v15 2026-08-02 13:52:31 -04:00
daniel 9228e93750 Preserve's period detection: probes are placed by position, and a sustain loop is the span analysed 2026-08-02 13:50:14 -04:00
daniel 163ab11e05 Handle Psi's ReaperSurface::Count sentinel in decideDropClass — Gamma's exhaustive-switch gate turns it into a hard error on contact
The sentinel is not a surface, so it breaks to the existing unclassifiable-surface refusal rather than joining a real case label.
2026-08-02 13:50:14 -04:00
daniel 334022c0f1 Gamma-W1-T7: gate PSOLA's two untested wires, fix the cadence test's contradictory rationale, add a vacuity guard 2026-08-02 13:50:14 -04:00
daniel 38337229d4 docs: correct Γ's payload rungs to v15/v16/v17 after Ξ took v14
States rung one as spent rather than derivable, so following the instruction
no longer contradicts the stated number — the trap that caused the collision.
2026-08-02 13:50:14 -04:00
daniel 93230208ff Γ-W1-T7: make Preserve's splices pitch-synchronous — the jump is a whole number of the source's own period, detected once at load
30 Hz out-of-band energy 15.45% -> 0.00%; the 29 Hz rate-2.0 detune -133 -> +0 cents.
An unknown period keeps the fixed-window geometry bit for bit. The detector cannot
reach process(): sampler_core does not link it.
2026-08-02 13:50:14 -04:00
daniel f8e57a3cbd Merge Γ-W1-T2: the master bus — limiter, meter publication, and the plugin's first PDC report 2026-08-02 13:50:13 -04:00
daniel 91c1b78d5e Γ-W1-T2: the published GR meter reads the limiter, not the mute
Retire the effectiveGain blend so the meter's minimum tracks smoothGain's own
reduction against real input, unscaled by the transition mute — a toggle over
quiet material now reads no reduction instead of pinning to 0.
2026-08-02 13:50:13 -04:00
daniel 6232851c6b Γ-W1-T2: the limiter toggle is a mute, not a crossfade — the ceiling holds across both transitions
The equal-gain dry/wet blend let a peak through at (1-m) of its level. Now the
fade rides only the limited path and the hard edge lands on silence.
2026-08-02 13:50:13 -04:00
daniel 0612abbddb Γ-W1-T2 review: one restart funnel, tighter ceiling proof, effective-gain meter
Fold setLimiterEnabled's restart request into setInstrumentParams so every writer
keeps the host's latency report in sync. Pin the window-sizing identity, drop the
per-sample modulo, tighten the ceiling tolerance, publish the blended gain.
2026-08-02 13:50:13 -04:00
daniel 3baf4ee50b Γ-W1-T2: the master bus — a true-peak limiter whose ceiling is a theorem, the meter's published half, and the plugin's first PDC report 2026-08-02 13:50:13 -04:00
daniel 4fa021edae Merge Γ-W1-T5: a real Preserve time-stretcher — write rate is duration, tap rate is pitch 2026-08-02 13:47:19 -04:00
daniel 20d86d7900 Merge Γ-W1-T3: staged contour traces draw the curve their exponent defines 2026-08-02 13:47:19 -04:00
daniel abace156a5 Fix inverted splice-cadence test: assert artifact energy, not zero-crossing period
Zero-crossing counting was anti-correlated with the real defect (splice debris
fools it). Now asserts energy outside the fundamental, with an alignable control,
matching test_preserve_low_frequency.cpp's approach.
2026-08-02 13:47:19 -04:00
daniel ab3548dced Merge Γ-W1-T1: one taper, one modifier law, the 10 s stage ceiling 2026-08-02 13:47:19 -04:00
daniel f39fb1b145 Γ-W1-T3: staged contour traces draw the curve their exponent defines
New pure curve_tessellate joins the overlay's node vertices through curveMap,
one sample per pixel column; the knot no longer floats off its own trace.
2026-08-02 13:47:19 -04:00
daniel ac653aa581 Measure Preserve's splice-alignment geometry on low-frequency material
A splice can only relocate by [0.75, 1.25]*window, so periods with no multiple
in that interval never phase-align — at 50 ms, f < 16 Hz and 26.7-32 Hz.
Harness runs by hand; too slow to gate.
2026-08-02 13:47:19 -04:00
daniel 6f39d0137a Merge Γ-W1-T4: the editor floor, the width budget, and the deck row law 2026-08-02 13:47:19 -04:00
daniel a1b42ed1a8 Fix envelope-overlay knot/trace disagreement on odd pixel spans
Generalize curveMidLevel/curveFromMidLevel to curveLevelAt/curveFromLevelAt at
arbitrary phi; knotVtx and its drag inverse now read the phi a knot's truncated
x actually implies, not always 0.5.
2026-08-02 13:47:19 -04:00
daniel ae59e9b70d Γ-W1-T5 remediation: narrow the rate-bound claim, fix baseline/measurement provenance, correct §2.4 framing
Re-derives the splice-cadence inequality and adds a corner probe that FAILS at
P=500 by design, pending a ruling. Names the baseline commit and harness edit,
fixes measurement methodology, corrects the Trigger-AHD/rate coupling framing.
2026-08-02 13:47:19 -04:00
daniel 748aad3538 Merge Γ-W1-T6: exhaustive-switch gate on pure libraries 2026-08-02 13:47:19 -04:00
daniel ee8a956fbd Γ-W1-T1 review fixes: mode-independent taper rounding, sharper drag-step test, reset-sweep verifies stored fields
Swap nearbyint for std::round (MXCSR-independent); derive the finest-drag test
from the editor floor, not the knob; verify resets against fields, not norms;
record the spline-point modifier exclusion.
2026-08-02 13:47:19 -04:00
daniel 589a8e078b Γ-W1-T5: a real Preserve time-stretcher — write rate is duration, tap rate is pitch
Generalizes the correlation-aligned SOLA delay line so the feed and the shift are
independent rates over one ring. Unity is bit-identical to the shipped read, asserted
against a hash baseline captured pre-change.
2026-08-02 13:47:19 -04:00
daniel 3eb72d01c4 One taper, one modifier law: extract param_taper, raise the stage ceiling to 10 s, and make the AHDSR schematic axis the taper itself 2026-08-02 13:47:19 -04:00
daniel ae54ca8128 Re-derive the floor-size test fixtures from the constants and move the ceiling to sample_bands.h 2026-08-02 13:47:18 -04:00
daniel 69e2f1d3e3 Promote switch-exhaustiveness diagnostic to an error on pure libraries (MSVC + GCC/Clang)
MSVC's C4062 is off by default and GCC/Clang's -Wswitch only warns without
-Werror; this repo sets no -Wall/-Werror anywhere. /we4062 and -Werror=switch
now cover both, scoped to pure libraries only.
2026-08-02 13:47:18 -04:00
daniel abb27f08f2 Raise the editor floor to 1190x680, derived from the deck's declared width budget, and make row membership a property of the group 2026-08-02 13:47:18 -04:00
daniel e589addc54 Merge bake diagnosis soundness: every printed claim backed by an observation, write proof only where evidence crosses the plugin boundary 2026-08-02 13:45:38 -04:00
daniel 1c8709e82d Take the read-back back out of the persist; a write verdict belongs only where evidence crosses the plugin boundary
Its false gated six undo points, so an unverified byte-equality assumption could have silently removed Ctrl-Z for a bank mutation that landed.
2026-08-02 13:42:51 -04:00
daniel 25390d5253 Prove every ext-state write by reading the key back, so no guard is constant-true
SetProjExtState's return describes the whole extname. The persist and the instrument's publish now re-read their key; both refusals can finally fire.
2026-08-02 13:14:49 -04:00
daniel 2cb0b52884 docs: correct two false claims in the Phase Ε spec
REAPER's GetUserFileName serves both pickers — the no-save-picker finding was a
regex miss. A new enum value is structural, not additive: BankModel rejects an
out-of-range SourceMode/Tier rather than degrading.
2026-08-02 12:38:41 -04:00
daniel 0afb885987 Make a bake's Banked landing reachable only through the persist upgrade
The dedup path claimed it directly, so a key could be answered Ok pointing at an entry a failed persist never wrote. Write-back is now guarded and three-valued, and landing one request split out of the scan pass.
2026-08-02 12:35:06 -04:00
daniel 1800bd64c3 Prove the bake's answer writes by reading the key back
SetProjExtState's return covers the whole extname, so it never saw one key. The persist verdict now reaches the report, and a throw mid-write no longer claims the landing left nothing behind.
2026-08-02 12:00:34 -04:00
daniel 6cabbd0dd4 Fix the bake scan report's unsound absence-as-signal claim
Gate the summary on any unanswered key and on SetProjExtState's return, print one line per scanned key, and make the undo block stack RAII.
2026-08-02 08:34:59 -04:00
daniel 2f8e88880e Merge bake-answer diagnosis: five named failure modes and a scan report that says what the landing saw 2026-08-02 08:06:45 -04:00
daniel 4abeace925 Merge capture-bounds diagnosis: empirical tolerance, unmeasurable-render refusal, refused renders kept for inspection 2026-08-02 08:06:35 -04:00
daniel 41ca833b86 bake: make the landing scan say what it saw, so a no-answer names its own cause
Splits Ignore into unreadable vs not-a-request and counts every verdict; the report prints only when the pass answered nobody, so its absence proves the action never ran.
2026-08-02 08:00:19 -04:00
daniel 0511d16d4f capture: close batch-quarantine silence, 0-byte asymmetry, and round-two doc overclaims
Batch captures now name the retained-render folder once instead of nothing; Auto/Manual tail modes refuse a 0-byte render like None does; VERIFICATION.md steps 1-3 no longer invite a false conclusion; docs/comments no longer overclaim.
2026-08-02 08:00:12 -04:00
daniel ef0da893b5 docs: add Phase Λ (Linux port) to PLAN.md
Adds the Phase Λ entry: six settled rulings, four open forks, and thirteen tracks across seven waves, from docs/product/linux-readiness.md. Adds the l slug transliteration, and scopes the plan-wide "nothing unanswered" claim, which Λ's open forks break.
2026-08-02 07:52:57 -04:00
daniel c037aa1cb6 docs: rule Phase Rho's three forks
Refuse multi-track; result track always Arrange; follow panel tail. Rho-F2 overrides the mode-following framing: explicit Arrange tags on track and item, plus an explicit-tag-wins filter in detectNewContent.
2026-08-02 07:40:01 -04:00
daniel 734672ba0e docs: scope Phase Λ, the Linux port
Product doc for the extension + ReaSampler 9000 on Linux, downstream of the two Λ-W1 audits: Daniel's six rulings, seven waves, the non-REAPER-host safety contract, and four open forks.
2026-08-02 07:26:55 -04:00
daniel 2005f90c66 capture: state the bounds tolerance as empirical, refuse unmeasurable renders, keep refused ones for diagnosis
The one-frame bound is not provable for a per-edge renderer; the test now shows where it breaks. Refused renders move out of the bank instead of being deleted, so the DAW experiment has something to read.
2026-08-02 07:23:30 -04:00
daniel 61e90af547 docs: record Phase Ε fork rulings in the plan
Ε-F1 proprietary RSBK, Ε-F2 new bank with auto-suffix, Ε-F3 refuse on a
degraded ledger. No Ε track is gated now. Also carries Phase Ρ's plan
sections, authored concurrently in this shared checkout.
2026-08-02 07:06:23 -04:00
daniel 461351ee02 docs: frame Phase Rho — render in place
Product notes for rendering a track's output to a new sibling track at the exact render position, source parked in Design mode, bank never touched. Framed as a third verb (arrange->arrange), not an exception to capture/placement separation. Three open forks.
2026-08-02 07:05:33 -04:00
daniel 52394fa08f docs: fold Daniel's three Phase Ε rulings into the product doc
Ε-F1 proprietary RSBK; Ε-F2 always a new bank with an auto suffix; Ε-F3
refuse import on a degraded ledger.
2026-08-02 06:58:04 -04:00
daniel 7f3b00a646 fix: bake-answer messages stop asserting causes the classifier can't see
Rewords Cleared/Unanswered/ForeignRequest to name only observed facts and every live hypothesis instead of picking a winner; adds a guarded answeredOutcome accessor against a future unhandled BakeAnswerKind; folds an unreachable BakeScanKey/Context test state; fixes generation-stamp timing.
2026-08-02 06:57:08 -04:00
daniel 7f040dd934 Merge Λ-W1-T2: Linux source/runtime portability audit 2026-08-02 06:53:54 -04:00
daniel 47065a19bb Merge Λ-W1-T1: Linux build/toolchain readiness audit 2026-08-02 06:53:51 -04:00
daniel b1726b0ad3 Fix audit citations, counts, and the L2-07/L2-09 mechanisms after code-review verification 2026-08-02 06:39:36 -04:00
daniel f57bf4fb6d docs: fix audit citations — bad line ranges, misattributed evidence, overclaimed severity
Corrects a false unguarded-include claim, re-scopes hot-path evidence to what's actually linked, replaces a nonexistent Fork-A collision scenario, fixes several miscounted TUs/libraries, re-grades two Fork-B items from Blocker to Major/non-blocker, and adds missing owners/done-conditions.
2026-08-02 06:39:31 -04:00
daniel 962ab64ef0 bake: name the five ways the extension can fail to answer, and move the landing verdict into a pure, tab-provable classifier
A no-answer stays a failure; it now says whether the extension never ran the landing, answered a stale generation, spoke a wire this build cannot read, cleared the request, or refused it.
2026-08-02 06:38:04 -04:00
daniel a91df760cc capture: name the render source in the exact-bounds refusal, and put its one-frame tolerance under test
The tolerance is unchanged and now derived, not assumed: frameCountFor lands in {floor(L), ceil(L)}, so a non-frame-aligned window can never miss by more than a frame. Naming the source is what tells a self-bounding render from a short one.
2026-08-02 06:37:40 -04:00
daniel 86c3c7f3b8 docs: spec Phase Ε — bank export/import as a version-tagged package
Adds docs/product/bank-package.md and the Phase Ε spec in docs/PLAN.md:
three waves, six tracks. Three forks open; Ε-F1 blocks Ε-W1-T1.
2026-08-02 06:32:07 -04:00
daniel 893455594f docs: audit source/runtime Linux-portability for extension and VST3 instrument
Two one-line compile blockers, a locale hazard in the persisted number codec, and a cost split showing the extension is nearly there while the instrument editor is a from-scratch X11 job.
2026-08-02 06:07:28 -04:00
daniel 5455b1047b docs: audit the Linux build/toolchain gap ahead of Phase Λ 2026-08-02 06:07:20 -04:00
daniel 6e937b9c61 docs: add a DAW verification checklist
Checks for post-1.0 work that no unit test can close, ordered by risk. Each item cites the obligation it discharges.
2026-08-02 04:32:29 -04:00
daniel 92f0aa209d Merge release 1.4.0 hygiene: AGPL v3 license, version bump, repo cleanup 2026-08-02 04:16:38 -04:00
daniel 19e28b02c3 docs: rewrite README against the landed tree
Overview, artifacts, prerequisites, platform support, setup, build/test, install, and repo layout, matching current CMake targets and channel support.
2026-08-02 04:15:41 -04:00
daniel ca43eb76d4 Update CLion project config 2026-08-02 04:10:20 -04:00
daniel 4fca140ace Untrack .idea/ ahead of the public push
Files stay on disk; the directory is now ignored.
2026-08-02 04:05:33 -04:00
daniel 573e878cbd Release 1.4.0 hygiene: license, version bump, drop scratch DSP
Add AGPL v3 LICENSE, bump version to 1.4.0, remove unreferenced non-compiling temp_cortex/ limiter scratch files, and extend .gitignore for .idea/, AGENTS.md, and cmake-build-* dirs.
2026-08-02 04:04:17 -04:00
daniel 194c2392cf Merge Phase Ψ — the extension trust pass: exact bounds, disjoint solo surfaces, reachable actions, honest drops, real names, true mono 2026-08-01 23:40:32 -04:00
daniel a4aeb4f6ab Merge dev into phase-psi: take Ξ-W3 before Ψ lands
# Conflicts:
#	docs/COMPLETED.md
#	docs/TODO.md
2026-08-01 23:39:24 -04:00
daniel 0f870b1337 docs: collapse Phase Ψ's landed track specs, and record Ψ-W3 — the wave a review finding opened 2026-08-01 23:32:25 -04:00
daniel a3a9c91256 docs: record Phase Ψ's seven landed tracks, and that none of them is DAW-verified yet 2026-08-01 23:22:06 -04:00
daniel a21a6176e8 Merge Ψ-W3: refuse every multi-track selected-tracks render, both scopes 2026-08-01 23:01:56 -04:00
daniel 2a9ab65944 Ψ-W3 remediation: fix the verify doc's wrong render source, add missing content checks, soften unverified claims
Corrected the Render-dialog source name the refusal's evidence depends on, added a by-ear content check and a file-size channel proxy, and stopped two comments from overclaiming.
2026-08-01 23:01:50 -04:00
daniel f69c4bf6bf Refuse every multi-track selected-tracks render, both scopes; make a failed mono collapse observable 2026-08-01 22:40:54 -04:00
daniel 6e6f4a6a15 Merge Ψ-W2-T2: a bit-identical capture collapses to one lossless mono channel
# Conflicts:
#	src/shell/capture/CLAUDE.md
#	src/shell/capture/capture.cpp
#	src/shell/capture/capture.h
2026-08-01 22:23:06 -04:00
daniel 91f3ffb09e Merge Ψ-W2-T1: captures named after their source track, surfaced on the panel card 2026-08-01 22:16:20 -04:00
daniel 8b191e3379 Ψ-W2-T2 remediation: atomic temp+rename collapse write, honest unknown-channel fallback, [verify — DAW] markers, corrected+filed bake-collapse deferral, observable collapse message, quiet-NaN test 2026-08-01 22:08:39 -04:00
daniel 0feb32d59b Ψ-W2-T1 remediation: scrim the card name over the waveform, hedge two SDK claims, fix a UTF-8-truncation empty-label bug, file the legibility DAW deferral 2026-08-01 22:08:35 -04:00
daniel 4fa3c1dd15 Ψ-W2-T2: collapse a capture whose channels are bit-identical to one lossless mono channel, index value measured off the landed file 2026-08-01 21:46:55 -04:00
daniel 3278b4eced Name captures after their source track: label and filename both, on every interactive mint site, and show the name on the panel card 2026-08-01 21:46:53 -04:00
daniel 4bdbbe0517 docs: close Phase Ξ — the popup abandoned by ruling, the bake window derives itself, and Γ's rung ladder shifts to v15 2026-08-01 21:44:05 -04:00
daniel 178cca3c25 Merge Ξ-W3-T1: the bake window derives itself — Hold is the one knob a sustain loop needs, and three truncations are gone 2026-08-01 21:34:10 -04:00
daniel eb6093e085 Close derived-bake-window review findings: NaN-guard remaining wire doubles, pin Trigger-span agreement, retire dead quantizer
Guards params_payload.cpp's filter-tail seconds and both keyTrack sites against NaN; pins Voice::start's Trigger-span formula against trigger_seam; retires unused shortestDivisionAtLeast.
2026-08-01 21:32:05 -04:00
daniel 09d64c9f46 Merge Ψ-W1-T1: a ranged item capture renders the window, with children and receives silenced for it
# Conflicts:
#	docs/TODO.md
#	src/app/CMakeLists.txt
2026-08-01 21:25:37 -04:00
daniel a0220e8c57 Ψ-W1-T1 second-round remediation: ±1-frame bounds tolerance, self-cleanup a refused render, hedge two unverified render-source inferences
Loosens the exact-bounds gate against REAPER's edge rounding; deletes the bytes a BoundsMismatch refusal writes, per prune_fs's self-cleanup carve-out.
2026-08-01 21:18:03 -04:00
daniel 65f6070348 Bake window: derived note lengths carry exact durations, not ladder rungs — a long take is no longer cut at 384 beats
Hold keeps its picker. Also: one home for the %-fold, duration-ordered Hold travel, and a corrupt tail degrades to absent rather than fabricating one.
2026-08-01 21:10:38 -04:00
daniel 7dc80e7a4f capture: refuse the multi-track ranged item render, silence the track's children and receives for it, and gate every exact-bounds capture on its frame count 2026-08-01 20:58:33 -04:00
daniel a0f9a23711 Merge Ψ-W1-T4: resolve drop targets per move, not once
# Conflicts:
#	src/shell/actions/CLAUDE.md
2026-08-01 20:57:55 -04:00
daniel 1044f5418f Merge Ψ-W1-T3: publish the Media Explorer import into the Media Explorer action section as well as Main 2026-08-01 20:37:30 -04:00
daniel 148d8a9e06 Merge Ψ-W1-T2: disjoint per-mode solo surfaces and a playback-gated mode switch 2026-08-01 20:37:24 -04:00
daniel 19aeb92775 Bake window derives itself: %-knob fold, declick pad, Gate held to exhaustion, preview velocity; Hold is the one knob a loop needs 2026-08-01 20:26:04 -04:00
daniel 9d10f151da Ψ-W1-T4 remediation: gate silent arrange drops, pin surface totality, hedge unverified SDK claims, close comment/exception-safety minors 2026-08-01 20:13:17 -04:00
daniel d589b99705 Ψ-W1-T3 review remediation: soften the double-fire claim to unspecified-by-SDK, mark the unload mirror [verify — DAW], fix stale comment, drop redundant assertions, dedupe hook-partitioning comments, drop what-comment; file the action_registry test-seam deferral. 2026-08-01 20:13:13 -04:00
daniel f2cdf676f3 Ψ-W1-T2 review remediation: solo restore drops on visible-in-target, not parked; N-mode segments read dead when unroutable
Fixes a hidden-parent solo replay that could silence the mix. Also closes the N-mode segment silent no-op, amends the invariant comment, trims view.cpp under 600 lines, hedges two SDK inferences, drops a dead null-check.
2026-08-01 20:13:10 -04:00
daniel fe3ac79ab5 Ψ-W1-T4: resolve drop targets per move, not once — every surface gets a defined outcome, a cue, and no silent no-op 2026-08-01 19:43:37 -04:00
daniel 72b870459c Publish the Media Explorer import into REAPER's Media Explorer action section as well as Main — custom_action + hookcommand2, second forever-stable id, one handler. 2026-08-01 19:43:27 -04:00
daniel 9c234c2e6b Ψ-W1-T2: disjoint per-mode solo surfaces and a playback-gated mode switch
Solo is cached, cleared and replayed per mode on a real switch only; the switch is refused visibly while the transport runs. The footer segment now routes through the activate actions, so a panel switch finally persists.
2026-08-01 19:43:18 -04:00
daniel 5e3ea6c851 capture: render a ranged item capture time-bounded — the selected-items source can't narrow a window, only a full-extent one uses it
sourceModeForScope now takes the item extent vs. the requested window. Full-extent item captures and the batch keep the old path unchanged.
2026-08-01 19:43:06 -04:00
daniel d3894dae6d test: audit the derived bake window end to end — two truncations pinned, Gate's missing hold length demonstrated 2026-08-01 19:38:28 -04:00
daniel 8bf6841f7b docs: spec Phase Ψ — the extension trust pass, seven items across two waves, six tracks, three scheduled invariant amendments 2026-08-01 19:01:01 -04:00
daniel 0a7778b396 docs: close Γ-F7 to signal-flow order and spec real units at the host boundary
The 44-id table stated in full. Adds the plain-value layer, a per-category
unit/precision table, the one-formatter invariant, a stepCount sweep, and the
filter read-side resolution.
2026-08-01 18:18:09 -04:00
daniel 9f17df1420 docs: record Ξ-W2-T1, the resample bake chain, and file its two deferrals 2026-08-01 18:11:46 -04:00
daniel 7ecb3aa470 Merge Ξ-W2-T1: the resample bake chain — the instrument renders the dialed sound, the extension banks it, one click re-points and resets 2026-08-01 18:05:06 -04:00
daniel 2fa55658c1 docs: schedule VST3 parameters into Phase Γ
Automation ships as Γ-W4; the stage ceiling goes to 10 s in W1-T1 ahead of the
one-way door; a new Γ-W3-T2 corrects Ξ's bake reset list. Four waves, ten tracks.
Opens Γ-F7 on parameter order.
2026-08-01 17:26:18 -04:00
daniel a09e45fc1d Ξ-W2-T1 re-review cleanup: soften ordering claim, bound bake guard fields, dedup gain/play-mode rationale, quiet foreign WrongProject noise 2026-08-01 17:23:00 -04:00
daniel 39c2d1cdb4 Ξ-W2-T1 remediation: print master gain into the bake, derive the window from the dialed sound, reset play mode to Trigger 2026-08-01 17:05:28 -04:00
daniel 256216d670 docs: close Γ-F6 and resequence Phase Γ into three waves
Dynamic latency ships as ruled; the restart cost is re-attributed to our own
setActive and filed in TODO. The reflow splits canvas (W1-T4) from arrangement
(W3-T1); preserve-time-stretch moves to W1-T5.
2026-08-01 16:51:04 -04:00
daniel eb777f55e1 docs: spec Phase Γ — the instrument's control surface
Two-row deck reflow (sound/contour), double-height MASTER with limiter and
meter, PITCH/RATE deck, unit-driven knob law, contour-trace fix, and a
re-approached loop/crossfade UX. Folds rulings Γ-F1..Γ-F5; opens Γ-F6.
2026-08-01 16:29:32 -04:00
daniel 60308a3655 Ξ-W2-T1: the resample bake chain — instrument renders, extension banks, one click re-points and resets 2026-08-01 16:26:28 -04:00
daniel 6c982cd617 docs: record Θ-W7, the arc-and-spline antialiasing fix, and file the scaled-fallback deferral 2026-08-01 15:18:59 -04:00
daniel 806a3037a3 Merge Θ-W7-T1: analytic AA stroker for arcs, needles, and spline curves — opaque core and angle-independent weight, replacing LICE_Arc and ThickFLine on the editor's radial and curve surfaces 2026-08-01 15:12:07 -04:00
daniel 704b7ef373 fix: enlarge every sub-2px stroker width to 2px, per Daniel's ruling
Knob track arc, inner-dial needle, and mini velocity-trace all sat below the analytic stroker's opaque-core floor. Raised to 2px; updated visual-design-language.md and core/ui/CLAUDE.md to match; kept the 1px-behavior test, corrected its stale comment.
2026-08-01 15:11:58 -04:00
daniel 3ad30942a7 temp-cortex limiter dump 2026-08-01 15:09:30 -04:00
daniel 07628a2059 fix: close Θ-W7-T1 round-2 leftovers — NaN guard placement, comment attribution, CLAUDE.md export
Moves the NaN/Inf finiteness check to addSegment where the UB-causing cast actually happens, makes strokeBounds reject an interior non-finite point instead of swallowing it, corrects a LICE_GetPixel misattribution, and documents rasterRowOffset.
2026-08-01 13:59:09 -04:00
daniel 3fb77027c6 fix: close Θ-W7-T1 review — scaling guard, opacity claims, two vacuous test fixes
Guards the stroke blend against LICE_EXT_GET_SCALING, tightens the analytic-stroker's boxes and NaN handling, corrects the opaque-core threshold and inner-dial rationale in the docs, and re-derives two review-flagged tautological tests so they actually fail against the bugs they claim to catch.
2026-08-01 13:45:43 -04:00
daniel 2e09776342 fix: stroke arcs and splines analytically — opaque core, angle-independent weight
LICE_Arc never reaches opacity and ThickFLine's width is minor-axis. One
distance-to-polyline coverage mask, blended once, replaces both.
2026-08-01 13:18:21 -04:00
daniel ae9019465e docs: close out Θ-W6 and Phase Θ, and file two legibility-pass deferrals 2026-08-01 10:36:22 -04:00
daniel 7504eefb59 Merge Θ-W6-T1: editor legibility — bigger knobs and labels, ms time constants, per-ring double-click reset, and an antialiasing pass over every drawn surface 2026-08-01 10:29:00 -04:00
daniel d445cfdae3 test: tighten waveform-collapse and knob-face rect assertions
Height-3 case pins the halfSpan clamp itself (height-4 passed pre-fix too); dropped the vacuous tall-rect mirror since min() is symmetric and wide already discriminates.
2026-08-01 10:07:47 -04:00
daniel 47f2a063e7 fix: close five Θ-W6-T1 review minors — headroom figure, knob-face radius, degenerate band clamp
Aligns inKnobFace's hit radius with computeKnob's draw-side min(w,h) rule and adds a non-square-rect test; clamps halfSpan for degenerate waveform bands with a test; fixes stale docs/comments and annotates an uncommitted perf measurement.
2026-08-01 10:01:40 -04:00
daniel ca464397b2 fix: restore waveform symmetry about the midline, cut deck_values' link to the bank model, and unit-test the column arithmetic
The waveform column's vertical extents move to pure component_geometry so the shared
primitive stops being untested; PlaySeconds hoists into a header-only play_seconds target.
2026-08-01 09:47:07 -04:00
daniel 7f74b11dce feat: legible ReaSampler 9000 editor — bigger knobs, ms time constants, per-ring double-click reset, and an antialiased draw pass 2026-08-01 09:16:30 -04:00
daniel 213ecfafe6 docs: close out Θ-W5, and record two spline-overlay UX deferrals
Collapse Θ-W5 to wave-level in PLAN.md, append its narrative to COMPLETED.md, fix a stale resolvePlay reference in core/instrument/CLAUDE.md, and file the drag-off-margin and AttackEnd/Origin shadow warts in TODO.md.
2026-08-01 00:29:40 -04:00
daniel 85cf34f858 Merge Θ-W5-T1: spline EGs — a free-drawn contour alternative to every staged envelope, hard points on the one shared spline, and a deck that redistributes reserved cell width 2026-08-01 00:19:35 -04:00
daniel aedcc6976c fix: pin the waveform arbitration in a testable predicate, close round-4 review minors
Extracts resolveWaveformClaim (core/instrument/ui/spline_edit) so the shell's node/tab/marker click resolution is unit-tested directly, not just its input geometry; folds the staged-envelope node into it; fixes comment accuracy, a cost regression, and test fidelity issues.
2026-08-01 00:17:06 -04:00
daniel 757e1585d6 fix: close round-3 review findings — smallest-target-first, residue test fix, extraction
Waveform overlay now resolves node/tab/marker click collisions by target area instead of check order; residue test now uses a distinguishing fixture; Gate-unavailable-while-drawn logic extracted to one pure helper shared by resolvePlay and applyControl.
2026-07-31 23:44:05 -04:00
daniel c3d67bc3da fix: close round-2 review findings — Critical silent-note bug plus majors/minors
Fixes the 2-point spline-EG early-free bug causing silent fade-ins, the pitch/filter enable-toggle Trigger-forcing hole, the contour-node/marker pixel shadow, missing deck-residue test coverage, and stale comments in knob_deck and spline_edit.
2026-07-31 23:12:08 -04:00
daniel d8ffd860d1 instrument: a deck group's reserved cell width goes to the cells present
A Trigger face dropping Sustain and Release now gets wider cells instead of
144 px of dead slots. Group widths, row packing and Gate are untouched.
2026-07-31 22:43:13 -04:00
daniel 1c774226d3 fix: close review findings on spline EGs — engine, codec, and popup/overlay UI grammar
Live pitch depth, Gate/Spline enable-rule agreement, inert kTrigLength, NaN wire guards, hard-flag-tail corruption no longer wipes the record, RT/cold spline tie-break, retired alt-click, marker-shadow fix, plus new test coverage.
2026-07-31 22:27:41 -04:00
daniel e44bd42dd9 instrument: spline EGs — hard points on the one shared spline, a drawn contour per envelope beside its staged state, payload v13 2026-07-31 21:33:59 -04:00
daniel f115904e4f docs: close out wave Theta-W4, and defer the deck layout rework to TODO 2026-07-31 20:31:53 -04:00
daniel a32ab4b5b2 Merge pth-w4-t2-velocity-deck-and-bipolar-curves: one VELOCITY deck, bipolar pitch and filter curves multiplying their depth knobs, and a drawn preview glyph 2026-07-31 20:27:56 -04:00
daniel 5e290119c5 instrument: the filter's velocity depth knob returns and multiplies the bipolar curve; the pre-v12 lift is a pure domain re-tag 2026-07-31 20:24:40 -04:00
daniel cfb53aade3 fix: close review findings on the velocity-curve deck and bipolar curves
Cancels the curve-node drag whenever the popup closes so Esc mid-drag can't alias the amp curve; generalizes CurveTarget routing to one switch; fixes stale/overstated comments; clamps a pre-v12 depth fold; adds deck-inertness and filter-fold test coverage.
2026-07-31 19:46:37 -04:00
daniel 9d38f87a2d instrument: one VELOCITY deck for all three velocity curves, bipolar and off by default for pitch and filter
Payload v12 appends the new velocity->pitch curve and folds the retired filter velAmount into its now-bipolar curve, so pre-v12 projects reopen sounding identical. Preview button takes a drawn play triangle.
2026-07-31 19:15:17 -04:00
daniel 4fecb58c0a docs: close out Theta-W4-T1 into COMPLETED, collapse the T1 spec, and record the frames-not-ms crossfade ruling 2026-07-31 18:33:23 -04:00
daniel 7261f0f6a8 Merge pth-w4-t1-gate-loop-sustain: Gate-mode loop sustain with a crossfaded seam, and the loop handles unshadowed 2026-07-31 18:29:14 -04:00
daniel 3cb22e984d loop: fix the crossfade seam's residual discontinuity, plus six review minors
Normalizes crossfadeWeight over crossfade-1 so the last rendered frame lands at exactly the incoming tap instead of a residual step; corrects the CLAUDE.md invariant and seam test to match. Shares lerpSource/crossfadedSource/maxCrossfade, fixes stale docs/constants, and clears crossfade on the loop-OFF gesture.
2026-07-31 17:59:58 -04:00
daniel 0fe4166d7d loop: crossfade the Gate sustain seam, and unshadow the loop handles that made loop points look gone 2026-07-31 17:36:36 -04:00
daniel a90ccd9a00 docs: record the palette rework and retire the overlay-contrast wart it resolved 2026-07-31 16:52:44 -04:00
daniel 1307007b91 Merge palette-darker-teal: deep-teal secondary, an owned spectral mid, and an overlay trace that clears the indicator floor 2026-07-31 16:46:56 -04:00
daniel a19d645a49 palette: enlarge the region title into WCAG large class; repoint the grabbed envelope handle off hue
Corrects theme.h's large-text thresholds, names accent/secondary's real
binding limiter, and adds compositeOver so the loop-span fill's 2.25:1
under-floor pair is asserted rather than assumed.
2026-07-31 14:07:01 -04:00
daniel 91f71f92bd palette: give the spectral mid and the envelope trace their own roles
Decouples the keyboard strip's mid stop from accent/secondary, which the
deep-teal darkening had inverted. Adds overlay/trace (#816AA6), the first
value to clear 3:1 against the waveform. Replaces the frozen-premise test.
2026-07-31 13:27:20 -04:00
daniel e1e668a521 docs: close out Θ-W3-T2 into COMPLETED, collapse the W3 wave, and record the overlay contrast wart as open 2026-07-31 13:20:33 -04:00
daniel 87754477a7 Merge Θ-W3-T2: one staged-envelope system — per-segment curves, the sustain-less AHD, and one overlay shared by all three envelopes 2026-07-31 13:11:12 -04:00
daniel 04e4f875af instrument: reassign loop-marker role off tertiary, onto secondary
Loop span/markers and the envelope overlay trace shared tertiary purple in the same
overlay rect. Loop markers now draw secondary; envelope overlay keeps tertiary.
Adds a theme-level distinctness regression guard.
2026-07-31 12:40:15 -04:00
daniel 03fb471c92 instrument: fix AHD DecayEnd overlay/grab defect, pin flaky curve test, close comment/doc findings 2026-07-31 10:19:45 -04:00
daniel 2fa1405b06 instrument: fix AHD node-tracking/tie-break/live-latch defects and close staged-envelope-curve test gaps 2026-07-31 09:52:17 -04:00
daniel d60ab1524a instrument: latch the note done at the read-head run-off, fit the migrated fades, and lift the curve dial and overlay selection into pure modules 2026-07-31 09:17:04 -04:00
daniel 13e8c5c4d9 instrument: one staged-envelope system — per-segment curves, the sustain-less AHD, and a shared overlay for all three envelopes
Trigger's fade pair folds into the AHD (and goes live); the release anchors right;
Preserve rings its synthetic tail out instead of cutting it. Payload v10.
2026-07-31 08:37:57 -04:00
daniel 87d7ceb066 docs: close out Ξ-W1-T1, Ξ-W1-T2 and Θ-W3-T1 into COMPLETED; map the note directory; document the Release build 2026-07-31 07:02:54 -04:00
daniel 98594df878 Merge Θ-W3-T1: live parameter delivery to sounding voices, holding normalized stage position across time edits 2026-07-31 06:44:04 -04:00
daniel 8dc76f4a1f Merge Ξ-W1-T2: the programmed capture-signal model, its domain closed at construction 2026-07-31 06:44:00 -04:00
daniel 60aeda1a3e Merge Ξ-W1-T1: one tracking ledger and one authority behind prune protection and replace-vs-add 2026-07-31 06:43:54 -04:00
daniel efd1e41f46 instrument: narrow the live-param publish lock to its own mutex, off the reload's decode
Knob-drag publishes no longer block behind a full reload's WAV decode — a dedicated livePublishMutex_ replaces reloadMutex_ for the seqlock's single-writer contract. Also fixes an editor comment overclaim and two doc restatements.
2026-07-30 21:54:20 -04:00
daniel bbc7dc70bb instrument: snap live params onto a fresh voice, roll a live drag back on capture loss, serialize the seqlock's two writers 2026-07-30 21:39:56 -04:00
daniel 1dade0bfcf instrument: deliver continuous playback params live to sounding voices via a seqlock block, holding normalized stage position across time edits 2026-07-30 21:03:05 -04:00
daniel dddecc5734 note: close out the model — correct an inert mutation claim, retag four non-discriminating assertions, assert Tempo's closure, fix three doc/test accuracy gaps
No behavior change; verification-record corrections and one static_assert.
2026-07-30 21:03:02 -04:00
daniel a80eb76c1f note: close every value type's domain at construction, so resolveNote is finite for every constructible input
Division and OffsetAmount get single normalizing doors and private constructors; fromBpm validates by running the conversions rather than their reciprocal. Readers drop their re-clamps and default labels.
2026-07-30 20:37:12 -04:00
daniel 6287534454 fix: classify future-version ledgers with changed record shape correctly, not as corrupt
Version-check now runs on the parseLedger failure path too, so a v3 blob whose record shape actually changed reports FutureVersion instead of Unreadable, avoiding the corrupt-blob "clear it" advice. Also closes the six minor findings.
2026-07-30 20:25:46 -04:00
daniel d923b352ae fix: harden note-program model against corrupt tempo/division/denomination records
Reject subnormal BPM that overflows to NaN, normalize Division equality, pin a single out-of-range-denomination interpretation across all readers, flag collapsed capture windows, add offset off-view editors and structural static_asserts, collapse duplicated CLAUDE.md facts.
2026-07-30 20:11:06 -04:00
daniel 45b87dc2ff tracking: read the ledger's version, not just write it; clear owned on any block; channel-correct prune recovery 2026-07-30 20:11:05 -04:00
daniel 834a6ddcc7 note: land the programmed capture-signal model — division ladder, tempo resolution, anchored offsets, one record and one resolver 2026-07-30 19:44:15 -04:00
daniel 7f70d94228 tracking: one ledger, one authority — prune protection and replace-vs-add answered from the same records, fail-safe on unreadable state 2026-07-30 19:44:11 -04:00
464 changed files with 69536 additions and 6814 deletions
+1
View File
@@ -0,0 +1 @@
*.rsbank binary
+3 -1
View File
@@ -1,10 +1,12 @@
/build/
/build-beta/
/.claude/worktrees/
/.idea/ctestState.xml
/.idea/
*.dll
*.dylib
*.so
*.o
*.obj
.DS_Store
/AGENTS.md
cmake-build-*/
-10
View File
@@ -1,10 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
Generated
-1
View File
@@ -1 +0,0 @@
reaper_mpeview
-350
View File
@@ -1,350 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="BackendCodeEditorSettings">
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CDeclarationWithImplicitIntType/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CommentTypo/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=ConstevalIfIsAlwaysConstant/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppAbstractClassWithoutSpecifier/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppAbstractFinalClass/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppAbstractVirtualFunctionCallInCtor/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppAccessSpecifierWithNoDeclarations/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppAwaiterTypeIsNotClass/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBooleanIncrementExpression/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBoostFormatBadCode/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBoostFormatLegacyCode/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBoostFormatMixedArgs/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBoostFormatTooFewArgs/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBoostFormatTooManyArgs/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppCStyleCast/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppCVQualifierCanNotBeAppliedToReference/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassCanBeFinal/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassIsIncomplete/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassNeedsConstructorBecauseOfUninitializedMember/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppCompileTimeConstantCanBeReplacedWithBooleanConstant/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppConceptNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppConditionalExpressionCanBeSimplified/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppConstParameterInDeclaration/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppConstValueFunctionReturnType/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppConstexprIfDiscardedBranch/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppCoroutineCallResolveError/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAArrayIndexOutOfBounds/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAConstantConditions/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAConstantFunctionResult/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAConstantParameter/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFADeletedPointer/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAEndlessLoop/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAInfiniteRecursion/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAInvalidatedMemory/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFALocalValueEscapesFunction/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFALocalValueEscapesScope/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFALoopConditionNotUpdated/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAMemoryLeak/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFANotInitializedField/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFANullDereference/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFATimeOver/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAUnreachableCode/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAUnreachableFunctionCall/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAUnreadVariable/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDFAUnusedValue/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeclarationHidesLocal/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeclarationHidesUncapturedLocal/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeclarationSpecifierWithoutDeclarators/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeclaratorDisambiguatedAsFunction/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeclaratorNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeclaratorUsedBeforeInitialization/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultCaseNotHandledInSwitchStatement/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultInitializationWithNoUserConstructor/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultIsUsedAsIdentifier/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultedSpecialMemberFunctionIsImplicitlyDeleted/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefinitionsOrder/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeletingVoidPointer/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDependentTemplateWithoutTemplateKeyword/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDependentTypeWithoutTypenameKeyword/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeprecatedEntity/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeprecatedOverridenMethod/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeprecatedRegisterStorageClassSpecifier/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDereferenceOperatorLimitExceeded/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDiscardedPostfixOperatorResult/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDoxygenSyntaxError/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDoxygenUndocumentedParameter/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDoxygenUnresolvedReference/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEmptyDeclaration/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceCVQualifiersOrder/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceCVQualifiersPlacement/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceDoStatementBraces/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceForStatementBraces/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceFunctionDeclarationStyle/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceIfStatementBraces/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceNestedNamespacesStyle/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceOverridingDestructorStyle/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceOverridingFunctionStyle/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceTypeAliasCodeStyle/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnforceWhileStatementBraces/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEntityAssignedButNoRead/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEntityUsedOnlyInUnevaluatedContext/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEnumeratorNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEqualOperandsInBinaryExpression/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppEvaluationFailure/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppExplicitSpecializationInNonNamespaceScope/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppExpressionWithoutSideEffects/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppFinalFunctionInFinalClass/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppFinalNonOverridingVirtualFunction/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppForLoopCanBeReplacedWithWhile/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppForwardEnumDeclarationWithoutUnderlyingType/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppFunctionDoesntReturnValue/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppFunctionIsNotImplemented/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppFunctionResultShouldBeUsed/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppFunctionalStyleCast/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppHeaderHasBeenAlreadyIncluded/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppHiddenFunction/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppHidingFunction/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppIdenticalOperandsInBinaryExpression/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppIfCanBeReplacedByConstexprIf/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppImplicitDefaultConstructorNotAvailable/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppIncompatiblePointerConversion/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppIncompleteSwitchStatement/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppInconsistentNaming/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppIntegralToPointerConversion/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppInvalidLineContinuation/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppJoinDeclarationAndAssignment/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppLambdaCaptureNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppLocalVariableMayBeConst/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppLocalVariableMightNotBeInitialized/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppLocalVariableWithNonTrivialDtorIsNeverUsed/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppLongFloat/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMemberFunctionMayBeConst/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMemberFunctionMayBeStatic/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMemberInitializersOrder/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMismatchedClassTags/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMissingIncludeGuard/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMissingKeywordThrow/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppModulePartitionWithSeveralPartitionUnits/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMsExtAddressOfClassRValue/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMsExtBindingRValueToLvalueReference/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMsExtCopyElisionInCopyInitDeclarator/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMsExtDoubleUserConversionInCopyInit/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMsExtNotInitializedStaticConstLocalVar/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMsExtReinterpretCastFromNullptr/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMultiCharacterLiteral/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMultiCharacterWideLiteral/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMustBePublicVirtualToImplementInterface/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppMutableSpecifierOnReferenceMember/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNoDiscardExpression/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNodiscardFunctionWithoutReturnValue/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExceptionSafeResourceAcquisition/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExplicitConversionOperator/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExplicitConvertingConstructor/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonInlineFunctionDefinitionInHeaderFile/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonInlineVariableDefinitionInHeaderFile/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNotAllPathsReturnValue/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppObjectMemberMightNotBeInitialized/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppOutParameterMustBeWritten/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppOverrideWithDifferentVisibility/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppParameterMayBeConst/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppParameterMayBeConstPtrOrRef/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppParameterNamesMismatch/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppParameterNeverUsed/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPassValueParameterByConstReference/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPointerConversionDropsQualifiers/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPointerToIntegralConversion/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPolymorphicClassWithNonVirtualPublicDestructor/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPossiblyErroneousEmptyStatements/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPossiblyUninitializedMember/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPossiblyUnintendedObjectSlicing/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrecompiledHeaderIsNotIncluded/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrecompiledHeaderNotFound/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrintfBadFormat/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrintfExtraArg/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrintfMissedArg/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrintfRiskyFormat/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppPrivateSpecialMemberFunctionIsNotImplemented/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRangeBasedForIncompatibleReference/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedefinitionOfDefaultArgumentInOverrideFunction/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantAccessSpecifier/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantBaseClassAccessSpecifier/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantBaseClassInitializer/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantBooleanExpressionArgument/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantCastExpression/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantComplexityInComparison/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantConditionalExpression/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantConstSpecifier/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantControlFlowJump/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantDereferencingAndTakingAddress/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantElaboratedTypeSpecifier/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantElseKeyword/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantElseKeywordInsideCompoundStatement/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantEmptyDeclaration/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantEmptyStatement/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantExportKeyword/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantFwdClassOrEnumSpecifier/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantInlineSpecifier/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantLambdaParameterList/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantMemberInitializer/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantNamespaceDefinition/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantParentheses/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantQualifier/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantQualifierADL/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantStaticSpecifierOnMemberAllocationFunction/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantStaticSpecifierOnThreadLocalLocalVariable/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantTemplateArguments/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantTemplateKeyword/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantTypenameKeyword/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantVoidArgumentList/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRedundantZeroInitializerInAggregateInitialization/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppReferenceToOverriddenVirtualFunction/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppReinterpretCastFromVoidPtr/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppRemoveRedundantBraces/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppReplaceMemsetWithZeroInitialization/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppReplaceTieWithStructuredBinding/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppReturnNoValueInNonVoidFunction/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppSmartPointerVsMakeFunction/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppSomeObjectMembersMightNotBeInitialized/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppSpecialFunctionWithoutNoexceptSpecification/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppStaticAssertFailure/@EntryIndexedValue" value="ERROR" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppStaticDataMemberInUnnamedStruct/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppStaticSpecifierOnAnonymousNamespaceMember/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppStringLiteralToCharPointerConversion/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTabsAreDisallowed/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTemplateArgumentsCanBeDeduced/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTemplateParameterNeverUsed/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTemplateParameterShadowing/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppThrowExpressionCanBeReplacedWithRethrow/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTooWideScope/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTooWideScopeInitStatement/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppTypeAliasNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUninitializedDependentBaseClass/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUninitializedNonStaticDataMember/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnionMemberOfReferenceType/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnmatchedPragmaEndRegionDirective/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnmatchedPragmaRegionDirective/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnnamedNamespaceInHeaderFile/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnnecessaryWhitespace/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnsignedZeroComparison/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUnusedIncludeDirective/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseAlgorithmWithCount/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseAssociativeContains/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseAuto/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseAutoForNumeric/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseDesignatedInitializers/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseElementsView/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseEraseAlgorithm/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseFamiliarTemplateSyntaxForGenericLambdas/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseInternalLinkage/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseRangeAlgorithm/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseStdSize/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseStructuredBinding/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUseTypeTraitAlias/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUserDefinedLiteralSuffixDoesNotStartWithUnderscore/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppUsingResultOfAssignmentAsCondition/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppVariableCanBeMadeConstexpr/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppVirtualFunctionCallInsideCtor/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppVirtualFunctionInFinalClass/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppVolatileParameterInDeclaration/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppWarningDirective/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppWrongIncludesOrder/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppWrongSlashesInIncludeDirective/@EntryIndexedValue" value="HINT" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppZeroConstantCanBeReplacedWithNullptr/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppZeroValuedExpressionUsedAsNullPointer/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=IdentifierTypo/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=IfStdIsConstantEvaluatedCanBeReplaced/@EntryIndexedValue" value="SUGGESTION" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=StdIsConstantEvaluatedWillAlwaysEvaluateToConstant/@EntryIndexedValue" value="WARNING" type="string" />
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=StringLiteralTypo/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppClangFormat/EnableClangFormatSupport/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_ARGUMENT/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_BINARY_EXPRESSIONS_CHAIN/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_CALLS_CHAIN/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_EXPRESSION/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_EXTENDS_LIST/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_FOR_STMT/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_PARAMETER/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_TYPE_ARGUMENT/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTILINE_TYPE_PARAMETER/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_MULTIPLE_DECLARATION/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ALIGN_TERNARY/@EntryValue" value="ALIGN_ALL" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/ANONYMOUS_METHOD_DECLARATION_BRACES/@EntryValue" value="END_OF_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/BLANK_LINES_AROUND_CLASS_DEFINITION/@EntryValue" value="1" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/BLANK_LINES_AROUND_DECLARATIONS/@EntryValue" value="0" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/BLANK_LINES_AROUND_FUNCTION_DECLARATION/@EntryValue" value="1" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/BLANK_LINES_AROUND_FUNCTION_DEFINITION/@EntryValue" value="1" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/BREAK_TEMPLATE_DECLARATION/@EntryValue" value="LINE_BREAK" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/CASE_BLOCK_BRACES/@EntryValue" value="END_OF_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/CONTINUOUS_LINE_INDENT/@EntryValue" value="Double" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INDENT_ACCESS_SPECIFIERS_FROM_CLASS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INDENT_CASE_FROM_SWITCH/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INDENT_CLASS_MEMBERS_FROM_ACCESS_SPECIFIERS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INDENT_COMMENT/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INDENT_SIZE/@EntryValue" value="4" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INDENT_STYLE/@EntryValue" value="Space" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INITIALIZER_BRACES/@EntryValue" value="END_OF_LINE_NO_SPACE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INT_ALIGN_EQ/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/INVOCABLE_DECLARATION_BRACES/@EntryValue" value="END_OF_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/KEEP_BLANK_LINES_IN_CODE/@EntryValue" value="2" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/KEEP_BLANK_LINES_IN_DECLARATIONS/@EntryValue" value="2" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/KEEP_USER_LINEBREAKS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/LINE_BREAK_AFTER_COLON_IN_MEMBER_INITIALIZER_LISTS/@EntryValue" value="ON_SINGLE_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/MEMBER_INITIALIZER_LIST_STYLE/@EntryValue" value="DO_NOT_CHANGE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/NAMESPACE_DECLARATION_BRACES/@EntryValue" value="END_OF_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/NAMESPACE_INDENTATION/@EntryValue" value="All" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/OTHER_BRACES/@EntryValue" value="END_OF_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/PLACE_CATCH_ON_NEW_LINE/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/PLACE_ELSE_ON_NEW_LINE/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/PLACE_NAMESPACE_DEFINITIONS_ON_SAME_LINE/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/PLACE_WHILE_ON_NEW_LINE/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SIMPLE_BLOCK_STYLE/@EntryValue" value="DO_NOT_CHANGE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_CAST_EXPRESSION_PARENTHESES/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_COLON_IN_BITFIELD_DECLARATOR/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_COMMA_IN_TEMPLATE_ARGS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_COMMA_IN_TEMPLATE_PARAMS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_EXTENDS_COLON/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_FOR_COLON/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_FOR_SEMICOLON/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_PTR_IN_DATA_MEMBER/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_PTR_IN_DATA_MEMBERS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_PTR_IN_METHOD/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_PTR_IN_NESTED_DECLARATOR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_REF_IN_DATA_MEMBER/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_REF_IN_DATA_MEMBERS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_REF_IN_METHOD/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_AFTER_UNARY_OPERATOR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_COLON_IN_BITFIELD_DECLARATOR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_EXTENDS_COLON/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_FOR_COLON/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_FOR_SEMICOLON/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_PTR_IN_ABSTRACT_DECL/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_PTR_IN_DATA_MEMBER/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_PTR_IN_DATA_MEMBERS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_PTR_IN_METHOD/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_REF_IN_ABSTRACT_DECL/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_REF_IN_DATA_MEMBER/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_REF_IN_DATA_MEMBERS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_REF_IN_METHOD/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_TEMPLATE_ARGS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BEFORE_TEMPLATE_PARAMS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_BETWEEN_CLOSING_ANGLE_BRACKETS_IN_TEMPLATE_ARGS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_ARRAY_ACCESS_BRACKETS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_CAST_EXPRESSION_PARENTHESES/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_DECLARATION_PARENTHESES/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_EMPTY_BLOCKS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_EMPTY_INITIALIZER_BRACES/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_EMPTY_METHOD_PARENTHESES/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_EMPTY_TEMPLATE_PARAMS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_INITIALIZER_BRACES/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_TEMPLATE_ARGS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPACE_WITHIN_TEMPLATE_PARAMS/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/SPECIAL_ELSE_IF_TREATMENT/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/TAB_WIDTH/@EntryValue" value="4" type="int" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/TYPE_DECLARATION_BRACES/@EntryValue" value="END_OF_LINE" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_AFTER_BINARY_OPSIGN/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_AFTER_DECLARATION_LPAR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_AFTER_INVOCATION_LPAR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_ARGUMENTS_STYLE/@EntryValue" value="WRAP_IF_LONG" type="string" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_BEFORE_DECLARATION_LPAR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_BEFORE_DECLARATION_RPAR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_BEFORE_INVOCATION_LPAR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_BEFORE_INVOCATION_RPAR/@EntryValue" value="false" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_BEFORE_TERNARY_OPSIGNS/@EntryValue" value="true" type="bool" />
<option name="/Default/CodeStyle/CodeFormatting/CppFormatting/WRAP_PARAMETERS_STYLE/@EntryValue" value="WRAP_IF_LONG" type="string" />
<option name="/Default/CodeStyle/EditorConfig/EnableClangFormatSupport/@EntryValue" value="false" type="bool" />
</component>
</project>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="userId" value="-2857a757:19fa27c75be:-7fff" />
</MTProjectMetadataState>
</option>
</component>
</project>
-7
View File
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakePythonSetting">
<option name="pythonIntegrationState" value="YES" />
</component>
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
</project>
-8
View File
@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/reasampler.iml" filepath="$PROJECT_DIR$/.idea/reasampler.iml" />
</modules>
</component>
</project>
-2
View File
@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CIDR" type="CPP_MODULE" version="4" />
Generated
-8
View File
@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/vendor/WDL" vcs="Git" />
<mapping directory="$PROJECT_DIR$/vendor/reaper-sdk" vcs="Git" />
</component>
</project>
+52 -12
View File
@@ -6,7 +6,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
**ReaSampler** is a per-project audio sample-bank capture tool that builds two artifacts: the REAPER extension (`reaper_reasampler`) and **ReaSampler 9000**, a Windows-only VST3 sampler instrument (`reasampler_9000.vst3`, `core/instrument/` + `shell/instrument/`, second CMake target `reasampler_vst`, gated on the vendored `vendor/vst3sdk` submodule slice). The pure-testable-core / REAPER-facing-shell discipline is preserved throughout: `core/` never includes REAPER or VST3 SDK types, `shell/` is where those hosts are actually touched, `app/` is the extension entry point. Every REAPER API name cited in project docs is correct-by-intent; verify argument order, types, and flag values against `vendor/reaper-sdk/sdk/reaper_plugin_functions.h` before use.
Per-module detail — what each file owns, its invariants — lives in the twenty per-directory `src/**/CLAUDE.md` files; see the compact map in "Architecture: the load-bearing split" below to find the right one. Landed-phase history lives in `docs/ARCHIVE.md`; current work lives in `docs/COMPLETED.md`, `docs/TODO.md`, and `docs/TODO-1.0.md` — see "Project docs" below.
Per-module detail — what each file owns, its invariants — lives in the twenty-seven per-directory `src/**/CLAUDE.md` files; see the compact map in "Architecture: the load-bearing split" below to find the right one. Landed-phase history lives in `docs/ARCHIVE.md`; current work lives in `docs/COMPLETED.md`, `docs/TODO.md`, and `docs/TODO-1.0.md` — see "Project docs" below.
## Settled decisions
@@ -19,8 +19,9 @@ Per-module detail — what each file owns, its invariants — lives in the twent
paths anywhere in the index.
- **Material:** must handle full-mix/stem bounces, chops/one-shots, and
single-cycle/wavetable grabs equally. That means exact sample-accurate bounds,
explicit tail control, channel-count preservation, and loop/zero-crossing
handling all matter from day one.
explicit tail control, correct channel handling (the exact-bounds channel rule
under Precision invariants), and loop/zero-crossing handling all matter from day
one.
## One-time submodule setup
@@ -46,6 +47,16 @@ On a multi-config generator (Visual Studio, Xcode) the bare `ctest` command abov
reports every test as "Not Run" — add `-C Debug` (or whichever config was built) to
resolve the test executables. Single-config generators (Ninja, Make) need no such flag.
On a multi-config generator, `cmake --build build` with no `--config` builds **Debug**
there is no `CMAKE_BUILD_TYPE`, no `CMAKE_CXX_FLAGS`, and no IPO/LTO setting anywhere in
the build, so nothing is optimized or inlined at that default. The performance
guardrails and structural heuristics below (header-inline hot paths, "no LTO
configured") presume an **optimizing** build. Shipping, installing, or judging
performance requires the Release config explicitly:
cmake --build build --config Release
ctest --test-dir build -C Release
Every pure module has a corresponding `<module>_tests` executable target that runs without REAPER or a DAW. Targets are declared per directory: each `src/**/CMakeLists.txt` owns its own libraries and their test targets, added via `add_subdirectory` from the root, which keeps only repo-global settings (version, channel, vendor paths). `cmake/reasampler_targets.cmake` holds the two shared declaration helpers. The two loadable-module targets are `reaper_reasampler` (the REAPER extension `.dll`/`.dylib`/`.so`) and `reasampler_vst` (the VST3 instrument; Windows-only, omitted if the `vendor/vst3sdk` slice is absent). The `sample_usage_tests` executable target runs the pure unit tests for `sample_usage` (no REAPER, no DAW).
### Beta channel build
@@ -69,22 +80,28 @@ Add the generated file to the appropriate `APPLE` / Linux `target_sources` block
### Install / reload
There is no hot-reload. Copy the built binary into REAPER's `UserPlugins/` folder (Options → Show REAPER resource path) and restart REAPER. Extensions load at startup only.
There is no hot-reload. Copy the **Release** build's binary (`build/Release/` on a multi-config generator — not the default `Debug/` output) into REAPER's `UserPlugins/` folder (Options → Show REAPER resource path) and restart REAPER. Extensions load at startup only.
## Architecture: the load-bearing split
`core/` holds pure, unit-testable logic — no REAPER or VST3 SDK types, each with a corresponding `<module>_tests` target that runs without a DAW. `shell/` holds the REAPER/host-facing shells — where those SDK types are actually touched. `app/` is the extension entry point. Each of the twenty directories below carries its own `CLAUDE.md` with the full module list and that area's invariants — open the relevant one for detail; this file states only repo-wide truth.
`core/` holds pure, unit-testable logic — no REAPER or VST3 SDK types, each with a corresponding `<module>_tests` target that runs without a DAW. `shell/` holds the REAPER/host-facing shells — where those SDK types are actually touched. `app/` is the extension entry point. Each of the twenty-seven directories below carries its own `CLAUDE.md` with the full module list and that area's invariants — open the relevant one for detail; this file states only repo-wide truth.
| Directory | Scope |
|---|---|
| `src/app/` | REAPER extension entry point |
| `src/core/audio/` | pure audio-data math |
| `src/core/capture/` | pure logic behind the capture pillar |
| `src/core/instrument/` | pure VST3-instrument core (engine / map / ui) |
| `src/core/instrument/` | pure VST3-instrument core (bake / engine / map / note / param / ui) |
| `src/core/instrument/bake/` | the resample bake's pure half — the programmed note resolved to a frame window, the offline render over a bake-only voice engine, and the post-bake reset |
| `src/core/instrument/engine/filter/` | pure per-voice resonant TPT/SVF filter (HP→BP→LP / HP→notch→LP morph, drive stage), run by each `Voice` between the pitch and amp stages |
| `src/core/instrument/engine/loop/` | the sustain loop's ONE validity/clamp fold plus its pre-seam crossfade geometry and the editor's default handle span |
| `src/core/instrument/note/` | the programmed capture-signal model — musical divisions, tempo resolution, anchored offsets |
| `src/core/instrument/param/` | the VST3 parameter surface's pure half — the FOREVER-FROZEN id table, the exposed set derived from the commit predicate, the plain-value layer, and the one formatter per unit category |
| `src/core/json/` | the hand-rolled JSON lexical layer |
| `src/core/model/` | the pure bank/sample index and its multi-bank container |
| `src/core/package/` | the pure RSBK bank-package codec — format contract, version ladder, JSON manifest, framing/layout codec |
| `src/core/reclaim/` | pure prune orphan computation |
| `src/core/tracking/` | the consolidated file-tracking system — birth/lineage records and the one authority answering prune's protected set and the resample's replace-vs-add |
| `src/core/ui/` | pure UI geometry, palette, and interaction-decision modules |
| `src/core/util/` | small shared pure utilities |
| `src/core/version/` | version/channel identity |
@@ -94,6 +111,7 @@ There is no hot-reload. Copy the built binary into REAPER's `UserPlugins/` folde
| `src/shell/bank_ops/` | promptless bank-mutation verbs |
| `src/shell/capture/` | REAPER-facing capture backends and action bodies |
| `src/shell/instrument/` | ReaSampler 9000 VST3 shells |
| `src/shell/package/` | package filesystem I/O (streaming atomic read/write, exclusive-create landing), the rollback journal, and the REAPER file pickers |
| `src/shell/panel/` | the docked bank-panel shell + the shared LICE draw kit |
| `src/shell/persist/` | project ext-state persistence, prune filesystem I/O, usage scan |
| `src/shell/view/` | Design View mode application shell |
@@ -103,9 +121,10 @@ There is no hot-reload. Copy the built binary into REAPER's `UserPlugins/` folde
The top-level split is by the pure/shell discipline: `core/` never includes REAPER or VST3 SDK
types; `shell/` is where those host types are actually touched — the discriminator is "may this
file touch a host type, REAPER *or* VST3 SDK." Subsystem directories sit beneath `core/` (see the
table above); `core/instrument/` further subdivides into `engine/` / `map/` / `ui/`. Namespaces
mirror directories — `reasampler::<subsystem>` for `core/`, house style for `shell/`. `app/` holds
`main.cpp` only: API-pointer ownership, `ReaperPluginEntry`, and dispatch.
table above); `core/instrument/` further subdivides into `bake/` / `engine/` / `map/` / `note/` /
`param/` / `ui/`. Namespaces mirror directories — `reasampler::<subsystem>` for `core/`, house
style for `shell/`. `app/` holds `main.cpp` only: API-pointer ownership, `ReaperPluginEntry`, and
dispatch.
For the module list within any one directory — what lives there, its invariants — open that
directory's own `CLAUDE.md` rather than looking here.
@@ -168,12 +187,13 @@ Comments carry *why*, and context where non-obvious — never *what* the code al
2. `rec->Register("gaccel", &accel)` — puts the action in the Actions list.
3. `rec->Register("hookcommand", ...)` — receives every action fired; claim only your own id, return `false` otherwise.
4. On unload (`rec == nullptr`), mirror-unregister everything with the same strings prefixed by `'-'`.
- **Non-main sections use a different mechanism.** `gaccel_register_t` carries no section field — `command_id` + `gaccel` can only ever produce a Main-section action. To publish into another section (Media Explorer = 32063, MIDI editor = 32060, MIDI event list = 32061, MIDI inline = 32062), register a `custom_action_register_t{uniqueSectionId, idStr, name, extra}` under `"custom_action"`; it returns the command id, or **0 on failure** (e.g. a duplicate `idStr`) — which the caller must tolerate rather than half-register. `idStr` must be unique **across all sections**, so an action published into both Main and a non-main section needs a SECOND id string; the FOREVER-STABLE contract binds it identically from the moment it ships. `custom_action_register_t` has no `ACCEL`, so a non-main entry ships no default keybinding. Dispatch for these ids arrives through `"hookcommand2"` (`bool(KbdSectionInfo*, int command, int val, int val2, int relmode, HWND)`) — `"hookcommand"` runs for the main section only. The two hooks must partition the ids between them; what happens when a command is claimed by both is unspecified by the SDK (`hookcommand2`'s doc says a `true` return prevents further hooks/actions from running, which is in tension with a clean double-fire either way), so nothing may rely on either outcome. On unload, mirror with `"-custom_action"` `[verify — DAW]` (the header confirms the `-` prefix for "most" registration types and spells out only `-pcmsrc` by name; `custom_action` itself is unconfirmed) and `"-hookcommand2"`.
## Product design docs
`docs/product/` holds the product-design reasoning behind each phase — the "why we chose this" that predates the spec. They are large; **grep for the cited section rather than reading a file whole**. `docs/cmake-cheatsheet.md` is a standalone build-system reference.
Files: `capture-tail.md`, `code-organization.md`, `design-view.md`, `midi-playback.md`, `multi-bank.md`, `provenance.md`, `removal-and-prune.md`, `versioning-and-release.md`, `visual-design-language.md`.
Files: `bank-package.md`, `capture-tail.md`, `code-organization.md`, `code-quality-audit.md`, `design-view.md`, `instrument-control-surface.md`, `linux-readiness.md`, `midi-playback.md`, `multi-bank.md`, `parameter-automation.md`, `provenance.md`, `removal-and-prune.md`, `render-in-place.md`, `single-cycle-and-wavetable.md`, `versioning-and-release.md`, `visual-design-language.md`. `audit-notes/` is a subdirectory of track-evidence appendices for `code-quality-audit.md`, not a peer doc — not enumerated above.
## Project docs
@@ -185,17 +205,37 @@ Plan-style docs live under `docs/`:
## The load-bearing principle
**Capture and placement are separate acts.** Capturing audio writes a file to the bank and adds an index entry. It **never** puts an item in the arrange view. Placement is a distinct, on-demand action (`insert` module / `InsertMedia`). Any code path that auto-inserts a capture into the timeline violates the purpose of the tool and **must be rejected in review**.
**Capture and placement are separate acts.** Capturing audio writes a file to the bank and adds an index entry. It **never** puts an item in the arrange view. Placement is a distinct, on-demand action (`insert` module / `InsertMedia`). Any code path that auto-inserts a capture into the timeline violates the purpose of the tool and **must be rejected in review**. A render that goes arrange → arrange, never entering the bank and never reading it (`shell/capture/render_in_place`), is a THIRD verb outside this rule rather than a softening of it — the rule binds anything that touches the bank on either side, so a bank sample may still only reach the timeline through an on-demand placement, and a capture may never grow a place step.
## Precision invariants — required before any feature ships
- **Null test:** a dry offline capture of a range, re-inserted at its source position, nulls to silence against the source — the tool's trust anchor. Ship as a verification action. (Verification action cut per `docs/product/provenance.md` — manual verification only.)
- **Bit-identical repeats:** identical offline capture requests produce identical files.
- **Non-destructive:** capture never mutates source items or tracks; the realtime backend's temp track is created and removed cleanly, and source routing is restored.
- **Exact bounds:** no rounding of the requested range; no added silence unless a tail is explicitly requested; channel count preserved (no silent stereo fold).
- **Exact bounds:** no rounding of the requested range; no added silence unless a tail is explicitly requested; **no lossy channel fold** — summing or averaging differing channels is forbidden. The one permitted collapse is lossless: a new capture whose channels are bit-identical per frame (float bit patterns, never an epsilon) lands as a 1-channel file, with `Sample::channelCount` and the file's `fmt` written together so the two can never disagree. Frame count, sample rate and bit depth are untouched by it. Never retroactive — existing entries and files are never rewritten — and ingest is excluded, because an imported file is the user's bytes, not our capture. The superseded wording ("channel count preserved") was already untrue in the other direction: a mono source renders at `RENDER_CHANNELS = 2`. `[verify — DAW]` "lossless" here is a file-bytes property; whether REAPER sums a 1-channel item on a stereo track at the same unity gain as a dual-mono 2-channel item (pan law, mono spread) — the null test's actual playback-chain property — is unconfirmed.
- **Relative paths only** in the persisted `BankIndex`.
- **Capture FX scope:** two scopes only — item = item/take FX only; track = item FX + the selected track's own track FX. There is no master scope (to capture the master, render a track instead). For both scopes, the out-of-scope chain (ancestors + master track, plus the item's own track for item scope) has its FX, gain, and pan/width/pan-law/mode neutralized to unity — the master track is bypassed as out-of-scope chain, not captured as a scope. Range (time selection or razor) is orthogonal.
## The resample bake — the one crossing from instrument into bank
A click inside the ReaSampler 9000 editor bakes the dialed sound into a bank capture. The
split is: **the instrument renders, the extension banks.** The instrument produces the audio
on its own voice path in its own process (so the bake is the object code that made the sound
the user approved, immune to engine-version skew between the two artifacts), stages it
outside the bank folder, and invokes ONE extension action over the VST3 host bridge; the
extension lands it and answers over the same per-instance key, synchronously, inside that
call. Consequences that bind:
- **The extension's link graph does not gain the voice engine.** `sampler_core` /
`pitch_shift` / the filter are NOT linked into `reaper_reasampler` — a link edge to any of
them means the design drifted back to an extension-side render.
- **No arrange mutation and no deletion.** The bake writes a file plus an index entry, like
every other capture. "Replace" means the bank entry now denotes the recapture; the
superseded file survives on disk until a prune reclaims it — the iterate loop's recovery
floor.
- **The bake adds nothing to `process()`.** It renders on the UI thread over a separate
`VoiceEngine`, with the live-parameter block detached.
## Non-goals / guardrails
- No auto-insertion of captures into the arrange (see the load-bearing principle).
+4 -2
View File
@@ -21,9 +21,9 @@ cmake_minimum_required(VERSION 3.19)
# invariant (reconstruct-from-components inside app_version.cpp) via a permanent synthetic
# "0.9.01" fixture there that must NEVER be bumped on release. It cannot see this line
# becoming a CMake derivation — that is this comment's job.
set(REASAMPLER_VERSION "1.0.0")
set(REASAMPLER_VERSION "1.7.5")
project(reaper_reasampler VERSION 1.0.0 LANGUAGES CXX)
project(reaper_reasampler VERSION 1.7.5 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -85,6 +85,7 @@ set(LICE_SRC
# ---------------------------------------------------------------------------
set(REASAMPLER_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
set(REASAMPLER_TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/tests)
set(REASAMPLER_PACKAGE_FIXTURE_DIR ${REASAMPLER_TESTS_DIR}/fixtures/package_compat)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/reasampler_targets.cmake)
enable_testing()
@@ -92,3 +93,4 @@ enable_testing()
add_subdirectory(src/core)
add_subdirectory(src/app)
add_subdirectory(src/shell/instrument)
add_subdirectory(src/shell/package)
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+114 -28
View File
@@ -1,20 +1,38 @@
# ReaSampler
A native C++ REAPER extension that captures any arbitrary audio source into a
per-project **sample bank** (cached files + a docked grid), decoupled from the
arrange view, with keyboard/MIDI-bindable capture and placement. Built as a
precision tool: deterministic, non-destructive, no clutter.
Version 1.6.0 · License: GNU AGPL v3 (see `LICENSE`)
A per-project audio sample-bank capture tool for REAPER, built as two artifacts: a
native C++ REAPER extension (`reaper_reasampler`) and a Windows-only VST3 sampler
instrument (`reasampler_9000.vst3`, ReaSampler 9000). It captures any arbitrary audio
source into a per-project **sample bank** (cached files + a docked grid), decoupled
from the arrange view, with keyboard/MIDI-bindable capture and placement. It is
designed as a precision tool: deterministic captures, non-destructive by
construction, no auto-inserted clutter.
## Status
Under active development, not yet formally released.
## The two artifacts
**`reaper_reasampler`** — the REAPER extension. Captures audio into a named,
per-project sample bank, displays it in a docked panel, and provides bindable
actions for capture and placement.
per-project sample bank and provides bindable actions across the workflow: offline
and realtime capture (with cancel), batch capture (per selected item or per razor
area), recapture-from-source, capture-and-assign to a live instrument instance,
insert with an opt-in tempo-conform variant, the resample-bake landing action,
multi-bank management (pool, activate, evacuate, move, copy, delete), prune/reclaim,
provenance and lineage tracking, Design View, and ingest via drag-out, arrange-drop,
and instrument-drop. All of it surfaces in a docked bank panel.
**ReaSampler 9000** (`reasampler_9000.vst3`) — a Windows-only VST3 sampler
instrument that plays bank captures back across a MIDI keyboard. The VST3 target
(`reasampler_vst`) is gated on the vendored `vendor/vst3sdk` slice; configure
quietly omits it if the slice is absent.
instrument that plays bank captures back across a MIDI keyboard. Since
`ComponentState` v10 it is self-contained: it decodes samples from its own
persisted references and plays with the extension absent, treating the bank as a
browsing source rather than a runtime dependency. The VST3 target
(`reasampler_vst`) is gated on `WIN32 AND EXISTS .../pluginfactory.cpp` — omitted
on macOS/Linux even when the vendored `vendor/vst3sdk` slice is present, and
quietly omitted anywhere the slice itself is absent.
A **beta channel** build is available via `-DREASAMPLER_CHANNEL=beta` at configure
time, producing `reaper_reasampler_beta` and `reasampler_9000_beta.vst3`. The two
@@ -27,8 +45,35 @@ and adds an index entry. It **never** puts an item in the arrange view. Placemen
is a distinct, on-demand action. Any code path that auto-inserts a capture into the
timeline violates the purpose of the tool.
## Prerequisites
- CMake ≥ 3.19
- A C++17 compiler
- Windows + MSVC to build the VST3 target (`reasampler_vst`) — the REAPER extension
itself is cross-platform
- PHP, to run the SWELL resource-generation step on macOS/Linux (below)
## Platform support
The REAPER extension targets Windows, macOS, and Linux; ReaSampler 9000 (the VST3
instrument) is Windows-only.
| Platform | Extension | VST3 instrument |
|---|---|---|
| Windows | Builds with no extra steps | Builds when `vendor/vst3sdk` is present |
| macOS | Builds, but dialogs need the manual SWELL resgen step below plus hand-uncommenting the `APPLE` `target_sources` block in `src/app/CMakeLists.txt` | Not built (Windows-only gate) |
| Linux | Same manual resgen + hand-uncomment requirement as macOS, against its own commented block | Not built (Windows-only gate) |
A macOS/Linux build that skips the resgen-and-uncomment step compiles cleanly
without dialogs and without a warning — this is expected, not a bug.
## One-time setup
A plain `git clone --recursive` also works, but it pulls every nested submodule of
`vendor/vst3sdk` (including `vstgui4`, `tutorials`, `doc`, `cmake` — none of which
this project links against). The steps below pull only the three submodules
actually needed:
git submodule update --init
Vendors three submodules:
@@ -43,10 +88,25 @@ Vendors three submodules:
cmake -B build -S .
cmake --build build
ctest --test-dir build
ctest --test-dir build -C Debug
Pure modules have `<module>_tests` targets that run without REAPER or a DAW.
`CMakeLists.txt` is the authoritative list of all targets.
On a multi-config generator (Visual Studio, Xcode), `cmake --build build` with no
`--config` builds **Debug** — nothing in this build sets `CMAKE_BUILD_TYPE` or an
optimization flag, so that's the default. The `-C Debug` above is required on a
multi-config generator too: without it, `ctest` silently reports every test as "Not
Run" instead of running them. Single-config generators (Ninja, Make) need neither
flag.
Pure `core/` modules each have a corresponding `<module>_tests` executable target
that runs without REAPER or a DAW. Targets are declared per-directory — each
`src/**/CMakeLists.txt` owns its own libraries and test targets, pulled in via
`add_subdirectory` from the root `CMakeLists.txt`, which itself declares no targets
directly.
Installing or judging performance requires the Release config explicitly:
cmake --build build --config Release
ctest --test-dir build -C Release
### Beta channel
@@ -60,33 +120,59 @@ Pure modules have `<module>_tests` targets that run without REAPER or a DAW.
php vendor/WDL/WDL/swell/swell_resgen.php src/resource.rc # macOS; Linux reuses the output
Add the generated file to the appropriate `APPLE` / Linux `target_sources` block in
CMakeLists.txt. The SWS extension build is the canonical reference for this step.
`src/app/CMakeLists.txt` (both are commented out by default). The SWS extension
build is the canonical reference for this step.
## Install
Copy the built binary into REAPER's `UserPlugins/` folder
(Options → Show REAPER resource path), then **restart REAPER**. Extensions load at
startup only; there is no hot reload.
There is no hot reload; REAPER loads extensions at startup only.
**Extension** — copy the **Release** build's `reaper_reasampler` binary
(`build/Release/` on a multi-config generator — not the default `Debug/` output)
into REAPER's `UserPlugins/` folder (Options → Show REAPER resource path), then
restart REAPER.
**VST3 instrument** — copy the **Release** build's `reasampler_9000.vst3` into the
system VST3 folder (`C:\Program Files\Common Files\VST3` on Windows) — a different
destination from the extension, not `UserPlugins/`. REAPER picks it up on its next
plugin rescan.
## Repo layout
The codebase is organized around one discipline: **pure, REAPER-free testable core
split from REAPER-facing shells**.
The codebase is organized around one discipline: **pure, REAPER/VST3-SDK-free
testable core, split from the REAPER- and VST3-facing shells that touch those host
types.**
- `src/`pure core modules (no REAPER types, unit-testable outside the DAW) and
REAPER-facing shells (extension entry point, panel, actions, capture backends, etc.)
- `src/vst/` — the VST3 instrument: pure voice engine + zone payload + editor UI
pure modules, and the VST3 shells
- `tests/` — unit tests for the pure core modules
- `src/app/`the REAPER extension's entry point (`main.cpp` only)
- `src/core/` — pure modules, no REAPER or VST3 SDK types, each with a
`<module>_tests` target: `audio/`, `capture/`, `instrument/` (further split into
`bake/`, `engine/filter/`, `engine/loop/`, `map/`, `note/`, `ui/`), `json/`,
`model/`, `reclaim/`, `tracking/`, `ui/`, `util/`, `version/`, `view/`, `wire/`
- `src/shell/` — REAPER/VST3-facing shells: `actions/`, `bank_ops/`, `capture/`,
`instrument/` (the ReaSampler 9000 VST3 shells), `panel/`, `persist/`, `view/`
- `src/resource.rc`, `src/resource.h`, `src/ext_keys.h` — root-level build inputs
not claimed by any one subdirectory
- `tests/` — unit test sources for the pure `core/` modules
- `cmake/` — shared CMake target-declaration helpers
- `docs/` — plan-style docs and product-design docs (see Further reading, below)
- `vendor/` — git submodules
See `CLAUDE.md` for the full module inventory, architectural contracts, and the
precise boundary between pure core and REAPER-facing shells.
precise boundary between pure core and REAPER/VST3-facing shells; each `src/**/`
directory also carries its own `CLAUDE.md` with that area's own module list and
invariants.
## License
GNU AGPL v3, copyright Daniel Harvey. See `LICENSE`.
## Further reading
- `CLAUDE.md` — architecture, module inventory, and build/API contracts
- `CONTEXT.md` — the authoritative spec (large: ~186k — grep the relevant section rather than reading whole)
- `CONTEXT-ARCHIVE.md` — build detail for landed work
- `PLAN.md` — roadmap
- `COMPLETED.md` — landed milestones
- `docs/PLAN.md` — the active roadmap
- `docs/COMPLETED.md` — landed milestones for the current (1.x) cycle
- `docs/TODO.md` — deferred follow-ups, with the reason each was deferred
- `docs/TODO-1.0.md` — the raw 1.x work list this cycle's plan was structured from
- `docs/ARCHIVE.md` — pre-1.0 history
- `docs/cmake-cheatsheet.md` — a standalone build-system reference
- `docs/product/` — the product-design reasoning behind each phase
+11
View File
@@ -12,6 +12,17 @@ function(reasampler_pure_library name)
if(ARG_LINK)
target_link_libraries(${name} ${ARG_LINK})
endif()
# A default-less switch missing an enumerator: MSVC's C4062 is off by its /W1 default;
# GCC/Clang's -Wswitch is on by default but only warns without -Werror, and this repo
# sets no -Wall/-Werror/-W4/-WX anywhere. Promoted to an error only here, on our own
# pure libraries, so a deliberately default-less switch (e.g. deckParamCommit,
# deck_groups.cpp) is a compile error on every toolchain. NOT C4061 (fires even with
# a default: present) — that would light up every defensive switch in the tree.
if(MSVC)
target_compile_options(${name} PRIVATE /we4062)
elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(${name} PRIVATE -Werror=switch)
endif()
endfunction()
# Test naming is exceptionless: target <name>_tests is built from tests/test_<name>.cpp
+1432
View File
File diff suppressed because it is too large Load Diff
+2012 -1187
View File
File diff suppressed because it is too large Load Diff
+758 -15
View File
@@ -46,7 +46,9 @@ Forward-looking follow-ups. Deferred by decision, not oversight — each entry r
**Priority / risk.** Low / deferred. Current behavior is safe; the only cost is unbounded bank-folder growth after reopens. Decided 2026-07-28 to ship the safe version and defer this.
**Done looks like.** Save → reopen → de-reference a capture from an instance → prune reclaims it. And: in-place-duplicate + diverge + delete-from-bank never deletes a capture a live instance holds.
**Re-examined 2026-07-30 by the tracking consolidation, and DELIBERATELY NOT absorbed.** The consolidation's mandate is a *safety* claim (no destructive act follows from ambiguity); this wart is a *completeness* one (nothing is lost, the folder grows). They do not conflict, and folding a fix in would have widened a safety-critical review surface with a mechanism that can under-protect. The strongest candidate examined was a **session epoch**: the extension mints a fresh epoch value at each project load and an instance stamps it into its record, so a record carrying a previous epoch is known-stale and may be clean-replaced regardless of nonce. It fixes exactly the reopen case — but a divergent same-key clone pair reopening together gives the first publisher a clean replace that drops the second's holds until the second republishes, i.e. a narrow revival of the sibling-drop bug. Any future attempt must close that window (e.g. by making the epoch rollover a union that clears the sticky poison only once both siblings have republished) before it is worth taking.
**Done looks like.** Save → reopen → de-reference a capture from an instance → prune reclaims it. And: in-place-duplicate + diverge + delete-from-bank never deletes a capture a live instance holds, with no window between the two publishes in which a hold is unprotected.
## Isolate capture from out-of-scope aux/parallel sends, not just FX/gain/pan
@@ -108,20 +110,6 @@ Forward-looking follow-ups. Deferred by decision, not oversight — each entry r
**Done looks like.** Not stated in PLAN.md.
## FX-GUID keying for `restoreFxOffline` (Design View park/restore)
**Context.** CONTEXT.md's "Open questions to resolve during build" (Design View section): the bulk of reconcile residuals shipped (`ViewModeModel::reconcile(liveGuids)` prunes orphaned snapshots on every toggle/load; folder restructure is self-healing because the tree is rebuilt each toggle; membership is intentionally kept so undo-delete preserves the tag). Two sub-items were left deferred out of that; this is the first.
**The wart.** `restoreFxOffline` currently restores per-FX offline state by slot index. If the FX chain is reshuffled while a track is parked, restore lands on whatever plugin now occupies that slot rather than the plugin it was originally captured from.
**Intended fix.** FX-GUID keying — key the per-FX offline snapshot entries by FX identity rather than slot index.
**The constraint the fix MUST handle.** The keying change requires a snapshot-schema migration; CONTEXT.md names this alongside the keying change as the reason the fix was deferred rather than folded into the reconcile-residuals work.
**Priority / risk.** Not stated in the source.
**Done looks like.** Not stated in the source beyond the fix description above.
## Dormant membership entries in persisted `view_state`
**Context.** CONTEXT.md's "Open questions to resolve during build" (Design View section), the second of the two sub-items left deferred after the reconcile-residuals ship described above.
@@ -150,6 +138,28 @@ Forward-looking follow-ups. Deferred by decision, not oversight — each entry r
**Done looks like.** Not stated in the source beyond "confirm no surprising fight."
## Spline overlay's drag-off delete margin may be too generous for its box
**Context (what shipped — Θ-W5-T1, spline-egs).** `kCurveDragOffMargin = 24` (`editor_internal.h`) was sized for the velocity-curve popup, whose editing box floats with slack on all sides — the popup's own sheet border sits well outside the box, so 24px of overshoot before a drag-off delete arms is comfortably inside the sheet. The Spline EG overlay reuses the same constant and the same drag-off-delete logic verbatim (`editor_paint_waveform.cpp`), but its box abuts the deck directly with no equivalent slack.
**The wart.** Dragging an overlay contour node toward the bottom of the waveform band and overshooting roughly 24px past the box floor carries the drag into the deck below and arms a delete — a gesture that reads as "drag toward the deck" rather than "delete this point." Mitigations already in place: a WARN paint cue while the drag is armed-to-delete, and `VelocityCurve::deletePoint` unconditionally refuses the two endpoints regardless of margin.
**Intended fix.** Not yet proposed — likely a smaller, overlay-specific margin (or a margin derived from the actual gap between the overlay box and the deck) rather than sharing the popup's constant.
**The constraint the fix MUST handle.** Whatever margin the overlay uses must still comfortably permit an intentional delete-by-drag-off gesture (the design's stated point-removal path) without shrinking it into a hair-trigger; the popup's own margin and delete behavior must be left untouched.
**Priority / risk.** Low, pending Daniel's hands-on assessment. Flagged by code review as an unmeasured UX judgment, not a confirmed defect — whether the overshoot is a real hazard in practice is Daniel's call.
**Done looks like.** Daniel has used the Spline EG overlay hands-on and either confirms the current margin is fine as shared, or a separate overlay margin is chosen and the WARN cue's trigger point is verified to match it.
## Pre-existing staged-envelope-node shadow at zero-attack (AttackEnd on Origin)
**Context (what shipped — Θ-W5-T1, spline-egs).** The staged envelope-node hit-test (`nodeAtPoint`, `envelope_edit.cpp`) and the drawn contour's node hit-test now feed the SAME `WaveformClaim` arbitration slot in `resolveWaveformClaim` (`spline_edit.h`), which resolves competing waveform-band claims — node, crossfade tab, marker column — by smallest nominal target area among the candidates that actually hit. This is the same defect class as the contour-node/marker collision W5 fixed by replacing check-order resolution with that arbitration.
**The wart.** A zero-attack `AttackEnd` vertex is drawn at the same pixel as `Origin` (the envelope's non-draggable start anchor), which for an AHD envelope sits at the start marker's frame. Because a node's nominal pick-box area is smaller than the marker's full-height grab-column area, and `resolveWaveformClaim`'s rule is "smallest area among hit candidates wins," the draggable `AttackEnd` node still claims the click over the start marker when the two coincide — and, at a loop starting there, over the crossfade tab. Folding the staged pass into the shared arbitration slot did not change this specific outcome, since the rule that decides node-vs-marker priority is unchanged from what the contour-node fix established. `Origin` itself is excluded from `nodeAtPoint`'s candidate set entirely (never draggable, never a hit), so the common case — attack > 0, no coincidence — is unaffected.
**RESOLVED — Γ-W2-T2 (`loop-crossfade-ux`), incidentally.** Giving every mark the cap-grip the crossfade already had is what closed it: the start marker now carries an 11x10 cap in the overlay's top strip, whose nominal area (110) is smaller than the node's fixed pick box (169), so the cap wins the coincident pixel and the marker is reachable again. No priority rule was added and `resolveWaveformClaim` is byte-for-byte unchanged — but the cap slot's own nominal area DID move, from the old clipped-actual measure (60 at frame 0) to the new nominal 110 every cap now feeds it (`markerHandleRect`'s own unclipped area). That move leaves the `cap < node < column` ordering unchanged only because 110 is still under the node's fixed 169 — the outcome held, not the area. Below the cap strip the node keeps the click, which is correct: that is where the node is actually drawn for any non-degenerate envelope. Pinned by `testAMarkCapOutranksACoincidentEnvelopeNodeInTheTopStrip` (`tests/test_spline_edit.cpp`). `Origin` was not touched and `isDraggable`'s shape rules are unchanged.
## Active-bank indicator placement (B4 polish)
**Context.** CONTEXT-ARCHIVE.md's "Open questions to resolve during build" (B4 panel section): forks 15 are all settled; one panel-polish detail remains open. Fork 4 already settled that the active-bank indicator must be "visually unmistakable" — only its placement is undecided.
@@ -163,3 +173,736 @@ Forward-looking follow-ups. Deferred by decision, not oversight — each entry r
**Priority / risk.** Not stated as a priority level; the source characterizes this as a "panel-polish detail."
**Done looks like.** Not stated in the source beyond choosing one of the three placement options.
## Confirm the card name strip reads legibly at the shipping cell size (Ψ-W2-T1 DAW verification)
**Context.** Ψ-W2-T1 (`capture-naming`) put the capture's label on the docked panel card,
across the top of the cell, drawn OVER the waveform thumbnail. Review found the strip's
text/primary was measured at ~1:1 contrast against the accent-lime waveform fill at the
shipping 140×84 cell size — a loud capture's peak reaches into the strip on 12 of its 13
rows — and remediated it with a bg/base scrim behind the name (`kCardNameScrimAlpha`,
`core/ui/theme.h`) sized so the composite clears the WCAG 4.5:1 body floor against both the
bare fill and bare bg/cell (pinned in `test_theme.cpp`).
**The wart.** The floor math is verified; the actual on-screen read is not. No `[verify —
DAW]` deferral was filed for this track's acceptance criterion ("the panel card shows the
name") when it landed, unlike the sibling Ψ tracks.
**Intended fix.** N/A — no code change. Daniel views the docked panel with real captures
(quiet and loud material, long and short names) and confirms the name reads over the
waveform at the shipping cell size.
**The constraint the fix MUST handle.** N/A — verification only.
**Priority / risk.** Not stated. The math clears its floor with real margin (see
`testCardNameScrimClearsBodyFloorOnItsWorstBackground`), so this is a confirmation step,
not a suspected defect.
**Done looks like.** Daniel confirms the card name reads legibly over both quiet and
loud waveform material at the shipping 140×84 cell size, or a follow-up adjusts the scrim
alpha and this entry is re-filed against the new value.
## A realtime capture interrupted by a project switch leaves an untracked file behind
**Context (found by the tracking-consolidation review, 2026-07-30).** `DriveRealtimeCapture` detects that the active project is no longer the one the in-flight capture belongs to, aborts the backend, and drops the handle. On a `Done` abort the backend has *already* moved the recorded WAV into the **original** project's bank folder (`capture_realtime_finalize`), so a file the tool created exists with no bank entry and no ledger record.
**The wart.** This is the one hole in "no silent gaps": a system-created file that is never recorded. It is in the safe direction — an untracked file is foreign, so prune will never reclaim it — but it is permanent, and the bank folder grows by one orphan per interrupted record.
**Intended fix.** Record the birth against the project the capture belongs to. Neither half is available at the switch point: `session`'s ledger and `saveToActiveProject` both target the *active* project, which is by definition the wrong one here.
**The constraint the fix MUST handle.** Writing the record into the now-active project would attribute another project's file to it — a worse error than the gap, since prune would then consider deleting a file it does not own the folder for. Deleting the stranded file instead was considered and rejected: it is the user's just-recorded audio, and prune is the system's only deletion authority over bank-folder bytes (`shell/persist/CLAUDE.md`) — a shell self-cleanup exemption covers transient scratch, not a finished recording. The fix therefore needs a deferred write against a *named* project (or a re-entry into the original project on the next poll), not a change at the abort site.
**Priority / risk.** Low / deferred. Mitigated in the meantime: the console message names the stranded file's project-relative path, so the operator can recover or remove it rather than discovering it later as an unexplained orphan.
**Done looks like.** Switching projects mid-record leaves the recorded file with a ledger record in the project it belongs to, so a later prune of that project can reclaim it normally.
## ~~Raise the stage-time ceiling above 2 s for long-decay sound design~~ — SCHEDULED, no longer deferred
**This entry is discharged into `docs/PLAN.md` at Γ-W1-T1 and is retained only as a pointer.** Daniel reversed Γ-F3 the same day he ruled it (2026-08-01): *"extend the stage lengths to 10s."* `kEnvTimeMaxSeconds` / `kGateStageMaxSeconds` move **2.0 → 10.0 in Γ-W1-T1**, beside the taper work rather than after it.
**Why the reversal, since the deferral's reasoning was sound.** The deferral said the right time to judge a 5× range change is with the new taper in the DAW under the hand. What changed is not that judgement but the **cost of waiting**: Ruling 1 schedules VST3 parameters inside the same phase (Γ-W4-T1), and a range endpoint is part of the host-facing normalization exactly as much as the curve between the endpoints is. Raising the ceiling is free this wave and permanently expensive four waves later — the same one-way door `docs/product/parameter-automation.md` §4 states for the taper itself, and §8 sweeps for exhaustively.
**What this entry contributed, and where it now lives.** Its two prerequisites (the log taper; `resetDeckParam` bypassing the taper, since 2.0 is a power of two and 10.0 is not) were already in Γ-W1-T1 and are now load-bearing rather than incidental. Its named hard part — *"the constant change is trivial; keeping the drawing legible is not"* — is now in-scope design work, specified at `docs/product/instrument-control-surface.md` §4.3.1: at 10 s a 30 ms attack is 0.3 % of the AHDSR schematic's stage domain, and the answer is to make the schematic axis **be** the taper, so a node's position within its stage slot is its knob's needle position.
**Nothing here is actionable as a TODO.** Delete this entry when Γ-W1-T1 lands.
## The editor's drag state machine has no seam, and `reasampler_editor.h` is near the ceiling
**Context (Γ-W3, meter re-review).** `reasampler_editor.h` stands at **564 lines** against the
~600-line ceiling — 36 lines of margin — and it keeps growing because every new surface on the
Sample face adds its transient state there. The obvious seam is the drag state machine: `drag_`
plus the per-gesture anchors it is read against.
**Why it was declined rather than taken.** `drag_` has **42 references across 13 shell TUs**
(measured over `src/shell/instrument/*.cpp`; the declaration in the header is additional). Of
the six input TUs, three write it and branch on it (`editor_input`, `_waveform`, `_curve`) and
three only write it (`_chrome`, `_browse`, `_deck`) — which is what makes the anchor invariant
observed rather than enforced. Extracting it is a real refactor of the editor's input half, not
a header move — and doing it inside a wave whose subject is the MASTER deck would have put an
unrelated high-blast-radius change in the same diff. Declining was right; leaving it unrecorded
was not.
**The shape a fix would take.** A `DragState` type owning the kind plus its anchor payload,
with the input TUs mutating it through named transitions rather than assigning `drag_` and its
anchors independently — which is also what would let the invariant "an anchor is only readable
while its own `DragKind` is in flight" be enforced rather than observed. `editor_interaction.h`
already holds the `DragKind` vocabulary and is the natural home.
**Priority / risk.** Low, but the margin is the clock: the next surface that adds two members to
the header takes it over the ceiling, and at that point the seam gets chosen under time pressure
by whoever is unlucky. Take it before that, not after.
**Done looks like.** `reasampler_editor.h` is back under the ceiling with room; no TU assigns
`drag_` and an anchor as two independent writes; and the transitions are named where the
`DragKind` catalogue already lives.
## `Sample::sourceMode` has no value meaning "produced by the instrument"
**Context (what shipped — Ξ-W2-T1, resample-bake-chain).** A resample bake's landed
`Sample` entry (`bake_land.cpp`) never sets `sourceMode`; it is left at the struct
default (`SourceMode::MasterMix`) rather than recording that the entry's audio came
from the instrument's own offline render, not from a capture backend.
**The wart.** A baked capture is indistinguishable, by `sourceMode`, from a master-mix
render — the bank has no way to tell "this file was produced by ReaSampler 9000" from
"this file was rendered off the master bus."
**Intended fix.** Add a `SourceMode` value for instrument-produced audio and set it at
the one landing site.
**The constraint the fix MUST handle.** `bank_model.cpp`'s deserializer rejects any
`sourceMode` value outside `MasterMix(0)..Realtime(5)` by failing the whole bank
blob's parse (`parseSample` returns `false`), not just that one field — so appending a
new enumerator is a forward-incompatible bank-format change: an older extension build
reading a newer project's bank would refuse to load it entirely. This needs its own
decision (a version-gated field, or accepting the compatibility cost) rather than a
one-line enum append.
**Priority / risk.** Low / deferred. Logged at Ξ-W2-T1's review rather than folded in.
**Done looks like.** A baked capture's `sourceMode` reads as instrument-produced, and
the compatibility question (how an older build reads a bank containing the new value)
is answered rather than left to fail closed by accident.
## `instrument_bake` doubles peak memory on the WAV build
**Context (what shipped — Ξ-W2-T1, resample-bake-chain).** `runBake` (`instrument_bake.cpp`)
copies the render's interleaved `float` buffer (`BakeAudio::interleaved`, `AudioSample
= float`) into a `std::vector<double>` before handing it to `buildFloat32Wav`, which
takes doubles and narrows back to float for the bank's 32-bit-float WAV contract.
**The wart.** The copy roughly doubles peak memory for the bake — an 8-byte double
holding a value that started and ends as a 4-byte float — for the duration of the WAV
build on a large bake.
**Intended fix.** Either give `buildFloat32Wav` (or a sibling entry point) a
`float`-input overload so the bake path narrows nothing it doesn't already own in
`float`, or narrow lazily during the WAV build instead of pre-copying the whole
buffer.
**The constraint the fix MUST handle.** `buildFloat32Wav`'s `double` parameter is
shared with every other caller in `core/capture/wav_codec`; a fix must not change
those callers' contract or add a second WAV-building code path to maintain.
**Re-confirmed still accurate (2026-08-02), after the mono-collapse landing touched
`wav_codec` adjacent to this site.** `applyMonoCollapse` operates on the staged bytes in
`bake_landing.cpp`'s `prepareLanding`, upstream of and unrelated to `runBake`'s
`std::vector<double>` copy in `instrument_bake.cpp`; `buildFloat32Wav`'s signature is
unchanged. The wart stands exactly as described above.
**Current blocker.** Not taken this wave because `instrument_bake.cpp` is being edited
by a live VST3-parameter track.
**Priority / risk.** Low / deferred. Logged at Ξ-W2-T1's review; correctness is
unaffected, only peak memory on a large bake.
**Done looks like.** A bake's peak memory no longer includes a full double-precision
copy of the rendered buffer, with `buildFloat32Wav`'s other callers unchanged.
## The deck layout rework — SPECCED, and the original shape SUPERSEDED
**Status (2026-08-01): no longer a deferral. The design notes Daniel owed this entry have
arrived, and they change the shape.** The rework is specced in
`docs/product/instrument-control-surface.md` §1 and sequenced as **Phase Γ** in
`docs/PLAN.md`. This entry is retained only until that work lands, because one loose end
below (the Θ-W4-T2 acceptance criterion) still needs an explicit disposition.
**What was superseded, and confirmed superseded by Daniel.** The original entry recorded a
directive of Daniel's for **one row of much *taller* decks with knobs stacked *within* a
deck** (his example: the filter's static knobs above its envelope knobs). **The new framing
replaces that.** The decks stay **single-height with knobs side-by-side**; what becomes
one row is the **sound** category (PITCH/RATE, FILTER, VELOCITY, VOICE), with the three
envelope decks on a second **contour** row and MASTER as a double-height deck spanning both.
The within-deck stacking idea is retired, not deferred.
**The measured-geometry block that used to live here has been deleted, not moved.** It was
taken at the 840 px floor with `kDeckCellW = 48` and is wrong twice over — Θ-W6-T1 changed
both the floor (980) and the cell metrics (60 × 74). The current, re-derived geometry — every
group's width, both row totals, and the resulting 1198 × 680 floor — is the table in
`docs/product/instrument-control-surface.md` §1.2. **Do not resurrect the old numbers.**
The unresolved 864-vs-872 px VELOCITY↔VOICE adjacency-threshold discrepancy is retired with
them; it was measured against a layout that no longer exists.
**The one live loose end.** Θ-W4-T2's acceptance criterion *"VELOCITY sits immediately to
the left of the VOICE group"* is not met at the default window size today. Under the new
layout it **is** met by construction — row 1 is PITCH/RATE, FILTER, VELOCITY, VOICE, in that
order, at every window width — so the criterion is satisfied rather than retired. Confirm it
when Phase Γ-W3 lands and remove this entry.
**Done looks like.** Phase Γ-W3 (`deck-reflow`) has landed; the VELOCITY↔VOICE adjacency
criterion is confirmed met at the floor width; this entry is removed.
## The AA waveform stroke's cost on the docked bank panel's card thumbnails
**Context (what shipped — Θ-W6-T1, legibility-and-antialiasing).** The antialiasing
audit fixed the min/max waveform column plot by adding an AA `LICE_FLine` stroke across
each column's extremes, on top of the existing fill (`draw_kit.cpp` `drawWaveform`).
`drawWaveform` is shared by the editor's hero waveform lanes, the docked bank panel's
card thumbnails, and the browse cards — the stroke lands on all three.
**The wart.** Measured cost (Release, MSVC 14.44, real LICE, 24 stereo cards ×
136 columns = 6528 columns): fill alone 0.070 ms per full-grid repaint, fill+stroke
0.48 ms — the stroke adds ~0.41 ms, about 2.5% of a 60 Hz frame. At card-thumbnail
scale the added smoothness is far less visible than on the editor's hero lanes, so the
cost is paid on every repaint of every card for a benefit concentrated in one consumer.
**Intended fix.** The identified cheap lever: skip the stroke below a card-sized box
and keep it only on the editor's hero lanes.
**The constraint the fix MUST handle.** Not done, because it is a product call about
where the comb artifact — the min/max column plot's jagged outline — actually reads
badly enough to matter, not a performance-forced decision (2.5% of a frame on
hover/scroll/drag repaint, not a continuous cost, is not itself disqualifying).
**Priority / risk.** Low. The measurement is a one-off scratchpad number
(`docs/product/visual-design-language.md` §8), not a standing regression guard —
re-measure before relying on it again.
**Done looks like.** A size threshold (or explicit per-consumer flag) below which
`drawWaveform` skips the AA stroke, with the panel/browse cards confirmed still
readable and the editor's hero lanes unchanged.
## High-DPI host scaling is unverified (distinct from the antialiasing audit)
**Context (what shipped — Θ-W6-T1, legibility-and-antialiasing).** The antialiasing
audit (item 13) confirmed every drawn surface renders smooth at 100% scale — the
disposition table in `docs/product/visual-design-language.md` §8 is the record. That
audit is about rasterization quality at the pixel level the plugin already draws at;
it says nothing about what happens when a host scales the plugin window itself.
**The wart.** Nothing in the instrument implements `IPlugViewContentScaleSupport`. A
host that applies DPI scaling to the plugin window resamples the already-rasterized
output rather than asking the plugin to redraw at the target resolution — every AA
guarantee the audit just confirmed (and the piano-key uniform-width guarantee, §8.1)
holds only at the client-pixel level the plugin itself draws, not above it.
**Intended fix.** Not proposed. Implementing `IPlugViewContentScaleSupport` (or
confirming the host compositor's resampling is acceptable without it) is the shape of
a fix, not yet scoped.
**The constraint the fix MUST handle.** Not yet known — no design work has started.
**Priority / risk.** Not stated. Recorded as a gap, not a defect: no host behavior has
been observed to be wrong, only unverified.
**Done looks like.** Either `IPlugViewContentScaleSupport` is implemented and the
AA/uniform-width guarantees are re-verified at a scaled client size, or a decision is
recorded that host-side resampling of the rasterized output is an accepted tradeoff.
## The analytic stroker's scaled fallback path is unexercised
**Context (what shipped — Θ-W7-T1, arc-and-spline-aa).** `blendCanvas`
(`shell/instrument/editor_stroke.cpp`) guards against `LICE_EXT_GET_SCALING` being
active by falling back to a per-pixel `LICE_PutPixel` path, because the primary raw-bits
path derives its geometry from logical width/height while writing through
`getRowSpan()` — under an active scale that would misplace the stroke or write past the
DIB allocation.
**The wart.** Nothing calls `SET_SCALING` today, so the fallback path never runs. Under
an active scale it would rasterize the coverage mask at *logical* resolution with each
logical pixel expanded to a scale-sized block — geometrically correct but blocky rather
than resolution-independent. This connects to the already-filed high-DPI host-scaling
deferral above; cross-referenced here rather than duplicated.
**Intended fix.** Not proposed — same shape as the host-scaling deferral above:
implementing (or verifying) genuine scale-aware rasterization is the shape of a fix, not
yet scoped.
**The constraint the fix MUST handle.** Not yet known — no design work has started, and
none can usefully start before the host-scaling deferral above is resolved, since that
is what would first exercise this path.
**Priority / risk.** Low / deferred. Recorded as a gap, not a defect: the fallback is
guarded, correct-but-blocky rather than wrong, and unreached by anything in the tree
today.
**Done looks like.** Either the fallback path is exercised under a genuinely scaled
bitmap and confirmed to place the stroke correctly, or it is redesigned to rasterize at
physical rather than logical resolution once `IPlugViewContentScaleSupport` (or
equivalent) makes scaling real.
## The loop intrinsic is folded twice: the bank blob and the instance ref can skew
**Context (what shipped).** Two call sites answer the same question — "does this capture
have a sustain loop, and where?" — by different routes, and both are load-bearing:
- `ReaSamplerEditor::pickedMarkers` (`shell/instrument/editor_session.cpp`) resolves the
intrinsic from the **live bank blob** first (`selectSample`), falling back to the
instance-owned `SampleRefs` only when the blob is unreadable, then lets
`params_.loopOverride` supersede it.
- `ReaSamplerProcessor::reloadInstrument` (`shell/instrument/processor_reload.cpp`)
resolves it from the **instance ref** via `resolveCapture`, which is the one
override-beats-intrinsic fold, and that is what the bake renders and what
`bakeWindowNeedsHold` is ultimately asked about.
**The wart.** The two can disagree whenever the bank blob's loop for a capture differs
from the copy in the instance's own refs table — a recapture that moved the loop points,
a hand-edited blob, or an instance that predates the current bank state. The face then
draws (and the Hold predicate answers about) one loop while the engine plays another.
**Pre-existing.** This split predates the derived-bake-window work; the bake-Hold
predicate is only a new *consumer* of `pickedMarkers`, not the origin of the divergence.
**Intended fix.** Route `pickedMarkers` through `resolveCapture` so both sites share the
one fold, as the bank/refs paths already do elsewhere.
**The constraint the fix MUST handle.** `pickedMarkers` runs on the editor's mouse-down
arbitration path (every waveform click, not just marker grabs) and deliberately skips its
bridge read once an override is set; a unified fold must not put a bank read back on that
path. It must also keep the browser-source semantics: the bank is where a *new* capture's
intrinsics come from, the refs table is where the *loaded* one's live.
**Priority / risk.** Low. Needs a recapture-moved-the-loop scenario to observe, and the
failure is a mis-drawn marker or a spuriously shown/hidden Hold knob, not bad audio.
**Done looks like.** One fold answers the intrinsic for both the editor's markers and the
engine's reload, with a test that moves the bank's loop out from under a loaded instance
and shows the two agreeing.
## `ingestHandleSectionCommand` has no unit test
**Context (what shipped — Ψ-W1-T3, media-explorer-section).** The Media-Explorer
import now dispatches through two hooks — `ingestHandleCommand` (Main,
`"hookcommand"`) and `ingestHandleSectionCommand` (Media Explorer,
`"hookcommand2"`). Both live in `ingest.cpp`, which compiles straight into the
`reaper_reasampler` MODULE target.
**The wart.** No `shell/` translation unit in this repo has a test target — every
`<module>_tests` executable is a `core/` pure-module target. `ingestHandleSectionCommand`
is a two-line command-id comparison; correctness here rests on code review, not CTest.
Review verified this constraint is real and the deferral correct.
**Intended fix.** Make `action_registry` a linkable library and give it the repo's
first `shell/` test target, driven by a fake `reaper_plugin_info_t`. Its own header
(`reaper_plugin.h:153-172`) shows `Register` is a plain member-function pointer on the
struct, not a REAPER API pointer resolved through `REAPERAPI_LoadAPI` — a fake instance
needs no live REAPER process to exercise `rec->Register(...)` calls. Once
`action_registry` is test-covered, move the Media-Explorer section registration into it.
**The constraint the fix MUST handle.** The extraction alone buys nothing:
`action_registry` has no test target today either, so lifting `ingestHandleSectionCommand`
into it without also standing up the test target just relocates the untested code. The
same follow-up could collapse `ingest.cpp`'s `ingestRegisterActions` hand-rolled `command_id`+`gaccel`
pair onto `action_registry::registerAction`, which already does exactly that dance for
the Q-W6 table.
**Priority / risk.** Low / deferred. `ingestHandleSectionCommand` is a two-branch
comparison, reviewed and correct at this scope; the gap is the missing test seam, not a
known defect.
**Done looks like.** `action_registry` is a linkable library with its own `shell/`-first
CTest target driven by a fake `reaper_plugin_info_t`; the Media-Explorer section
registration and `ingestHandleSectionCommand` move into it and gain unit coverage; and
`ingest.cpp`'s own `command_id`+`gaccel` registration collapses onto
`action_registry::registerAction` where the shapes match.
## The `&128` multi-track output shape is still DAW-unobserved, and a refusal now rests on it
**Context.** The multi-track TRACK capture no longer lands one track's audio under an
`Ok`: `renderOffline` refuses every selected-tracks render covering more than one track,
both scopes, naming the way out (`render_settings::isMultiTrackStemRender` /
`multiTrackRefusalMessage`). What did NOT change is the evidence: the per-track-output
reading of `&128` is still INFERRED from the SDK header documenting the single-file bit
`&(4<<16)` for item/razor sources only. It has never been observed in a DAW.
**The wart.** The refusal is therefore as unverified as the defect it closes. If REAPER
in fact sums a multi-track `&128` render into the single literal `RENDER_PATTERN`, the
refusal costs a working capture — a user who selects two tracks and captures gets a
message where a correct summed file used to land.
**Intended fix.** Run the observation in `docs/verify-track-scope-multitrack.md` §3 (a
hand-driven Render dialog, source "selected tracks via master", one literal filename, two
tracks selected — then count the files REAPER writes). If it comes back "one file per
track", nothing to do and the inference is retired into fact. If it comes back "one
summed file", the refusal is over-strict for the TRACK scope and should be narrowed back
— and the ITEM-scope half is then an OPEN question, not settled: a full-extent item
capture already sums a multi-track item selection via `&32|single-file`
(`test_render_settings.cpp`'s `testMultiTrackStemRenderIsNamedForRefusal`), so if `&128` also sums, a ranged item capture
routed through it sums too, and keeping the item refusal in that branch would make item
scope inconsistent with itself across the range boundary (full-extent sums, ranged
refuses, same scope). Whether that inconsistency is acceptable or the item refusal should
narrow too needs its own look at that point — not decided here.
**The constraint the fix MUST handle.** Narrowing the refusal must keep the ITEM scope
refusing, must keep `renderOffline` the single seam (so a recipe replay cannot diverge
from a fresh capture), and must not re-open the collapse for any caller that reaches
`&128` later — the predicate is keyed on the render source precisely so new callers
inherit it.
**Priority / risk.** Low and bounded either way: the current behavior refuses rather than
lands wrong audio, so the cost of being wrong here is a refused capture, not a bad one.
**Done looks like.** The `&128` multi-track output shape is DAW-observed and written into
`src/shell/capture/CLAUDE.md` as fact rather than inference, and the refusal is either
kept as-is or narrowed to the item scope with that observation cited.
## A `SelectedItems` recipe replays against whatever items are selected then
**Context (surfaced by Ψ-W1-T1, capture-range-exactness).** `RunRecaptureFromSource`
rebuilds a `CaptureRequest` from the recorded `CaptureRecipe` and resolves its source
tracks by GUID. `renderOffline` engages `RenderTrackSelection` only when the recipe's
source mode is `SelectedTracks`, which is what makes a ranged item capture and a
track capture replay against their recorded tracks rather than the live selection.
**The wart.** A recipe whose source mode is `SelectedItems` — every pre-fix item-scope
capture, and every post-fix full-extent one — renders `&32`, which prints whatever
items happen to be selected when the replay fires. The recorded recipe therefore does
not fully determine the audio it reproduces, which is what "recapture from source"
promises.
**Intended fix.** Not proposed. The recipe stores tracks and a range; it carries no
item GUIDs, so no guard on the shell side can reconstruct the item selection from
what is recorded. Closing it means widening `CaptureRecipe` (a wire-format change with
a version rung) or re-sourcing full-extent item captures through the tracks render too,
which would drag them onto the isolation path for no gain.
**The constraint the fix MUST handle.** Widening the recipe must keep every already-
persisted recipe readable, and must not make a replay depend on items that no longer
exist — a deleted source item has to degrade to a stated refusal, not a silent
substitution.
**Priority / risk.** Pre-existing; not introduced or worsened by the range-exactness
work. Harmless when the user re-runs a recapture with the same items still selected,
wrong when they do not.
**Done looks like.** A `SelectedItems` recapture either reproduces its recorded audio
from the recipe alone, or refuses with a message naming what the recipe cannot pin
down.
## An overlapping item on the source track itself is not isolated from a ranged item capture — DECIDED, not deferred
**Context (surfaced by Ψ-W1-T1, capture-range-exactness).** The re-source to the
selected-tracks render (`&128`) needed transient upstream silencing so an item capture
did not also print folder children and receives; `render_isolation` (`UpstreamIsolation`)
covers both. A third widening exists in the same shape: a non-selected item on the
SAME track that overlaps the requested range is now audible in the render, where the
pre-fix `&32` selected-items source excluded it by construction (that source only ever
prints the selected items).
**This is a decision, not a gap.** `src/shell/capture/CLAUDE.md` states the reasoning in
full and it is not repeated here: `UpstreamIsolation`/`render_selection` silence and
select TRACKS because the recipe that replays a capture stores tracks and a range, never
item GUIDs — a mute plan keyed to today's overlapping item could not be recomputed at
replay time, so muting items would make the capture stop reproducing itself. The named
candidate (a) in `docs/PLAN.md` §Ψ-W1-T1 carried exactly this semantic edge; it was
weighed against candidate (b) (an item-bounds render with a derived start time) and (a)
shipped with the edge accepted rather than closed.
**Priority / risk.** Low in the common case (one item per track over the captured range is
the normal shape); a project with deliberately overlapping items on one track is the one
that surfaces it, and the practical mitigation is unchanged from before this track:
select/move the neighbour, or capture at track scope instead.
**Done looks like.** Nothing to do — recorded so a future reviewer does not read the
non-isolation as an oversight and re-propose closing it against the recipe's stated
tracks-and-range-only shape.
## A 0-byte render can still pass every gate under Auto/Manual tail (closed)
**Context (surfaced by Ψ-W3 review).** `OfflineRenderBackend::capture`'s exists-check
passes for a 0-byte file, and the bounds gate used to fire only when `expectedFrames > 0`
— an invalid/empty layout read `expectedFrames == 0` and skipped the gate rather than
refusing, so a 0-byte render reached `stampCaptureSample` and landed as
`CaptureStatus::Ok` with an empty `contentHash` and `channelCount == 0`.
**Narrowed, then reopened as an asymmetry.** `shell/capture/render_bounds_gate` was
first changed to refuse an unmeasurable render (invalid layout, or a layout declaring no
sample rate) instead of skipping it — but that gate only ever judges `TailMode::None`,
so a 0-byte render under Auto/Manual still landed as `Ok`, while `None` now refused and
quarantined the identical file. The two tail modes disagreed on a defect neither should
accept.
**Closed.** `capture.cpp` now checks `checkRenderedFileNotEmpty` right after the
exists-check, on every tail mode, before the `TailMode::None`-only bounds gate runs —
a 0-byte render is refused and quarantined identically regardless of tail mode. The
refusal reuses `CaptureStatus::BoundsMismatch` rather than minting its own status; the
earlier note here preferred a distinct status, and that preference is unresolved, not
withdrawn.
## `renderHonoredBounds`'s one-frame tolerance is empirical, not proven
**Context.** The millisecond-floor defect that motivated this gate is closed
(`docs/COMPLETED.md`), but the gate itself — `render_window.h`'s
`renderHonoredBounds` — carries a one-frame tolerance that carried through the fix
unchanged and was never itself proven.
**The wart.** A renderer that resolves the window's two edges by DIFFERENT
conventions can sit two frames from `frameCountFor`'s answer on a
correctly-honored render. That cannot account for the 8- and 38-frame shortfalls
the floor produced (`docs/COMPLETED.md`), so it was not the cause of those
refusals — but it means a future one- or two-frame refusal may be the gate's own
edge convention rather than a real defect.
**Intended fix.** Not proposed. Widening the tolerance is a precision-invariant
decision, not a bug fix, and was deliberately not taken on speculation.
**Priority / risk.** Low. Nothing to date implicates the tolerance itself;
recorded so a future narrow refusal is investigated rather than assumed to be
the same floor.
**Done looks like.** Either the tolerance is confirmed correct by a DAW
observation that isolates edge-convention behavior from bounds-floor behavior,
or it is widened with the reasoning recorded.
## `TailMode::Auto` and `Manual` have no automatic bounds observation
**Context.** `render_bounds_gate.cpp`'s `checkRenderedBounds` returns early for
anything but `TailMode::None`, so the millisecond-floor fix (`docs/COMPLETED.md`)
was measured only against `TailMode::None` — Auto and Manual were never
observed, before the fix or after it.
**The wart.** The inference that Auto/Manual are fixed too is sound — same
bounds path, same floor, same fix — but it is an inference, not a measurement.
`checkRenderedFileNotEmpty` runs on every tail mode and still catches a 0-byte
render, but that is the ONLY automatic bounds signal Auto/Manual get; a
floored or otherwise short-but-nonzero render under either mode would land as
`Ok` with nothing to catch it.
**Intended fix.** Not a code change — a DAW observation. `docs/VERIFICATION.md`'s
"Capture range and bounds" section already carries the manual check: repeat an
off-grid-start capture at Manual over a source loud to the window's end and
check the landed frame count against window + `tailMs`; Auto can't be checked
by count (it trims trailing silence) and needs the null test by ear/inversion
instead.
**Priority / risk.** Low. Both modes share the same bounds path as the
now-fixed `TailMode::None`, so nothing suggests they still floor — but nothing
confirms it either.
**Done looks like.** A DAW-observed Auto and Manual capture, each landing the
window as requested, closes the inference into fact — or surfaces a
mode-specific divergence this entry does not currently know about.
## Floor, ceil and round are not the identity on a millisecond grid point in binary double (caution, not an open question)
A discarded compensation design for the millisecond-floor defect
(`docs/COMPLETED.md`) rested on the premise that a grid-aligned value survives a
bare floor/ceil/round unchanged. That is false in binary double: `1.007 * 1000
== 1006.9999999999999` (floors to 1006, not 1007), and `4.068 * 1000 ==
4067.9999999999995` (floors to 4067, not 4068). The compensation this premise
would have supported is no longer needed — the fix moved the render to a bounds
mode that does not floor at all — so this is not a live open question. Recorded
because it would bite any future millisecond-grid arithmetic that assumes an
on-grid value is safe from a bare floor: `render_window.h`'s own
`isOnMillisecondGrid`/`msFlooredEndFrameCount` already carry the nanosecond
tolerance that handles it correctly on this codebase's side of the boundary; the
trap is for whoever writes the next piece of grid arithmetic without that guard.
## `capture.cpp` is over the ~600-line ceiling — the seam is identified, taking it is blocked
**Context.** Removing the settled bounds experiment's instrumentation (the console
verdict and the three-checkpoint `RENDER_STARTPOS`/`ENDPOS` read-back) brought the file
from 697 to **620 measured lines**, against root `CLAUDE.md`'s ~600-line ceiling. The
seam that entry originally named is gone with the instrumentation; nothing left in the
file is bisectable without cutting load-bearing why.
**The remaining seam is a real responsibility boundary**, and the file header already
names it as two things: `OfflineRenderBackend::capture` (the offline render driver)
versus the four helpers BOTH backends share — `makeUniqueTag`, `captureNameFor`,
`collapseCapturedFileToMono`, `stampCaptureSample` — consumed by `capture_batch`,
`capture_orchestrator`, `capture_realtime_shell`, `capture_realtime_finalize` and
`render_in_place`. Lifting those four into their own TU takes the driver under the
ceiling and gives the cross-backend steps their own home.
**Why not taken.** `src/shell/capture/` has no `CMakeLists.txt` of its own — its sources
are listed in `src/app/CMakeLists.txt`, so a new TU needs an edit there. Forcing the
four helpers into an existing TU instead (orchestrator, realtime finalize) would put
them in a wrong home to dodge one build-file line, which is worse than the overshoot.
## bext TimeReference read-back is not a floor detector (dead end, recorded so it is not re-litigated)
Idea considered and dropped: read a captured file's `BWF:TimeReference` tag back as
independent evidence on the START-edge millisecond-floor question above. `WDL/metadata.h`'s
`WriteMetadataPrefPos` only writes it past its `prefpos > 0.0` guard (`:1301`) — that guard
alone is enough to rule the approach out. One nuance worth recording separately: the
millisecond quantization at `:1382-1383` (`AddMexMetadata`'s `ParseUInt64(val)/1000.0`)
belongs to the MEX caller, not proven to be `WriteMetadataPrefPos`'s own behavior or the
renderer's direct call into it — so even without the guard, a floored bext tag would show
that MEX quantizes, not that the render engine does.
## Split `render_bounds_gate` on the verdict/message vs. filesystem seam
**Context (Ψ-W3 round-two review).** `render_bounds_gate.cpp` mixes pure verdict
composition (frame-count comparison, message text) with filesystem I/O
(`retainRefusedRender`'s `fs::create_directories`/`fs::rename`) in one shell TU. The
verdict half has no REAPER dependency and no filesystem dependency either — it could be
`core/capture`, unit-tested directly instead of only through the pure `render_window`
functions it calls. The reviewer's suggested split: verdict + message composition pure
and testable in `core/capture`, leaving only `retainRefusedRender` (and the two thin
`checkRendered*` entry points that call it) in `shell/capture`.
**Why deferred.** Out of scope for the dispatch that surfaced it — a structural split,
not the bug fix in front of it.
**Filed also because it's already slightly wrong today.** `render_bounds_gate.cpp`
touches no REAPER API (it is `<filesystem>` + the pure `core/capture` modules only), so
`src/shell/capture/CLAUDE.md`'s "this directory is the REAPER API surface only" scope
line no longer describes it — one more small argument for eventually moving the
REAPER-free half to `core/capture`, separate from the untested-filesystem-code gap
above.
**Done looks like.** `core/capture` owns a pure `checkRenderedBoundsVerdict`-shaped
function under a `<module>_tests` target with no REAPER, no VST3 SDK, and no
filesystem includes; `shell/capture/render_bounds_gate` shrinks to the file-move and
the two callers' plumbing.
## The capture path ignores `saveToActiveProject`'s return at four sites
**Context.** `saveToActiveProject()` returns false for exactly two reasons — no active
project, or an unsaved one — and in both cases NOTHING was written. Four capture sites
discard that return outright: `capture_orchestrator.cpp`'s `RunCapture`, `capture_batch.cpp`'s
`RunBatchCaptureItems` and `RunBatchCaptureRazor`, and `realtime_lifecycle.cpp`'s `CommitRealtimeResult`.
**The wart.** A capture on an unsaved project renders the file into the bank folder, adds
the `Sample` to the in-memory book, records a birth record in memory — and loses all three
on reload. The bytes stay on disk with no index entry and no persisted ledger record, so
they are a foreign file prune will never reclaim (an unrecorded file is untouchable by
design — `core/tracking/CLAUDE.md`). Nothing is printed. The bank-op family already reads
this return and discards its undo point on a false; the capture family does not read it at
all.
**Why filed, not fixed.** Pre-existing, and the right answer is a product decision this
dispatch had no mandate for: refuse the capture up front, keep it and warn, or prompt for
a Save-As (the bank ops chose "quiet persist by design, deliberately no Save-As prompt" —
whether capture should follow is a separate call).
**Done looks like.** A capture attempted with no saved project either does not write bytes
at all, or writes them and says so in a sentence naming what will not survive a reload —
and the choice between those two is recorded rather than implicit.
## `panel_input`'s wheel handler persists the whole book per wheel message
**Context.** `panel_input.cpp``handleWheel` calls `markTailDirty()` on every wheel
message that actually moves `manualMs`, while the pointer is over the footer in Manual
mode. (It coalesces sub-notch deltas within ONE message and no-ops at a bound, so the
count is wheel messages that changed the value, not raw notches.)
**The wart.** `markTailDirty` is `saveToActiveProject()` — a full `BankBook` serialize plus
six ext-state value writes on the UI thread — for a setting that is one number. A flick
over the footer is a dozen of them in a few hundred milliseconds. Disproportionate rather
than incorrect: no guardrail is violated (this is nowhere near the two named hot paths),
and the writes are idempotent.
**Intended fix.** Coalesce: mark dirty and let one timer tick flush, the same shape the
panel already uses elsewhere for repaint batching.
**Done looks like.** A continuous wheel gesture over the footer produces one persist, and
the value that lands is the gesture's final one.
## `RunCaptureItemAssign`'s undo point does not follow the pattern its comment claims
**Context.** `capture_orchestrator.cpp`'s `RunCaptureItemAssign` states that the action follows
the bank-op family's discard-on-unsaved pattern.
**The wart.** It does not: `RunCaptureItemAssign` records the undo point unconditionally whenever
`sampleId` is non-empty, and never consults the persist's return at all. So on an unsaved
project it records an undo point for ext-state that was never written — the empty
no-effect entry `persistBankOp`'s guardrail exists to avoid. The comment describes the
intended behavior, not the code.
**Why filed, not fixed.** It is one instance of the capture-family gap filed above, and
fixing it alone would leave the other four sites divergent. Fix them together, or explain
in one place why capture differs from bank ops.
**Done looks like.** The comment and the code agree, and the whole capture family answers
the unsaved-project case one way.
## `core/tracking/CLAUDE.md`'s untracked-file enumeration says "reaches the `.rpp`" too loosely
**Context.** `src/core/tracking/CLAUDE.md` §"Invariants" — "No silent gaps — in memory at
creation, on disk at the next save" — enumerates how a created file can stay
untracked, and describes the ledger as reaching the `.rpp` at the following
`saveToActiveProject()`.
**The wart.** `saveToActiveProject()` writes REAPER's IN-MEMORY project state and marks the
project dirty; REAPER writes the `.rpp` on the project's own save, which may be much later
or never. The sentence was already loose before this branch and is not made wrong by it —
but it is the same over-claim ("a write reached the file on disk") the bake's reporting
pass spent several rounds removing from its own sentences, so it should read the same way.
**Why filed, not fixed.** Editing another layer's own CLAUDE.md from a persist-and-report
dispatch is exactly the boundary crossing the per-directory docs exist to prevent. It is a
doc-keeper edit.
**Done looks like.** The enumeration distinguishes "in the project's state" from "on disk
in the `.rpp`", and does not gain a second home for the distinction.
## `view_mode_model.cpp` is over the ~600-line structural bar, and `view.cpp` is close behind
**Context (surfaced by the FX-GUID keying track).** Root `CLAUDE.md`'s structural
heuristics put an ~600-line ceiling on any one file, with a documented responsibility
seam as the required method for splitting it, not an arbitrary bisection.
`src/core/view/view_mode_model.cpp` measures **815 lines** (verified this pass),
up from 715 before the FX-GUID keying track's v2 schema addition made it worse.
**The named seam.** The JSON codec — `serialize()`/`deserialize()` — wants its own
`view_state_codec` TU in `src/core/view/`.
**Why it was deferred, and this reasoning should survive.** `serialize()` is a
`ViewModeModel` member and `deserialize()` a static factory (confirmed:
`std::string ViewModeModel::serialize() const` and
`std::optional<ViewModeModel> ViewModeModel::deserialize(const std::string&)`), both
reaching private state — so extraction needs either a friend declaration or a new
public accessor surface. Doing that in the same commit that changed the byte format
the golden test literals pin would roll a format change and a codec extraction
together, which is the riskier order.
**`src/shell/view/view.cpp` is no longer over the bar.** It measures **594 lines**
(`wc -l`, re-measured after the undo collapse moved one track's whole park/restore —
snapshot, flags and per-FX offline — into `view_fx_park`'s `parkTrack`/
`restoreTrack`). Recorded because the entry above used to name it as a second
over-ceiling file: if it grows again, note that a further seam there is blocked
not by a private-state/friend question but by a build file another team owns —
`src/shell/view/` has no `CMakeLists.txt` of its own today, so a new TU costs one
`target_sources` line in `src/app/CMakeLists.txt` instead.
**Priority / risk.** Not stated.
**Done looks like.** `view_mode_model.cpp`'s JSON codec is extracted into its own
`view_state_codec` TU (with the friend/accessor question resolved deliberately, not
sidestepped), dropping the file under the ~600-line ceiling.
## FX-GUID stability for the park's restore is unverified in the DAW
**Context.** The Design View park/restore FX keying (`restoreTrack`,
`src/shell/view/view_fx_park.cpp`) rests on `TrackFX_GetFXGUID` returning an identity that
survives a chain reorder while a track is parked. SWS issue #802 reports that after
`SNM_MoveOrRemoveTrackFX` reorders a chain, the FXID lines do not follow the plugin
(`SNM_PreObjectState()``RemoveAllIds()`) — if that still holds, an SWS-driven
reorder while parked produces wrong-plugin restores or mass drops, which is the exact
operation this keying targets.
**What must be checked.** Native drag-reorder, an SWS move, save/reload, and two live
instances of the same plugin.
**Already flagged in code — this entry is the tracked home, not a restatement.**
There is a `[verify — DAW]` marker at `fxGuidString` in `src/shell/view/view_fx_park.cpp` and
a note in `src/shell/view/CLAUDE.md`'s Gotchas; point at them rather than restating
them in full.
**Priority / risk.** Not stated.
**Done looks like.** Native reorder, SWS reorder, save/reload, and a
two-instance-of-the-same-plugin case are each observed in a live REAPER session, and
either the identity is confirmed to survive all four, or a degradation is found and
the keying is amended.
+226
View File
@@ -0,0 +1,226 @@
# DAW verification — post-1.0 work on `dev`
Checks for Θ, Ξ, Ψ, Ε, Ρ, Γ, and Ω work that no unit test can close. Build **Release**, install into
`UserPlugins/`, restart REAPER. Panel tail toggle = **None**, project rate 48000, unless a check says otherwise.
## Precision invariants
- [ ] Dry offline item capture of a 2 s range, re-inserted at its source position, inverted against the source — reads silence (`CLAUDE.md` §"Precision invariants" — "Null test")
- [ ] Run the identical offline capture request twice — the two files are byte-identical on disk (`CLAUDE.md` §"Precision invariants" — "Bit-identical repeats")
- [ ] After any capture, source items and tracks are unchanged: fader, pan, mute, FX bypass, selection (`CLAUDE.md` §"Precision invariants" — "Non-destructive")
- [ ] After a realtime capture, the temp track is gone and every source track's routing is back as it was (`CLAUDE.md` §"Precision invariants" — "Non-destructive")
- [ ] Capture 10.00012.000 s — card reads 2.000 s / 96000 frames, no leading or trailing silence (`CLAUDE.md` §"Precision invariants" — "Exact bounds")
- [ ] With an FX on the source track: item scope does NOT carry it, track scope does (`CLAUDE.md` §"Precision invariants" — "Capture FX scope")
- [ ] Track scope on a child track with FX, gain, and pan set on the parent and master — neither colors the capture (`CLAUDE.md` §"Precision invariants" — "Capture FX scope")
- [ ] Save, move the whole project folder elsewhere, reopen — every card still resolves and auditions (`CLAUDE.md` §"Precision invariants" — "Relative paths only")
## The decisive observation
- [ ] **Run first.** `docs/verify-track-scope-multitrack.md` §3 by hand, and count the files REAPER writes (`docs/TODO.md` §"The `&128` multi-track output shape is still DAW-unobserved", `docs/COMPLETED.md` §"Ψ-W3-T1", `docs/COMPLETED.md` §"None of the seven is DAW-verified")
- [ ] Two files confirms Ψ-W1-T1 and Ψ-W3-T1 at once; **one summed file invalidates both** — stop and report, the refusal is costing a capture 1.0.0 accepted (`docs/COMPLETED.md` §"None of the seven is DAW-verified")
- [ ] Then walk the rest of `docs/verify-track-scope-multitrack.md` (§1–§2, §4–§7) for the multi-track refusal itself (`docs/COMPLETED.md` §"Ψ-W3-T1")
## Capture range and bounds
- [ ] Over an item much longer than the selection: item scope × time selection, and item scope × razor — each lands exactly the window, not the whole item (`docs/COMPLETED.md` §"Ψ-W1-T1")
- [ ] Same source: track scope × time selection, and track scope × razor — same exact window (`docs/COMPLETED.md` §"Ψ-W1-T1")
- [ ] One razor-union case (two disjoint areas, one track) — lands the requested window, no `ReaSampler capture failed:` line (`docs/COMPLETED.md` §"Ψ-W1-T1")
- [ ] Capture an item whose extent already equals the window — still lands, unchanged (the byte-identity regression floor) (`docs/COMPLETED.md` §"Ψ-W1-T1")
- [ ] **The millisecond floor — SETTLED, nothing to re-run for `TailMode::None`.** The floor lives in the custom-time-bounds field (`RENDER_BOUNDSFLAG=0`), not in the render engine. Two live 48 kHz `TailMode::None` renders on `RENDER_BOUNDSFLAG=2` (time selection, handed over via `GetSet_LoopTimeRange`) came back exact — 97627 frames against 97627 — the second over a window whose START carried a sub-millisecond remainder, with no floored model of that window able to reproduce the count. Time selection is now the only bounds mode a capture can reach; the console verdict line and the `RENDER_STARTPOS`/`ENDPOS` read-back probe that answered this are gone. Full observation: `src/core/capture/render_settings.h`'s `kRenderBoundsTimeSelection`
- [ ] **Still open — Auto and Manual tail.** `checkRenderedBounds` judges `TailMode::None` only (Auto/Manual add frames by design), so the settled result covers those two by INFERENCE, not observation, and the inference rests on an unverified PREMISE too: that the (retired) floor applied to the bounds identically across all three tail modes, and that all three now hand the window over the same way. Neither is measured — both live short renders that settled the bounds mode were `TailMode::None`; no Auto or Manual capture has been observed at all. **On Auto/Manual, the ONLY automatic check left is the 0-byte gate (`checkRenderedFileNotEmpty`)** — there is no automatic bounds signal for those two modes at all until this bullet is closed by hand. What would establish it: repeat an off-grid-start capture at **Manual** over a source that is loud right to the window's end, and check the landed file's frames against window + `tailMs` — a floored edge shows up in that count. **Auto** cannot be checked by count (it trims trailing silence), so it needs the null test by ear/inversion against the source instead
- [ ] `[verify — DAW]` A tail is assumed to render PAST the window end — the SDK header (`:3048`) confirms only that `RENDER_TAILMS` is a length in ms, not that it extends past the end. If that assumption is wrong, a tail capture is silently SHORTER than its window with no detector at all. Report whether either tail capture comes up short against the source
- [ ] A refused render is kept for diagnosis at `<project folder>/reasampler_refused/` (the refusal line names the path; a failed move leaves it unindexed in the bank folder and says so). Delete the folder when done — nothing in the bank references it
- [ ] **If a capture is refused for a short render**, report the refusal line verbatim. A message naming `floored to the millisecond` means the floor is back on a mode measured escaping it; a shortfall of one or two frames with no such sentence may be the gate's own edge-convention tolerance rather than the render (`render_window.h`'s `renderHonoredBounds`)
## Names and channels
- [ ] Capture from a named track — the card reads `<Track> MM-DD HHMM`; capture again the same minute and the second carries an ordinal (`docs/COMPLETED.md` §"Ψ-W2-T1")
- [ ] Capture from an unnamed track, and from a multi-item selection — both readable, `+N` present on the multi (`docs/COMPLETED.md` §"Ψ-W2-T1")
- [ ] Load a named capture into ReaSampler 9000 — the same name shows there (`docs/COMPLETED.md` §"Ψ-W2-T1")
- [ ] The card label stays legible over its scrim at every card size (`docs/COMPLETED.md` §"Ψ-W2-T1")
- [ ] Capture a dead-center mono source — the `.wav` is roughly half the size of the equivalent stereo capture (`docs/COMPLETED.md` §"Ψ-W2-T2")
- [ ] Insert that collapsed file on a stereo track and null it against the source — confirms REAPER sums a 1-channel item at unity (`docs/COMPLETED.md` §"Ψ-W2-T2")
- [ ] Capture a true-stereo source — stays 2-channel, and both it and the collapsed file load into the instrument correctly (`docs/COMPLETED.md` §"Ψ-W2-T2")
## Mode switching
- [ ] Solo tracks in Arrange, switch to Design, solo different tracks, switch back — each mode restores its own solo set verbatim (`docs/COMPLETED.md` §"Ψ-W1-T2")
- [ ] Attempt a mode switch while the transport is playing, then while recording — both refuse, visibly (`docs/COMPLETED.md` §"Ψ-W1-T2")
- [ ] Click the footer mode segment, save, reopen the project — the mode persisted (`docs/COMPLETED.md` §"Ψ-W1-T2")
- [ ] `[verify — DAW]` Reproduce the strand: project with FX in both modes, switch to Design, save, close, reopen, toggle to Arrange. Toggle back and forth several more times — the arrangement's FX must NOT converge on permanently offline/hidden. A track the tool refuses to park is NAMED in the console, and the same refusal is not reprinted on a later reapply unless the refused set changed (`src/shell/view/view_fx_park.h`'s `decidePark` / `reportRefusedParks`)
- [ ] `[verify — DAW]` **ONE switch, ONE point.** In a project with several FX across several tracks, switch modes once and count the undo points REAPER shows (Ctrl-Z tooltip / undo history): expect exactly ONE, `ReaSampler: activate <mode> view` — never two, and never one per FX. Then press Ctrl-Z once: the flags unpark and EVERY FX comes back online, in that single step. Verify the EFFECT, not merely that one entry exists — a mask that failed to pick up `UNDO_STATE_FX` would still show one correct-looking entry while leaving every plugin offline, which reads as a pass and isn't. Then Ctrl-Y: the redo re-parks all of it, also in one step (`src/shell/view/CLAUDE.md` §Invariants — "ONE mode switch is ONE undo point")
- [ ] `[verify — DAW]` **Where the `view_state` lands on undo AND redo, and whether the redo strands a track.** `persistViewState` writes the ext state AFTER `applyMode`'s block closes, so the point never saw the new `view_state` — the undo direction is expected to come out right by position, the redo direction is the open one. Use a project with FX on the tracks that park. After the Ctrl-Z above, read the footer segment: it must show the mode the user came FROM, and a further switch must bank solos under that mode id. Then Ctrl-Y and read it again: if the tracks re-park while the footer still shows the pre-switch mode, the redo restored the stale ext state and model-vs-project is out of step. **Then switch modes ONCE MORE and read the console** — the hypothesised consequence is a `left unparked` refusal line naming those tracks, because the redo-restored model carries no snapshot for a chain that reads parked. A clean switch with no refusal line kills the hypothesis; the line appearing confirms a NEW refusal route and the persist position has to be reopened. Report which, and the footer state at each step. Do NOT fix by moving `persistViewState` inside the block — it can open a modal Save-As (`src/shell/view/CLAUDE.md` §Gotchas)
- [ ] `[verify — DAW]` **No point on open.** Open a project saved in Design mode with every inactive leaf already fully parked (flags AND FX), and check the undo history: the load-tick reapply writes nothing, so it must add NO undo point at all — the `("", 0)` discard form. This only holds when the saved state really was fully parked; a first open after tagging a new leaf, an FX added to a parked track, or a plugin hand-onlined since the last save all have real state to write and legitimately mint one correct point. An entry appearing on a project that WAS fully parked means the discard is not working — and since `mintManagedLanes`' no-op path rests on the same idiom, check that alongside it (`src/shell/view/view.h`'s `applyMintsUndoPoint`)
- [ ] `[verify — DAW]` **The hitch now sits on the switch.** On a project with heavy plugins (convolution, a loaded sampler) across several parked tracks, time the mode toggle: by design the action does not return until every plugin has unloaded/reloaded. Report roughly how long, and whether the UI recovers cleanly afterwards — the whole write phase runs under one `PreventUIRefresh(1)` hold (`src/shell/view/CLAUDE.md` §Invariants — the documented caveat)
- [ ] `[verify — DAW]` **Nested blocks around the FX writes.** Two directions, both undocumented in the SDK header. (a) `render_in_place` calls `applyMode` inside its OWN undo block, so its single `ReaSampler: render selected track to a new track` point should now absorb the reapply's FX moves — run that verb from Design mode over a track with FX and confirm ONE point, not two, and that Ctrl-Z reverses all of it. (b) The inverse: fire a mode-switch action WHILE a switch's plugin loads are in flight (a heavy chain widens the window) — `applyMode` is latched, so the expected outcome is that the second switch is DROPPED entirely and silently; the history must show one point, and the footer must still read the first switch's target. Re-firing it afterwards must work normally. (c) The same window, but let `OnTimer` -> `bankPanelRefresh` -> `mintManagedLanes` run into it: that path is NOT latched and opens a block of its own, so check the history for a split or misordered point (`src/shell/view/CLAUDE.md` §Gotchas)
- [ ] `[verify — DAW]` **The load reapply is never lost to the latch.** Open a project saved in Design mode with heavy plugins on parked tracks (so an apply is long) while another apply can overlap — e.g. trigger a project open from an action fired during a switch. The saved mode must still be applied: the load glue tests `modeApplyInProgress` before spending its one-shot signal and retries on the next timer tick, so a delayed-by-a-tick reapply is a pass and a never-applied one is a failure (`src/app/main.cpp`'s load glue, `src/shell/view/view.h`'s `modeApplyInProgress`)
- [ ] `[verify — DAW]` **A tab switch mid-apply cannot split the block.** `applyMode` pins the project once at entry and threads it through `Undo_BeginBlock2`/`Undo_EndBlock2`/`ValidatePtr2`. With a long switch in flight, switch project tabs (the pump premise makes this reachable) and confirm the undo point lands on the project the switch started in, with nothing written into the other tab (`src/shell/view/view.cpp`'s `applyMode`)
- [ ] `[verify — DAW]` **A→B→A costs two full cycles.** Toggle Arrange→Design→Arrange quickly on a project with heavy plugins: every plugin unloads and reloads twice, where the retired intent queue made a fast double-toggle free. Confirm the END STATE is still correct (every FX online, every driven flag back at its captured value) and report whether the doubled cost is tolerable in practice (`src/shell/view/CLAUDE.md` §Invariants — the A→B→A bullet)
- [ ] `[verify — DAW]` For a track the console names as left unparked, follow the message's recovery IN FULL: re-enable its TCP/mixer visibility, main send and FX enable, **and set every FX in its chain online** (FX enable is the chain bypass — it does not bring an individually offlined FX back). Then switch modes twice: it parks and restores normally, with no further console line. Do the flag half ONLY on a second such track and confirm it is still refused — the FX half of the trust test, and the reason the message spells the step out (unit-tested only as a decision, never against a live chain)
## Actions and drops
- [ ] Add the import action to a Media Explorer toolbar and fire it from there — it imports (`docs/COMPLETED.md` §"Ψ-W1-T3")
- [ ] Fire the existing Main-section import binding — still works (`docs/COMPLETED.md` §"Ψ-W1-T3")
- [ ] Unload/reload (restart REAPER) — no duplicate Media Explorer entry in the action list (`docs/COMPLETED.md` §"Ψ-W1-T3")
- [ ] Drag one card across the arrange, over an FX window, over the TCP/MCP and back — cue changes per surface, every transition reverses (`docs/COMPLETED.md` §"Ψ-W1-T4")
- [ ] Drag fast, and drag onto a narrow TCP — target class still resolves; no release anywhere in REAPER is a silent no-op (`docs/COMPLETED.md` §"Ψ-W1-T4")
- [ ] Drop a single card into the arrange — an item lands at the pointer's track and time (`docs/COMPLETED.md` §"Ψ-W1-T4")
- [ ] Drag-out to an external app twenty-plus times in a row — audio arrives every time; this is a soak, a single pass is not a gate (`docs/COMPLETED.md` §"Θ-W1-T2" — "Neither acceptance criterion has actually been met yet")
- [ ] Drop a capture onto an FX container — the instrument loads with that capture (`docs/COMPLETED.md` §"Θ-W1-T2" — "Neither acceptance criterion has actually been met yet")
## Bank packages
- [ ] **Run in full.** `docs/verify-package-transfer.md` — the whole cross-machine
export/import round trip: writes-one-file, the transfer itself, re-importing the
same file never overwrites, the round trip back to the source, the too-new /
truncated / mid-payload-corruption refusals (each an exact string), the
unsaved-project refusals, and drag-and-drop (`docs/COMPLETED.md` §"Ε-W3-T1")
- [ ] Force a degraded tracking ledger and confirm the import refuses **before the
file picker opens**: save a project with a bank, close REAPER, edit the saved
`.rpp`'s `owned_files` ext-state value inside its `<REASAMPLER ...>` block — corrupt
the JSON for the `Unreadable` case, or bump `"v":2` to `"v":3` for the
`FutureVersion` case — reopen the project, then run *ReaSampler: import bank
package (.rsbank)*. Read off: the console prints the ledger-refusal block and no
file dialog ever appears (`origin_ledger.h`'s `LedgerStatus` and `ledgerDegraded`,
`package_import_action.cpp`'s `ledgerPermits`)
- [ ] Export dialog: type a destination name with no extension, then again over a
name that already carries a different one (e.g. `mybank.bak`) — read off whether
`GetUserFileName` appended `.rsbank` itself or ReaSampler's own re-append produced
the double-extension result (`mybank.bak.rsbank`) the code expects
(`src/shell/package/CLAUDE.md` §"Gotchas" — "The re-append is suffix-blind")
- [ ] Both the export and the import file dialogs open in front of REAPER's main
window, not behind it — `GetUserFileName` takes no owner window
(`src/shell/package/CLAUDE.md` §"Gotchas" — "`GetUserFileName` also takes no owner window")
- [ ] With a ReaSampler 9000 instance's editor open on the destination project
(Browse view visible), import a `.rsbank` from the docked panel — the browser
reflects the new bank without closing or reopening the editor (the bank-generation
bump, `session.h`'s `bumpBankGeneration`, polled by the instrument at
`processor_reload.cpp`'s `pollBankSync`)
- [ ] Drag two or more `.rsbank` files onto the docked panel in one drop — each lands
as its OWN new bank, never merged into one, and if the tracking ledger is degraded
the refusal prints ONCE for the whole drop rather than once per file
(`panel_window.cpp`'s `handleDropFiles`)
- [ ] Kill REAPER (or the process) partway through an import so a partial bank file
is stranded under its real name in the bank folder, then re-run the same import
into the same project — read off what happens. Whether the import verb should
pre-clean that stale debris is an open question, not yet decided
(`src/shell/package/CLAUDE.md` §"Gotchas" — "A crash mid-export strands the `.rsbanktmp` sibling")
## The resample bake
- [ ] Bake a dialed sound — the banked file sounds like what the editor was playing (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Not demonstrated")
- [ ] Bake the result twice more — iteration composes, nothing is lost per pass (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Not demonstrated")
- [ ] Save and reopen after a bake — the instance still points at the baked capture (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Not demonstrated")
- [ ] Confirm no bake put an item in the arrange, and the superseded file is still on disk (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Not demonstrated")
- [ ] Bake from an instance in a background project tab — refuses rather than writing into the wrong bank (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Two behaviors worth recording")
- [ ] Load the VST with the extension not installed — the resample affordance reads unavailable, not silently lossy (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Two behaviors worth recording")
- [ ] After a bake: instance is in Trigger with start point reset, channel mode and preview velocity survived (`docs/COMPLETED.md` §"Ξ-W2-T1" — "Reset-scope classifications made at review")
- [ ] Gate mode + active sustain loop — "Bake Hold" appears within ~500 ms, its label fits its cell, its travel is duration-ordered (`docs/COMPLETED.md` §"Ξ-W3-T1")
## Render in place
- [ ] Fire *Render track in place* over a track with a range selected — solo the source
and the new sibling track, invert one track's polarity, and confirm silence. This is
Ρ's own trust anchor: the placement is the null test performed automatically
(`docs/product/render-in-place.md` §"DAW-verification obligations",
`docs/COMPLETED.md` §"Phase Ρ — Render in place")
- [ ] Render in place from three source positions in turn — a normal mid-folder track, a
track that is last in its folder, and a folder-parent track — each time confirm the new
sibling track lands at the same nesting level as the source and that the folder bus
feeds (or bypasses) it correctly. Then, to settle whether `TrackList_AdjustWindows(false)`
is actually needed: comment out that call in `render_in_place.cpp`'s
`RunRenderTrackInPlace` (it was added preemptively, answering a question the spec had
left open rather than one the code confirmed), rebuild, and repeat the folder-parent
case — if nesting still displays correctly with the call removed, it can be dropped in a
follow-up (`docs/product/render-in-place.md` §"DAW-verification obligations")
- [ ] Render in place from a dead-centre (channel-identical) source — confirm the placed
item is mono, and confirm it plays back at the same perceived level the stereo source
did before the render. This is root `CLAUDE.md`'s existing mono-summing
`[verify — DAW]`, promoted to load-bearing because Ρ is the first path that places a
collapsed render into the mix automatically (`docs/product/render-in-place.md`
§"DAW-verification obligations")
- [ ] Fire Render track in place once from Arrange and once from Design. From Arrange:
confirm the source track parks and the result track is visible and in the mix. From
Design: confirm the source stays on the bench, the result track is parked too, then
switch to Arrange and confirm the result track appears in the source's place. **In
both cases wait out at least one panel timer tick before checking membership** — that
is the check that catches a missing explicit-tag-wins filter or an untagged item,
either of which silently reverses the ruling that the result track is always an
Arrange member (`docs/product/render-in-place.md` §"Mode transitions — the source
parks, the result goes to Arrange")
- [ ] Render in place, then press Ctrl-Z once — confirm the new track and its item are
both gone, the source track's folder depth is restored, the rendered file itself is
still on disk, and the source track is still tagged Design (`docs/product/render-in-place.md`
§"DAW-verification obligations")
- [ ] Render in place from a named source, then run it again over the resulting (already
`Capture `-prefixed) track — confirm the name does not stack a second prefix, and
confirm the new sibling's colour matches the source's (the colour clone has no unit
coverage at all). Repeat once from an unnamed source and confirm the result reads
`Capture Track N` (`docs/product/render-in-place.md` §"DAW-verification obligations";
the name-composition logic itself — apart from the live colour clone and the real
`GetTrackName`/`P_NAME` round trip — is unit-tested in `tests/test_capture_name.cpp`)
- [ ] Save a project into a folder whose recording path is set away from the default
(Project Settings → Media → Path), then Render track in place — confirm the rendered
file lands in that configured recording path, not the project folder itself
(`render_in_place.cpp`'s `RunRenderTrackInPlace`, `GetProjectPathEx`)
- [ ] Render in place, save the project, and reopen it — confirm the result track (which
carries an explicit `kArrangeModeId` membership record, unlike the shipped
tag-selected-tracks action which never writes one) behaves identically, in every
mode-switch and visibility check, to an ordinary untagged Arrange track. The JSON
round-trip itself is unit-tested (`tests/test_view_mode_model.cpp`); this is the
live-view half that isn't (`docs/product/render-in-place.md` §"Mode transitions — the
source parks, the result goes to Arrange")
## Instrument migration
- [ ] Open a project saved before the zone retirement — the instance reopens on its first zone and sounds the same (`docs/COMPLETED.md` §"Θ-W1-T1")
- [ ] Such an instance with implicit channel mode + a stereo capture reopens **Stereo** — confirm that is acceptable by ear (`docs/COMPLETED.md` §"Θ-W1-T1")
## Waveform marker zero-crossing snap (Ω-W2-T5)
- [ ] `[verify — DAW]` Drag a Gate loop mark on a single-cycle capture — the felt radius the mark
may be pulled to reach a crossing genuinely reads as imperceptible, i.e. a displacement inside
the pointer's own grab neighbourhood is not one the eye catches (`src/core/instrument/ui/waveform_view.h`'s
`kZeroCrossingSnapPx` comment)
- [ ] `[verify — DAW]` Hold Ctrl, then drag a waveform marker (start/loop start/loop end) off a
zero crossing — confirm it lands exactly where dropped, with no snap, in a live editor window
(`editor_input_waveform.cpp`'s `dragWaveform`, `GetKeyState`-driven, no CI test target)
- [ ] `[verify — DAW]` Press and hold Ctrl BEFORE mouse-down on a mark that coincides with a
contour node or another mark's cap — confirm the mark is grabbed (not the node dragged, not a
hard/smooth toggle fired), matching the fix in `resolveWaveformClaim`
(`src/core/instrument/ui/spline_edit.cpp`)
## Look and feel
- [ ] Sign off by eye in a live editor window: knob arcs, needles, envelope splines, waveform outline (`docs/COMPLETED.md` §"Θ-W7-T1", `docs/COMPLETED.md` §"Θ-W6-T1" — "Antialiasing pass")
- [ ] Same pass for legibility: text sizes, arc weight, and whether the waveform stroke thickens the docked panel (`docs/COMPLETED.md` §"Θ-W6-T1", `docs/COMPLETED.md` §"Θ-W6-T1" — "Sizing")
- [ ] Piano strip at the 840 px default — keys tile uniformly, the 37 px end gutters read as acceptable (`docs/COMPLETED.md` §"Θ-W2-T3")
- [ ] Resize the editor across several widths — gutters stay symmetric, no key width jumps (`docs/COMPLETED.md` §"Θ-W2-T3")
- [ ] Set host/OS scaling to 150% then 200% — record how the strip and the AA strokes actually look (`docs/TODO.md` §"High-DPI host scaling is unverified (distinct from the antialiasing audit)", `docs/COMPLETED.md` §"Θ-W2-T3" — "Width uniformity is guaranteed in client pixels only")
## The VST3 parameter surface
- [ ] `[verify — DAW]` Whether REAPER renders `ParameterInfo::units` beside the string
`getParamStringByValue` returns, or shows the string alone. We ship the SDK's own
convention (digits in the string, unit carried separately); if REAPER shows no unit at
all, the fallback is a one-line change to the single formatter, touching neither the
frozen id table nor the editor (`docs/COMPLETED.md` §"Γ-W4-T1")
- [ ] Whether REAPER's own per-parameter MIDI learn covers what a shipped `IMidiMapping`
CC table would have — the decision to ship no default map rests on it; if learn does not
reach these parameters, a CC table is additive and frozen by nothing (`docs/COMPLETED.md`
§"Γ-W4-T1")
- [ ] The three migration round trips: a pre-parameter project opens with every parameter
reading the blob's value and sounds identical; a project saved by this build restores
fully in an older binary; a project with automation drawn, saved and reopened, replays
against the same plain values (`docs/COMPLETED.md` §"Γ-W4-T1")
- [ ] `[verify — DAW]` **Whether an offline render replays automation at all** — the
sharpest case for the audio-side drain, because the host drives `process()` and may
never touch the controller (`docs/COMPLETED.md` §"Γ-W4-T1")
- [ ] `[verify — DAW]` **Whether REAPER restores instance state through `setState`, not
`setComponentState`** — the entry-point half of the original bundled `[verify, FIRST]`
that an earlier pass closed only the delivery-channel half of. The evidence short of a
DAW is strong but is inference: `vstsinglecomponenteffect.h:41-47` collapses the two
names on a single-component plug-in, and the blob has round-tripped through payload
v1…v16 in real projects. Exercising it costs one save/reopen (`docs/COMPLETED.md`
§"Γ-W4-T1")
@@ -0,0 +1,813 @@
# Λ-W1 Track 1 — Linux build/toolchain audit (build-system lens)
Static analysis of the build surface only — the 23 `CMakeLists.txt` files, `cmake/`,
`src/resource.rc`/`src/resource.h` + the SWELL resgen pipeline, the three vendored submodules
as *build inputs*, the `ctest` harness, toolchain-level flags, and the packaging story in
`docs/product/versioning-and-release.md`. 2026-08-02, branch `pl-w1-t1-build-toolchain-audit`
(cut from `dev` at 6e937b9).
**Source portability is explicitly NOT audited here** — no Win32/GDI/LICE API usage, path
handling, threading, drag/drop, dialog code, fonts, or instrument runtime code. A parallel
track (T2) owns that; what I noticed in passing is listed under "Referred to T2" at the end
and nowhere else.
**Verification posture.** I am on Windows and cannot build or run anything on Linux. Every
claim below is grounded in a file I opened in this worktree — the tree's own CMake, or a
vendored header/source under `vendor/` — not asserted from memory of similar SDKs. Where a
claim depends on runtime behaviour I cannot observe (does REAPER's Linux build call
`SWELL_dllMain`? does GCC accept this TU?), it is marked `[verify — Linux]` with the exact
check, and it is **not** stated as fact. A subsequent citation pass caught several
line-number and attribution errors in this draft (corrected in place, disclosed at the point
each occurs) — grounded-in-a-file is a floor, not a guarantee against a mis-copied line range.
To get the vendored citations I ran `git submodule update --init` for all three submodules
inside this worktree; nothing in the tracked tree was modified.
Severity vocabulary, per the dispatch: **Blocker** = the Linux build cannot produce a loadable
artifact; **Major** = it builds but is degraded or unshippable; **Minor** = ergonomics,
warnings, CI polish. Effort bands are S (< half a day), M (13 days), L (a week+), and each
names the reason for the band rather than asserting a number.
---
## 1. Baseline — what the build does today, per platform
**Two loadable modules, 84 pure libraries declared under `src/core/`, 91 CTest targets,
three vendored submodules.** (84 = the `reasampler_pure_library` + bare `add_library` count,
grep-verified library-by-library across the 18 `src/core/**` CMake files that declare any —
`src/core/CMakeLists.txt` and `src/core/instrument/CMakeLists.txt` declare none, only
`add_subdirectory` calls (plus one test in the latter); there are 20 CMake files under
`src/core/**` total, matching the 19 figure in §1d below, which counts *test* declarations
across the whole tree, not `src/core/**` alone. 46 of the 84 are on the extension's link
line.)
- Root `CMakeLists.txt` is 95 lines and declares **no targets at all**: it owns the version
string (`:24`), the channel fork (`:4054`), the `configure_file` for
`version_generated.h` (`:5861`), the four vendor path variables (`:6568`), the
four-TU `LICE_SRC` list (`:7883`), `enable_testing()` (`:90`), and three
`add_subdirectory` calls (`:9294`).
- Language/toolchain settings are exactly three lines: `CMAKE_CXX_STANDARD 17`,
`CMAKE_CXX_STANDARD_REQUIRED ON`, `CMAKE_POSITION_INDEPENDENT_CODE ON`
(`CMakeLists.txt:2830`). There is **no** `CMAKE_BUILD_TYPE`, no `CMAKE_CXX_FLAGS`, no
`CMAKE_CXX_EXTENSIONS`, no IPO/LTO setting, and no `target_compile_options` anywhere in
the tree — I grepped all 23 CMake files for `compile_options`, `find_package`,
`pkg_check`, `link_directories`, `target_link_options`, and `install(` and got zero hits
outside the two files named below.
- **Platform conditionals exist in exactly two files.** Grepping all 23 `CMakeLists.txt`
for `WIN32|APPLE|UNIX|LINUX|MSVC|GNU|Clang|CMAKE_SYSTEM` returns hits only in
`src/app/CMakeLists.txt` (`:71` `if(WIN32)`, `:76` `elseif(APPLE)`, `:88` `else()`) and
`src/shell/instrument/CMakeLists.txt` (`:9` `if(WIN32 AND EXISTS ...)`). Every other
CMake file is platform-neutral by construction: they call the two helpers in
`cmake/reasampler_targets.cmake` (`reasampler_pure_library` at `:815`,
`reasampler_test` at `:1924`) and nothing else.
### 1a. The REAPER extension (`reaper_reasampler`)
Declared as a `MODULE` library over 39 listed TUs (38 shell TUs + `app/main.cpp` itself)
plus `${LICE_SRC}` (`src/app/CMakeLists.txt:851`), linking 46 pure static libraries (`:52`) with
`${SDK_INC} ${WDL_INC}` on the include path (`:56`). Output naming is
`PREFIX ""` + channel-derived `OUTPUT_NAME`, pinned to the top of the build tree by
`LIBRARY_OUTPUT_DIRECTORY`/`ARCHIVE_OUTPUT_DIRECTORY` (`:6569`).
The three-way platform block (`:7198`) is:
| Branch | State | What it does |
|---|---|---|
| `if(WIN32)` `:7174` | **Live and shipped** | adds `src/resource.rc` for the RC compiler |
| `elseif(APPLE)` `:7686` | **Partly aspirational** | adds `swell-modstub.mm`, defines `SWELL_PROVIDED_BY_APP`, links `-framework AppKit`, forces `.dylib`. The resgen `target_sources` line at `:86` is **commented out**. |
| `else()` (Linux) `:8897` | **Partly aspirational** | adds `swell-modstub-generic.cpp`, defines `SWELL_PROVIDED_BY_APP`, forces `.so`. The resgen `target_sources` line at `:97` is **commented out**. |
So on Linux the build system today produces `reaper_reasampler.so` with the SWELL modstub
compiled in and **no dialog resource of any kind**. `README.md:6768` states this is
"expected, not a bug" — the tree is honest about it.
**Open question, macOS-only, unresolved by this doc.** The APPLE branch adds
`${SWELL}/swell-modstub.mm` (`:79`), an Objective-C++ TU, but `CMakeLists.txt:26` is
`project(reaper_reasampler VERSION 1.4.0 LANGUAGES CXX)` — OBJCXX is never enabled anywhere
in the tree. Whether CMake resolves a `.mm` source against a plain CXX-only project (some
Apple-toolchain configurations infer Objective-C++ from the extension regardless; others do
not) is unverified from this tree and untestable without a macOS box. `[verify — macOS]`.
Three build-input facts I verified in `vendor/` and that hold in the extension's favour:
- `vendor/WDL/WDL/swell/swell-modstub-generic.cpp` is entirely inside
`#ifdef SWELL_PROVIDED_BY_APP` (`:21`, closed at `:150`). Since
`SWELL_LOAD_SWELL_DYLIB` is not defined anywhere in this build, the `#else` branch at
`:133` applies: the file's whole contribution is the three
`SWELL_curmodule_*resource_head` globals (`:3133`), the API function-pointer table
built from `swell.h` (`:3749`), and the `SWELL_dllMain` export (`:135`) that resolves
every SWELL symbol from a host-supplied `GetFunc`. That is the correct stub for a
REAPER extension, and the comment at `src/app/CMakeLists.txt:90` ("With
SWELL_PROVIDED_BY_APP you can drop pkg-config / -lX11 entirely") is **correct**: no SWELL
implementation TU, no X11, no GDK is compiled or linked into the extension.
- The four-TU LICE slice is self-contained on Linux. `lice.cpp` reaches SWELL only through
`SWELL_DeleteGfxContext` (`:153`, `:218`), `SWELL_GetCtxFrameBuffer` (`:182`, `:226`) and
`SWELL_CreateMemContext` (`:224`); `lice_textnew.cpp` reaches it through
`SWELL_PushClipRegion`/`SWELL_SetClipRegion` (`:10271028`) and `SWELL_PopClipRegion`
(`:1048`). All six are entries in SWELL's API table
(`vendor/WDL/WDL/swell/swell-functions.h:857`, `:863`, `:877`, `:885887`), so the
modstub resolves them from the host. No fifth LICE TU is implied: the `_LICE_RGB2HSV_invtab`
table lives inside `lice.cpp` itself (`:3040`), and the one non-Win32-only helper
`utf8makechar` is a file-static defined at `lice_textnew.cpp:26` and used at `:241242`.
This is a link-success inference, not a from-first-principles proof — the actual proof is
V1, a successful build. One loose end: SWELL's own `Makefile:106107` lists
`lice_colorspace.o` among the LICE objects *its* build needs — a fifth TU we don't compile.
It stays unreconciled but harmless: `lice_colorspace.cpp` defines the real `LICE_RGB2HSV`
function (declared `lice.h:577`, distinct from the `_invtab` table above), and grepping our
four LICE_SRC TUs and all of `src/` for a call to it returns nothing — SWELL needs the TU
for its own generic-GDK backend, which our four-TU slice never invokes into.
- `CMAKE_POSITION_INDEPENDENT_CODE ON` (`CMakeLists.txt:30`) is already set. This is the
single most commonly missed setting for a `MODULE` target fed by `STATIC` libraries on
Linux, and it is correct today.
### 1b. The VST3 instrument (`reasampler_vst`)
Hard-gated to Windows: `if(WIN32 AND EXISTS "${VST3_SDK}/public.sdk/source/main/pluginfactory.cpp")`
(`src/shell/instrument/CMakeLists.txt:9`). The gate is a conjunction — even with the
`vendor/vst3sdk` slice fully initialised, a Linux configure silently omits the target.
`README.md:3335` states this explicitly. Two module-level `CLAUDE.md` files record the
underlying product decision (D5) as *settled*, with "a mac/Linux build" named as a
non-goal: `src/core/instrument/CLAUDE.md` (Non-goals/guardrails) and
`src/shell/instrument/CLAUDE.md` (same). `src/shell/panel/CLAUDE.md` carries a third
instance ("Windows-only (D5) — font/GDI/HFONT choices assume Windows").
Inside the gate: a 20-source `vst3_sdk` static library (`:1638`, grep-counted; lines 28/29/37
are comments) pinned to SDK tag
`v3.7.9_build_61` (confirmed by `git describe --tags` in `vendor/vst3sdk`), and the
`reasampler_vst` MODULE (`:4481`) which additionally compiles `dllmain.cpp` and
`moduleinit.cpp` directly (`:7879`, with the linker-stripping rationale at `:7577`) plus
`${LICE_SRC}` (`:80`). Output is a single **file** named `<name>.vst3` (`:106111`).
### 1c. Resources
`src/resource.rc` declares exactly one dialog — `IDD_BANK_PANEL`, a bare `WS_CHILD`
`DIALOG` with an empty `BEGIN`/`END` body and no controls (`:1822`). `src/resource.h`
defines the single id `IDD_BANK_PANEL 1000` (`:8`). It is consumed by
`CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_BANK_PANEL), …)` at
`src/shell/panel/panel_window.cpp:135`.
### 1d. Test harness
91 test declarations across 19 `CMakeLists.txt` files (grep count), matching 91 files in
`tests/`. 90 go through `reasampler_test` (`cmake/reasampler_targets.cmake:1924`, which is
`add_executable` + `target_link_libraries` + `add_test`); one is longhand —
`app_version_padding_tests` (`src/core/version/CMakeLists.txt:3742`), which recompiles
`app_version.cpp` against a second `configure_file` output so the include-dir substitution
works. Neither shape carries anything platform-specific.
Only two test files mention a platform at all: `tests/test_capture_paths.cpp` (five
`#ifdef _WIN32` blocks at `:19`, `:41`, `:87`, `:152`, `:205`, each with a POSIX `#else`
branch already written — e.g. `:158168` asserts `resolveBankFile("/home/d/proj", …)`), and
`tests/test_pitch_shift.cpp:3`, where the string is inside a comment explaining why the
target links nothing that would drag `<windows.h>` in. No test includes `reaper_plugin.h`,
`windows.h`, or any SWELL header. **The test harness is the healthiest part of this
surface**; see §3 for the one generator-shape caveat.
### 1e. Packaging / release, as already committed
`docs/product/versioning-and-release.md` already commits to Linux as a first-class target:
- `:361363` — "**Artifact per platform.** The binary is `reaper_*.dll|.dylib|.so`; the
macOS/Linux builds need the SWELL resgen step (CLAUDE.md §SWELL dialog resources) baked
into the pipeline. Three platform artifacts per channel per release."
- `:307310` — two named artifacts (stable + beta) per platform, "three platform artifacts
each", explicitly handed off to dev-ops.
- `:364366` — "Install is copy-in + restart… there is no server-side rollout."
What that document does **not** contain: any mention of code signing, macOS notarization, a
CI runner, or a Linux install path. I grepped it for `sign|notariz|CI|platform|linux` — one
hit is not cited above (`:393`, "artifacts (stable + beta) per platform", the same dev-ops
handoff as `:307310`); the rest are the lines above. The substantive conclusion — no
signing/notarization/CI/Linux-install-path mention anywhere — holds regardless. There is no
CI configuration anywhere in the repo (`ls -a` on
the root shows `.git`, `.gitignore`, `.gitmodules`, `CLAUDE.md`, `CMakeLists.txt`, `LICENSE`,
`README.md`, `cmake`, `docs`, `src`, `tests`, `vendor` — no `.github`, no `.gitlab-ci.yml`),
and no `install()` rule in any of the 23 CMake files. So "the pipeline" is entirely notional
today, on every platform.
---
## 2. Findings
### Λ-01 — the Linux/macOS dialog-resource path is broken in three independent ways, and the fix may not need resgen at all
**Severity: Major. Effort: S (mechanical) to M (if the resgen route is taken and automated).**
**Citations.** `src/app/CMakeLists.txt:9497` (the Linux comment block) and `:8386` (the
identical macOS one); `vendor/WDL/WDL/swell/swell_resgen.php:313314`;
`vendor/WDL/WDL/swell/swell-dlggen.h:22`; `vendor/WDL/WDL/swell/sample_project/myapp.cpp:192193`;
`vendor/WDL/WDL/swell/swell-dlggen.h:214218`; `vendor/WDL/WDL/swell/swell-modstub-generic.cpp:3133`;
`vendor/WDL/WDL/swell/swell-functions.h:612619`; `src/resource.rc:1822`;
`src/shell/panel/panel_window.cpp:135`.
**What breaks.** Three defects stack, and each alone would sink the step:
1. **The named script does not exist.** Both comment blocks say
`php ${WDL_INC}/swell/mac_resgen.php src/resource.rc` (`:85` and `:96`). Listing
`vendor/WDL/WDL/swell/` shows `swell_resgen.php`, `swell_resgen.pl`, and
`swell_resgen.sh` — there is no `mac_resgen.php`. `CLAUDE.md` and `README.md:120` both
name the correct script; only the CMake comments are wrong, which is exactly the file an
implementer will be reading when they do the work.
2. **The named output file is not what the generator writes.** Both commented
`target_sources` lines (`:86`, `:97`) reference
`${REASAMPLER_SRC_DIR}/resource.rc_mac_dlg.h`. `swell_resgen.php:313314` composes its
output names as `$srcfn . "_mac_menu"` and `$srcfn . "_mac_dlg"` — so the actual outputs
are `src/resource.rc_mac_dlg` and `src/resource.rc_mac_menu`, with **no** `.h` suffix.
3. **Even the correct filename cannot be a `target_sources` entry.** `swell-dlggen.h:22`
states the contract outright: "Use swell_resgen.pl or swell_resgen.php on the .rc file,
which will produce .rc_mac_dlg, **include that**." The generated body is a run of
`SWELL_DEFINE_DIALOG_RESOURCE_BEGIN(...)` macro invocations
(`swell_resgen.php:117129`) that only expand after `swell-dlggen.h` has been included —
`swell-dlggen.h:214218` shows the macro emitting a static `SWELL_DialogRegHelper` that
registers into `SWELL_curmodule_dialogresource_head`. The canonical consumption pattern
is the SDK's own sample: `sample_project/myapp.cpp:192193` does
`#include "../WDL/swell/swell-dlggen.h"` then `#include "res.rc_mac_dlg"`. A CMake
`target_sources` entry for an extensionless file would not even get a language assigned.
**The runtime consequence, and why this is Major rather than Blocker.** The `.so` still
builds and still loads: the extension's whole action family, capture pipeline, and persist
layer are untouched. What fails is the dock panel. `swell-functions.h:615` defines
`CreateDialog(hinst,resid,par,dlgproc)` as
`SWELL_CreateDialog(SWELL_curmodule_dialogresource_head,(resid),par,dlgproc,0)`.
`swell-modstub-generic.cpp:32` *defines* that head but nothing ever populates it, because
the resgen'd registration TU does not exist — so it stays null and
`panel_window.cpp:135`'s `CreateDialogParam` gets a null resource list. The panel is the
product's primary surface, so a Linux build without it is not shippable; it is not a
Blocker only because the binary loads and the actions work.
**The route worth considering first.** `swell-functions.h:606608` documents an escape
hatch: *"If you are using CreateDialog() and creating a child window, you can use a resource
ID of 0, which creates an opaque child window. Instead of passing a DLGPROC, you should pass
a (WNDPROC) routine that returns LRESULT (and cast it to DLGPROC)."* The header comment is
not just documentation — the implementation confirms both halves of it:
`swell-dlg-generic.cpp:291292` is `SWELL_DialogResourceIndex *p=resById(reshead,resid); if
(!p&&resid) return 0;`, and `resById` (`:3443`) walks from a (here, null) `reshead` and
returns 0 on a miss. That confirms the graceful-failure claim behind "Major rather than
Blocker" above (a null `reshead` plus a non-zero `resid` returns 0, not a crash — matching
`panel_window.cpp:137`'s `if (!g_panel.hwnd) return;`), **and** that `resid == 0` skips the
lookup entirely (`&&resid` short-circuits), which is the escape hatch this paragraph is about.
`src/resource.rc:1822`
shows `IDD_BANK_PANEL` is precisely that: a `WS_CHILD` dialog with an empty body and zero
controls, whose comment at `:810` says "the bank_panel shell owns every pixel and draws the
sample grid with LICE in `WM_PAINT`". If the panel is created with resource id 0 on
non-Windows, **the entire resgen pipeline — the PHP dependency (`README.md:54`), the
generated-file-in-source-tree problem, and the per-platform regeneration story — disappears
from the Linux and macOS builds.** The cost is a source change in `panel_window.cpp` and the
DLGPROC→WNDPROC return-type contract; that half is T2's call, not mine, and I am naming the
option rather than choosing it. This is a shared macOS/Linux fix either way.
**If the resgen route is taken instead**, the build work is: a `find_program(PHP …)`, an
`add_custom_command` generating into `${CMAKE_CURRENT_BINARY_DIR}` (not the source tree —
`.gitignore` has no pattern matching `resource.rc_mac_dlg`, so today's manual step would
leave an untracked generated file sitting in `src/`), a new one-line shim TU that includes
`swell-dlggen.h` then the generated file, and that shim added to `target_sources`. That is
the M-effort half of the band.
---
### Λ-02 — `--config Release` is a silent no-op on Linux, so the documented ship command produces an unoptimized binary
**Severity: Major. Effort: S — one `if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)` block plus a doc correction.**
**Citations.** `CMakeLists.txt:2830` (the complete list of language settings — I read the
whole 95-line file and there is no `CMAKE_BUILD_TYPE` anywhere); `README.md:106109`;
`CLAUDE.md` §"Build and test" and §"Install / reload".
**What breaks.** Both docs prescribe `cmake --build build --config Release` as the
optimize-and-ship incantation, and `README.md:130131` tells the user to copy from
`build/Release/`. `--config` is a multi-config-generator flag; on Ninja or Unix Makefiles it
is accepted and ignored. Because no `CMAKE_BUILD_TYPE` default is set, the resulting build
passes **no `-O` flag at all** to GCC/Clang — not `-O0` explicitly, just the compiler's
unoptimized default. The failure is silent in both directions: the command succeeds, and the
artifact lands at `build/reaper_reasampler.so` — a path the docs never state for a
single-config generator (a gap, not an error; see Λ-08).
This matters more here than the usual "forgot to set the build type" — but only for `peaks`.
`CLAUDE.md`'s §"Build and test" (not §"Performance guardrails") states, at `CLAUDE.md:54`,
that the header-inline hot paths "presume an **optimizing** build", with no LTO configured to
recover it if they don't. `peaks`' `computeEnvelope`/`lastFrameAboveThreshold` is one of
those paths and IS linked into the extension (`src/app/CMakeLists.txt:56`), so the finding
holds for Fork A as stated. It does **not** extend to `Voice::advanceFrame` or the three
`envelopes.h` evaluators (named at `src/core/instrument/CLAUDE.md:378`, not in root
`CLAUDE.md`) — those belong to `sampler_core`, which `src/app/CMakeLists.txt:5759` states is
deliberately NOT linked into the extension and which only enters a build at all inside the
Windows-gated `reasampler_vst` target (§1b). On Fork A that code never compiles into
`reaper_reasampler` in the first place; the unoptimized-build risk to it is a Fork B concern,
not this extension-only one. A Linux user following the README's `--config Release` would
ship an extension binary whose `peaks` hot path did not inline.
**Done when:** `cmake --build build` on Linux (Ninja/Make, no `--config`) produces a build
whose compile commands (`compile_commands.json` or verbose build log) show an explicit `-O`
flag, and the README/CLAUDE.md ship instruction names the single-config-generator path.
**Sequencing note.** This is not strictly Linux-specific — Ninja on Windows has the same
shape — but it becomes load-bearing the moment Linux is a shipped platform, because Makefiles
and Ninja are the default there.
---
### Λ-03 — no symbol-visibility control, and two modules in one process both export a full copy of LICE
**Severity: Major. Effort: S — one `CXX_VISIBILITY_PRESET hidden` + `VISIBILITY_INLINES_HIDDEN` pair, plus a `[verify — Linux]` load test.**
**Citations.** `CMakeLists.txt:7883` (`LICE_SRC`); `src/app/CMakeLists.txt:35` and
`src/shell/instrument/CMakeLists.txt:80` (the same four LICE TUs compiled into *both*
modules — the rationale for the duplication is at `CMakeLists.txt:7577`);
`vendor/reaper-sdk/sdk/reaper_plugin.h:52`; `src/app/main.cpp:251`;
`vendor/vst3sdk/pluginterfaces/base/fplatform.h:164`;
`vendor/WDL/WDL/swell/Makefile:20`.
**What breaks.** Nothing in the build sets a visibility preset, so GCC/Clang default to
`-fvisibility=default` and every non-static symbol in both modules — all of LICE, all the
WDL helpers, every pure library's exported functions, and the whole C++ standard-library
instantiation set — lands in the module's dynamic symbol table. On Windows this is a
non-issue: each DLL has its own symbol table and per-module resolution. `[verify — Linux]`
on ELF, symbols from `dlopen`'d objects CAN participate in global interposition — but whether
they actually do here depends on REAPER's own `dlopen` flags (`RTLD_GLOBAL` vs `RTLD_LOCAL`)
and whether REAPER's executable is linked `--export-dynamic`, neither of which this tree can
answer. The scenario this doc originally named — a hypothetical `reasampler_9000.so` — does
not exist on Fork A: per Λ-10 and `src/shell/instrument/CMakeLists.txt:9`, the VST3 target is
gated `WIN32 AND EXISTS ...` and is never built on Linux unless D1 selects Fork B. The
Fork-A-real risk is different: any **second REAPER extension** loaded in the same REAPER
process (a third-party `.so` in `UserPlugins/`) that links its own copy of LICE/WDL and also
defaults to `-fvisibility=default` is a candidate to interpose with `reaper_reasampler.so`'s
`LICE_FillRect` and the rest of the exported LICE/WDL symbol set. That is a class of bug that
presents as "one extension's LICE draws with another extension's LICE build" and is invisible
on Windows, where each DLL keeps its own symbol table.
**Why hiding is safe here.** The two symbols that genuinely must be exported already say so
explicitly: `reaper_plugin.h:52` defines
`REAPER_PLUGIN_DLL_EXPORT __attribute__((visibility("default")))` on non-Windows, and
`main.cpp:251` uses it (`extern "C" REAPER_PLUGIN_DLL_EXPORT int REAPER_PLUGIN_ENTRYPOINT(...)`).
On the VST3 side, `fplatform.h:164` defines `SMTG_EXPORT_SYMBOL` the same way. SWELL's own
build already uses `-fvisibility=hidden` (`Makefile:20`), which is the precedent. The one
thing to confirm on a Linux box is that `swell-modstub-generic.cpp:135`'s `SWELL_dllMain`
survives — it carries its own `__attribute__ ((visibility ("default")))` at that line, so it
should, but the modstub is compiled by *our* build, not SWELL's.
*Shared macOS/Linux — the visibility default and the LICE-TU duplication (`CMakeLists.txt:7577`)
apply the same way under the APPLE branch's Mach-O two-level namespace, though the concrete
Fork-A-real interposition mechanism above is ELF-specific; macOS's own dynamic-linker symbol
resolution is a separate `[verify]` this doc does not attempt.*
---
### Λ-04 — nothing links a thread library, and `<pthread.h>` is in the extension's include graph
**Severity: Major (VST3 target) / Minor (extension). Effort: S — `find_package(Threads)` + `Threads::Threads`.**
**Citations.** `src/shell/panel/panel_state.h:2024`;
`vendor/vst3sdk/base/thread/source/flock.cpp:71133`;
`src/shell/instrument/CMakeLists.txt:1539`; `vendor/WDL/WDL/swell/Makefile:90`.
**What breaks.** No CMake file in the tree calls `find_package(Threads)` or links
`Threads::Threads`/`-lpthread`/`-ldl` (grep-verified across all 23). Two separate exposures:
- **Extension.** `panel_state.h:23` includes `<pthread.h>` on non-Win32 — and it is not the
only entry point: `vendor/reaper-sdk/sdk/reaper_plugin.h:50` includes `<pthread.h>`
unconditionally in its non-Windows branch, so it is in **every** shell TU's include graph
(every `.cpp` that includes `reaper_plugin.h`/`reaper_plugin_functions.h`), not just the
one panel file. This strengthens rather than changes the finding: I still did not find a
pthread *call* in `src/shell/`'s own code, so this may be an include-only dependency that
needs no link flag on a modern glibc (where the pthread symbols are in libc proper). Stays
Minor, and `[verify — Linux]`.
- **VST3 target.** `flock.cpp` is unambiguous: on non-Windows it calls
`pthread_mutexattr_init`/`_settype`/`_destroy` (`:7176`), `pthread_mutex_init` (`:74`),
`pthread_mutex_destroy` (`:89`), `_lock` (`:105`), `_unlock` (`:121`) and `_trylock`
(`:133`). It is unconditionally in the `vst3_sdk` source list
(`src/shell/instrument/CMakeLists.txt:27`). Any Linux VST3 target must link a thread
library. SWELL's own Makefile uses `-lpthread -ldl` (`:90`) for the same reason.
Adding `find_package(Threads REQUIRED)` + `target_link_libraries(... Threads::Threads)` is
correct on all three platforms and costs nothing on Windows.
**Done when:** the extension links with `Threads::Threads` removed (proving the include-only
half needs no flag, or naming the symbol that forces it — see V5), and, if Fork B is taken,
`reasampler_vst` links clean with `Threads::Threads` present.
*Shared macOS/Linux — `reaper_plugin.h:50`'s non-Windows `<pthread.h>` include and
`flock.cpp`'s non-Windows pthread calls apply identically to the APPLE branch.*
---
### Λ-05 — `reaper_plugin.h`'s SWELL include resolves only by coincidence of the `-I` line
**Severity: Minor. Effort: S — a comment, or an `INTERFACE` target that carries both include dirs as one unit.**
**Citations.** `vendor/reaper-sdk/sdk/reaper_plugin.h:4254`; `CMakeLists.txt:6566`;
`src/app/CMakeLists.txt:56`; `src/shell/instrument/CMakeLists.txt:97`.
**What breaks — and, today, does not.** On non-Windows, `reaper_plugin.h:49` does
`#include "../WDL/swell/swell.h"`. Relative to the including file's own directory
(`vendor/reaper-sdk/sdk/`) that resolves to `vendor/reaper-sdk/WDL/swell/swell.h`, which does
not exist — listing `vendor/reaper-sdk/` shows only `README`, `reaper-plugins`, and `sdk`.
The include is nevertheless satisfiable, because the quoted-include fallback searches the
`-I` path, and `WDL_INC` is `${CMAKE_CURRENT_SOURCE_DIR}/vendor/WDL/WDL` (`CMakeLists.txt:66`) —
so `WDL_INC` + `../WDL/swell/swell.h` normalizes to `vendor/WDL/WDL/swell/swell.h`, which
exists. Both module targets pass `${WDL_INC}` (`src/app:56`, `src/shell/instrument:97`), so it
holds today.
The hazard is that this is a load-bearing coincidence with no comment anywhere, and it is
**invisible on Windows** — `reaper_plugin.h:43` takes `<windows.h>` instead, so dropping
`${WDL_INC}` from any target that includes `reaper_plugin.h` would pass CI on Windows and
fail only on Linux/macOS. Worth pinning before more targets are added.
---
### Λ-06 — the build has no platform partition of its source list, so every T2 finding lands here as a CMake change
**Severity: Minor (structural). Effort: S per TU once T2 says which ones need it.**
**Citations.** `src/app/CMakeLists.txt:851` and `:7198`;
`src/shell/actions/drag_out_win.cpp:8`, `:249`, `:282`.
**Mechanism.** All 38 shell TUs (plus `app/main.cpp`, 39 listed TUs total) are listed unconditionally (`:851`); the platform block at
`:7198` only *adds* sources, never removes or substitutes any. Every TU therefore enters a
Linux compile, and the only thing standing between the build and a compile error is each
file's own `#ifdef` discipline. Today that discipline is uneven in a way worth recording:
- `drag_out_win.cpp` is the model — `#ifdef _WIN32` at `:8` with a real
`// ---- macOS / Linux (SWELL)` branch at `:249` and `#endif` at `:282`.
- `arrange_drop_win.cpp` and `instrument_drop_win.cpp` contain **zero** occurrences of
`_WIN32` (grep count 0 each) and include no `<windows.h>` — they are `_win`-suffixed for
the surface they serve, not for a platform dependency, and appear portable by inspection.
This is not itself a defect; it is the reason the ordering sketch in §5 puts "read T2's
output, then partition the source list" as a distinct step rather than folding it into the
resgen work.
---
### Λ-07 — `std::filesystem` in a pure library, with no stated minimum compiler
**Severity: Minor. Effort: S — a `cmake_minimum_required`-adjacent compiler check or a documented floor.**
**Citations.** `src/core/capture/capture_paths.cpp:5` (`#include <filesystem>`) and `:95`
(`std::filesystem::path(rppPath).parent_path().string()`); `README.md:5054`.
**What breaks.** `capture_paths` is a *pure* library with its own CTest target
(`src/core/capture/CMakeLists.txt:12`), so this is on the test-harness path as well as the
extension's. GCC 8 requires an explicit `-lstdc++fs` for `std::filesystem`; GCC ≥ 9 and
libstdc++ ≥ 9 do not. `README.md:51` states only "A C++17 compiler" as the prerequisite, and
`cmake_minimum_required(VERSION 3.19)` (`CMakeLists.txt:1`) says nothing about the compiler.
On any current distro toolchain this is a non-issue; it becomes one on an older CI image.
Twelve other files in `src/shell/` also use `<filesystem>` (grep-verified), but one —
`src/shell/instrument/instrument_bake.cpp` — is in the `reasampler_vst` target, not the
extension: eleven in `reaper_reasampler`, sharing the fix below; the twelfth shares it only
if/when Fork B builds that target on Linux.
**Done when:** `capture_paths_tests` links on the oldest toolchain the phase targets without
`-lstdc++fs` added explicitly, or that flag is added and documented as the floor.
*Shared macOS/Linux — `capture_paths` and the eleven extension-side `<filesystem>` users
compile identically under the APPLE branch; whether Apple's libc++ needs the same kind of
minimum-toolchain floor as libstdc++ does is a separate `[verify]` this doc has not checked,
but the coverage-hole shape (undocumented compiler floor) is identical either way.*
---
### Λ-08 — the install instruction is silent about single-config generators, and no path is documented for Linux at all
**Severity: Minor. Effort: S — a doc fix, or an `install()` rule if packaging is ever automated.**
**Citations.** `src/app/CMakeLists.txt:68` (`LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}"`);
`README.md:130131`; `CLAUDE.md` §"Install / reload";
`docs/product/versioning-and-release.md:364366`.
**What breaks — a gap, not an error.** `README.md:130131` and `CLAUDE.md` §"Install /
reload" both already carry the multi-config qualifier verbatim ("`build/Release/` on a
multi-config generator — not the default `Debug/` output") — so the instruction is not
wrong, it is simply silent about the other case. On a multi-config generator CMake appends
the config directory, giving the documented `build/Release/`. On Ninja/Make the module lands
directly at `build/reaper_reasampler.so`, and neither doc names that path. Compounding it,
there is no `install()` rule anywhere in the 23 CMake files, and no target directory is
documented for Linux at all — `CLAUDE.md` and `README.md:132` say "REAPER's `UserPlugins/`
folder (Options → Show REAPER resource path)", which is a correct user-facing instruction but
not a path a pipeline can use. I could not confirm REAPER's Linux resource-path root from the
SDK: grepping `vendor/reaper-sdk/sdk/` for `UserPlugins` and `reaper_*.so` returns nothing —
the `reaper_*.dll|dylib|so` filename convention stated in `CLAUDE.md` is not documented in the
vendored headers. `[verify — Linux]`.
---
### Λ-09 — no warning flags anywhere, so the first GCC/Clang build surfaces a diagnostic set nobody has ever seen
**Severity: Minor. Effort: S to add flags; **unknowable** to fix what they reveal — that is the honest band.**
**Citations.** grep for `target_compile_options` across all 23 CMake files: zero hits (the
only `compile_definitions` hits are `SWELL_PROVIDED_BY_APP` at `src/app/CMakeLists.txt:80`,
`:92` and the SDK's `DEVELOPMENT`/`RELEASE` selector at
`src/shell/instrument/CMakeLists.txt:42`). `CMakeLists.txt:2830` for the absence of
`CMAKE_CXX_EXTENSIONS`.
**Mechanism.** The codebase has been compiled by exactly one compiler family. MSVC's default
is `/W1`; GCC/Clang's default is essentially silent. Adding `-Wall -Wextra` on the first
Linux build is the right move, but the size of the resulting diagnostic set over ~39k LOC is
not estimable from Windows, which is why the effort band is split. Do **not** add `-Werror`
in the same change.
Secondary, in the same family: `CMAKE_CXX_EXTENSIONS` is unset, so it defaults to `ON` and
GCC/Clang compile as `-std=gnu++17` rather than `-std=c++17`. Not a bug; a hygiene knob
worth flipping while the flags are being set, since it is the difference between "portable
C++17" and "whatever GNU extensions happened to be used".
**Coverage hole: the link-succeeds-but-load-fails asymmetry is never stated.** GNU `ld` does
not error on undefined symbols in a shared object by default — MSVC's linker does. For a
`MODULE` REAPER `dlopen()`s, that means a Linux build can link `reaper_reasampler.so` clean
and only discover a missing symbol when REAPER tries to load it (`dlopen` failing, or a
partially-resolved symbol table if a satisfying-by-coincidence symbol exists elsewhere in the
process — a real risk given Λ-03's global-interposition finding above). Neither `Threads`
(Λ-04) nor visibility (Λ-03) named this asymmetry, and it undercuts §5's framing of V1
(`cmake --build build`) as "the single highest-information action available" — a clean build
on Linux does not carry the same guarantee a clean Windows build does. `-Wl,--no-undefined`
(GNU ld) would restore the MSVC-equivalent fail-at-link-time behavior; whether it is needed
here specifically depends on whether `SWELL_PROVIDED_BY_APP`'s function-pointer design (§1a)
already accounts for every symbol the modstub doesn't itself define — that is `[verify —
Linux]`, since it requires an actual GCC/Clang link to observe.
**Done when:** the Linux build either adds `-Wl,--no-undefined` (or the equivalent) so an
undefined-symbol build failure surfaces at link time, or a stated reason is recorded for why
`SWELL_PROVIDED_BY_APP` makes the gap moot.
*Shared macOS/Linux — `-Wall -Wextra`, `CMAKE_CXX_EXTENSIONS OFF`, and the GNU-ld-vs-MSVC-ld
asymmetry (macOS's linker also does not default to erroring on undefined symbols) apply
identically to the APPLE branch.*
---
### Λ-10 — the submodule story costs a Linux developer a large download for a target that is gated off
**Severity: Minor. Effort: S — a doc paragraph.**
**Citations.** `.gitmodules` (three entries, no `shallow`, no `branch`);
`README.md:7086`; `src/shell/instrument/CMakeLists.txt:9`; `CLAUDE.md` §"One-time submodule setup".
**Mechanism.** `README.md:7275` already warns that `git clone --recursive` pulls all of
`vendor/vst3sdk`'s nested submodules (`vstgui4`, `tutorials`, `doc`, `cmake`) that this
project never links, and prescribes the narrow init instead. What neither the README nor
`CLAUDE.md` says is that on Linux the `vendor/vst3sdk` submodule is **pure cost**: the
`WIN32 AND EXISTS` gate at `src/shell/instrument/CMakeLists.txt:9` omits the target
regardless, so `git submodule update --init vendor/reaper-sdk vendor/WDL` is the complete
Linux prerequisite. One sentence in the platform-support table would save every Linux
contributor the download.
---
## 3. Surfaces checked and found clean
Recorded so the plan author does not re-spend effort here. Each was read or grepped in this
pass.
- **All 23 `CMakeLists.txt` files were read in full**, not sampled: root; `src/app`;
`src/core`; `src/core/{audio,capture,instrument,json,model,reclaim,tracking,ui,util,version,view,wire}`;
`src/core/instrument/{bake,engine,map,note,ui}`; `src/core/instrument/engine/{filter,loop}`;
`src/shell/instrument`. Plus `cmake/reasampler_targets.cmake`. Of these, 21 are entirely
platform-neutral — they declare libraries and tests through the two helpers and nothing
else.
- **`CMAKE_POSITION_INDEPENDENT_CODE ON`** (`CMakeLists.txt:30`) — the usual Linux
`MODULE`-fed-by-`STATIC` trap, already handled.
- **`.so` naming.** `PREFIX ""` (`src/app/CMakeLists.txt:66`) + `SUFFIX ".so"` (`:93`) +
channel-derived `OUTPUT_NAME` (`:67`) yields `reaper_reasampler.so` /
`reaper_reasampler_beta.so`, matching the `reaper_*` convention. `ARCHIVE_OUTPUT_DIRECTORY`
(`:69`) is a Windows import-lib concern and harmlessly inert on Linux.
- **The channel fork is platform-independent.** `REASAMPLER_CHANNEL` (`CMakeLists.txt:4054`)
threads through `configure_file` (`:5861`) into names only; nothing in it is
Windows-specific, so beta builds fork identically on Linux.
- **The version padding canary** (`src/core/version/CMakeLists.txt:2142`) uses a
function-scoped `set()` + second `configure_file` + longhand `add_executable`. Portable;
no platform assumption.
- **The whole test corpus is platform-neutral.** 91 files in `tests/`, 91 declarations in
CMake. Only `test_capture_paths.cpp` branches on platform and it already has POSIX
expectations written; only `test_pitch_shift.cpp` mentions `windows.h`, in a comment.
- **Generator-shape handling in the docs is already correct.** `README.md:9398` explains
that `-C Debug` is required on multi-config and unnecessary on Ninja/Make. `ctest --test-dir
build` works bare on Linux; the `-C Debug` in the README's example is harmless there.
- **SWELL API coverage for the LICE slice** — all six SWELL GDI entry points LICE needs are
in the modstub-resolved table (`swell-functions.h:857`, `:863`, `:877`, `:885887`).
- **The LICE slice needs no fifth TU on Linux** (`lice.cpp:3040` `_LICE_RGB2HSV_invtab`
table, `lice_textnew.cpp:26` file-static `utf8makechar`) — an inference from V1's link
success plus these two spot checks, not exhaustive; see §1a's fuller caveat, including the
unreconciled `lice_colorspace.o` in SWELL's own `Makefile:106107`.
- **`swell-modstub-generic.cpp` compiles against its own includes** — it uses `printf`
(`:61`), which arrives via `swell.h``swell-types.h:29` (`#include <stdio.h>`). The
`dlopen`/`readlink` block (`:69131`) is behind `SWELL_LOAD_SWELL_DYLIB`, which this build
never defines.
- **The Linux run-loop IIDs are already in the vendored VST3 slice.**
`public.sdk/source/common/commoniids.cpp:5054` defines `Linux::IEventHandler`,
`Linux::ITimerHandler` and `Linux::IRunLoop` under `#if SMTG_OS_LINUX`, and that file is
already in the `vst3_sdk` source list (`src/shell/instrument/CMakeLists.txt:36`). A Linux
VST3 port needs no additional SDK translation unit for the run loop.
- **`SMTG_OS_LINUX` / `SMTG_EXPORT_SYMBOL` are correct in the pinned SDK**
(`pluginterfaces/base/fplatform.h:132`, `:164`).
- **The MSVC-ABI caveat is Windows-scoped.** `reaper_plugin.h:22` warns that the C++
interfaces "require MSVC on win32, or at least the MSVC-compatible C++ ABI" — that is a
constraint on Windows toolchains (mingw), not on Linux, where REAPER and the extension both
use the Itanium ABI.
---
## 4. The VST3-on-Linux question, stated as a fork
Daniel rules on this. Below is the cost of each side with the evidence, and nothing else.
### Fork A — extension only on Linux
Scope: everything in §2 (Λ-01 through Λ-10). The VST3 gate at
`src/shell/instrument/CMakeLists.txt:9` stays exactly as it is; a Linux configure omits the
target and the `vendor/vst3sdk` submodule becomes optional there (Λ-10).
**Cost profile:** one Major that must be solved (Λ-01, the panel), two Majors that are
one-line-ish but load-bearing (Λ-02 optimization, Λ-03 visibility), one Major/Minor
(Λ-04 threads), and six Minors. No new third-party dependency. No new artifact format. No
change to any product decision on record.
**The unknown that dominates the band:** none of the extension's source portability is
audited here. The build-system work is small; whether the 38 shell TUs *compile and behave*
against SWELL's Win32 subset is T2's answer, and it, not this list, sets the phase's size.
### Fork B — extension + ReaSampler 9000 on Linux
Everything in Fork A, plus the following. Three of five are Blockers under the severity
vocabulary defined above ("the Linux build cannot produce a loadable artifact"): B1, B2, B3.
B4 downgrades to Major — the module still loads; only the editor fails to attach without it.
B5 is not a technical blocker at all — it is a documentation act, though one that must
precede the others in sequence (see §6 Stage 5).
- **B1 — the entry point is the wrong one, and the right one is already vendored.**
`src/shell/instrument/CMakeLists.txt:78` compiles
`public.sdk/source/main/dllmain.cpp` into the module. That file does
`#include <windows.h>` at `:41` with no `SMTG_OS_*` guard — grepping the file for
`SMTG_OS` returns nothing, and its only conditionals are
`#if defined(_MSC_VER) && defined(DEVELOPMENT)` (`:43`, `:96`) and `#ifdef __cplusplus`
(`:58`, `:87`). Linux needs
`public.sdk/source/main/linuxmain.cpp`, which is present in the slice and exports
`ModuleEntry`/`ModuleExit` (`extern "C"` declarations `linuxmain.cpp:4752`; definitions
`:5967` and `:7282` respectively). Both are **mandatory** — the
SDK's own loader refuses the module without either
(`public.sdk/source/vst/hosting/module_linux.cpp:189204`, error strings "The shared
library does not export the required 'ModuleEntry' function" and the same for `ModuleExit`).
`GetPluginFactory` is checked at `:205`. **Effort S** — a `CMakeLists.txt` source swap
(`dllmain.cpp``linuxmain.cpp`) plus the platform `if()`; both files are already vendored,
nothing to write from scratch.
- **B2 — the artifact is a directory bundle, not a file.** Today the target sets
`SUFFIX ".vst3"` on a MODULE (`src/shell/instrument/CMakeLists.txt:106111`), producing a
single file. `module_linux.cpp:146170` (`getSOPath`) shows what a Linux host actually
opens: the path must be a **directory**, containing `Contents/`, containing
`<machine>-linux/` where `<machine>` is `uname().machine` (`:158163`, helper at `:8897`),
containing `<stem>.so` (`:167168`). So `reasampler_9000.vst3/Contents/x86_64-linux/reasampler_9000.so`.
That is `add_custom_command(POST_BUILD)` work plus an install rule. Install roots are
`$HOME/.vst3/`, `/usr/lib/vst3/`, `/usr/local/lib/vst3/` and `$APPFOLDER/vst3/`
(`module_linux.cpp:282302`). `Contents/Resources/moduleinfo.json` is **optional**
`getModuleInfoPath` (`:356365`) returns empty when the file is absent rather than failing.
**Effort M** — mechanical, but it is a new artifact shape with an install story and a
per-architecture directory name.
- **B3 — the drawing stack is the real cost, and it is where Fork B stops being a build task.**
The VST3 module compiles the same four LICE TUs (`src/shell/instrument/CMakeLists.txt:80`),
and on non-Win32 LICE resolves its GDI through SWELL (§1a). But **a VST3 plugin is not a
REAPER extension**: `swell-modstub-generic.cpp`'s default branch exports `SWELL_dllMain`
(`:135`), which only REAPER's *extension* loader calls. Nothing hands a VST3 plugin the
SWELL function table. That leaves two routes:
- **Route B3a — `SWELL_LOAD_SWELL_DYLIB`** (`swell-modstub-generic.cpp:69131`): the stub
reads `/proc/self/exe`, strips to the directory, and `dlopen`s `libSwell.so` beside the
host binary (`:8198`), then calls `SWELL_set_app_main(SWELLAppMain)` (`:112114`). That
reference makes `SWELLAppMain` a **required definition in the plugin** — it is declared at
`swell-types.h:137` as "to be implemented by app (if using swellappmain.mm)". Whether
REAPER's Linux install ships a
`libSwell.so` beside its executable is `[verify — Linux]`, and this route makes the VST3
load-bearing on being hosted by REAPER specifically, which is consistent with D5's
REAPER-only stance but is a new runtime coupling to state explicitly.
- **Route B3b — build SWELL into the module.** `vendor/WDL/WDL/swell/Makefile:100104`
enumerates the 14 SWELL TUs (`swell.o swell-ini.o swell-miscdlg-generic.o
swell-wnd-generic.o swell-menu-generic.o swell-kb-generic.o swell-dlg-generic.o
swell-gdi-generic.o swell-misc-generic.o swell-gdi-lice.o swell-generic-headless.o
swell-generic-gdk.o swell-appstub-generic.o swell-modstub-generic.o`) and `:106107` the 8
LICE TUs it needs alongside. Link requirements at `:90` (`-lpthread -ldl`), `:128130`
(pkg-config `gtk+-3.0` or `gdk-3.0`), `:145151` (`freetype2` + `-lfontconfig`) and
`:154` (`-lGL`).
**This is a wholly new third-party dependency surface** — GDK/GTK3, FreeType, Fontconfig,
OpenGL — that the extension deliberately avoids via `SWELL_PROVIDED_BY_APP`. Flagging it
as a scope expansion, per the dispatch's constraint; it is not something to slip in.
**Effort L either way**, and B3b is the larger of the two by a wide margin.
- **B4 — the editor's platform contract changes.** The view must report
`kPlatformTypeX11EmbedWindowID` (`pluginterfaces/gui/iplugview.h:79`) instead of
`kPlatformTypeHWND` (`:62`), and timers/file-descriptors must go through
`Steinberg::Linux::IRunLoop` (`iplugview.h:267279`) with `IEventHandler` (`:223229`) and
`ITimerHandler` (`:239245`) — the header states the reason at `:255256`: "On Linux the
host has to provide this interface to the plug-in as there's no global event run loop
defined as on other platforms." The whole `namespace Linux` block is `#if SMTG_OS_LINUX`
(`:209`, closed `:284`), so it compiles in automatically. The **build-side** cost is nil
(the IIDs are already vendored — see §3); the **source-side** cost is `editor_platform.cpp`
and every timer in the editor, which is T2's surface. **Effort: build S, source L** — build
is S because no new CMake source is needed (the SDK block compiles in automatically); source
is L because it is a genuine window/run-loop rewrite (an X11 embed contract with no Win32
analogue, not a mechanical port) and outside this doc's own portability scope to size
further.
- **B5 — a settled product decision has to be reversed, in writing.** D5 ("Windows-only,
VST3-only, REAPER-only") is recorded as a locked decision with "a mac/Linux build" named
as a non-goal in `src/core/instrument/CLAUDE.md` (Invariants → the three locked decisions;
and again under Non-goals/guardrails) and `src/shell/instrument/CLAUDE.md`
(Non-goals/guardrails). `src/shell/panel/CLAUDE.md` carries a third dependent statement.
Fork B is not just more work — it invalidates three recorded invariants and needs Daniel's
explicit reversal before any code moves. **Effort S** — no code or CMake change of its own,
a rewrite of the three `CLAUDE.md` passages naming D5 plus Daniel's sign-off; the L-sized
cost sits in B3/B4, not here.
**The asymmetry worth naming.** Fork A's build work is small and its unknown is source
portability. Fork B's build work is genuinely large (B2, B3) *and* carries an unbounded
source-portability tail (B3b's dependency surface, B4's window/run-loop rewrite) *and*
requires reversing a settled decision. The two are not "the same phase, one bigger" — they
are different-shaped commitments.
---
## 5. Open questions
### `[verify — Linux]` — answerable by trying it on a Linux box
| # | Question | Exact check |
|---|---|---|
| V1 | Does the extension compile at all under GCC/Clang? | `cmake -B build -S . -G Ninja && cmake --build build 2>&1 \| tee build.log` — the single highest-information action available and gates most of T2's list too, with one caveat (Λ-09): a clean link is not the same guarantee here as on MSVC, since GNU `ld` does not error on undefined symbols in a `MODULE` by default — V1 answers "does it compile and link", not "does it load". |
| V2 | Does `ctest` pass all 91 targets? | `cmake -B build -S . -G Ninja && cmake --build build && ctest --test-dir build --output-on-failure` (no `-C` needed on Ninja). |
| V3 | Does REAPER's Linux build call `SWELL_dllMain` in a `reaper_*.so`, populating the API table? | Drop the built `.so` in `~/.config/REAPER/UserPlugins/`, restart, and check the extension's actions appear. A null table shows as immediate crash or dead actions. |
| V4 | Where exactly is `UserPlugins/` on Linux, and is `reaper_*.so` the right filename glob? | Options → Show REAPER resource path in a Linux REAPER. The SDK headers do not document either — grep of `vendor/reaper-sdk/sdk/` for `UserPlugins` and `reaper_*.so` returns nothing. |
| V5 | Does `panel_state.h:23`'s `<pthread.h>` actually require a link flag on the target glibc? | Build without `Threads::Threads`; if it links, it does not. |
| V6 | Does `-fvisibility=hidden` leave `ReaperPluginEntry` and `SWELL_dllMain` exported? | `nm -D --defined-only reaper_reasampler.so \| grep -E 'ReaperPluginEntry\|SWELL_dllMain'` after adding the preset. |
| V7 | With Λ-01 fixed by the resource-id-0 route, does `SWELL_CreateDialog` return a usable child HWND for the docker? | Panel toggle action in a Linux REAPER. |
| V8 | Does `std::filesystem` need `-lstdc++fs` on the chosen toolchain? | Build `capture_paths_tests` alone; the link error names it. |
| V9 | Does REAPER's Linux install ship a `libSwell.so` beside its executable (Fork B, route B3a)? | `ls $(dirname $(readlink -f $(which reaper)))/libSwell.so`. |
| V10 | Which `uname -m` values must the VST3 bundle carry (Fork B, B2)? | `uname -m` on each target. `module_linux.cpp:158163` keys the bundle directory off exactly this string (tree-grounded and verified); which architectures REAPER itself ships for Linux (x86_64, aarch64, armv7l is the claim) is an external fact with no source in this tree — `[verify]` against REAPER's own download page before relying on it. |
### `[Daniel]` — genuine product/scope calls
| # | Question | Why it is not answerable by reading code |
|---|---|---|
| D1 | **Fork A or Fork B?** Extension only, or extension + ReaSampler 9000 on Linux? | §4 states both costs. The choice is scope, and D5 makes it a reversal of a recorded decision, not a technical lookup. |
| D2 | If Fork B: **route B3a (dlopen the host's `libSwell.so`, requires defining `SWELLAppMain`) or B3b (vendor and build full SWELL, adds GDK/GTK3 + FreeType + Fontconfig + OpenGL)?** | B3b is a dependency-surface expansion; the dispatch requires that be flagged rather than chosen. B3a is cheaper but couples the plugin's UI to being hosted by REAPER specifically. |
| D3 | Is **macOS in or out** of the same phase? | Λ-01, Λ-03, Λ-04, Λ-07 and Λ-09 are all marked *shared macOS/Linux* at their own sections above (Λ-01: identical broken comment block, `src/app/CMakeLists.txt:8386` vs `:9497`, and shared `swell_resgen.php` output per `README.md:120`; Λ-03/04/07/09: same mechanism under the APPLE branch, detailed at each). Doing both at once is cheaper than doing them serially — but that is a scope call, and macOS additionally implies signing/notarization (not mentioned anywhere in `versioning-and-release.md`) plus its own open question this doc does not resolve: whether `swell-modstub.mm` (`src/app/CMakeLists.txt:79`) even compiles under a CXX-only `project()` (`CMakeLists.txt:26`, no `OBJCXX`) — see §1a. |
| D4 | Does **CI get built in this phase**, and on what runner? | `versioning-and-release.md:307311` and `:361363` hand "the pipeline" to dev-ops and commit to three platform artifacts per channel, but no CI exists in the repo on any platform. Adding it is infrastructure and needs an explicit ask. |
| D6 | Is the Linux artifact **shipped or developer-only** for 1.x? | Determines whether Λ-02 (Release build) and Λ-08 (install path) are must-fix or nice-to-have, and whether a Linux `install()` rule is worth authoring. (Numbered D6, not D5, to avoid colliding with the settled product decision D5 — "Windows-only, VST3-only, REAPER-only" — cited above at §1b and B5.) |
| D7 | Λ-01's fork: **resource-id-0 escape hatch, or the resgen route?** §6 Stage 2 gates on T2's read of `panel_window.cpp`, and V7 presupposes the route is already picked. | It is a source-code + build-pipeline tradeoff (a `panel_window.cpp` DLGPROC→WNDPROC change vs. a PHP build step + generated-file handling) with no code-only right answer — needs Daniel's call once T2 reports, same as D1/D2. |
Deliberately **not** listed as `[Daniel]`, because reading more would settle them: whether
`arrange_drop_win.cpp`/`instrument_drop_win.cpp` need platform gating (read the files — T2);
whether the SDK's `moduleinfo.json` is required (it is not — `module_linux.cpp:362364`);
whether the Linux run-loop IIDs need a new SDK TU (they do not — `commoniids.cpp:5054`).
---
## 6. Ordering sketch
Dependency order only — this is sequencing input for a plan author, not the plan.
**Stage 0 — the one action that reprices everything.** Run V1 and V2 on a Linux box against
the tree as-is. Configure will succeed (nothing in the CMake requires Windows); the compile
will produce a diagnostic set that is the actual size of this phase. Every band below is
provisional until this is done. Λ-10's doc fix rides along free, since the person doing this
will hit it first.
**Stage 1 — toolchain floor, no source dependency.** Λ-02 (`CMAKE_BUILD_TYPE` default),
Λ-03 (visibility presets), Λ-04 (`Threads::Threads`), Λ-09 (warning flags + `CXX_EXTENSIONS
OFF`), Λ-05 (pin the `WDL_INC` coincidence), Λ-07 (compiler floor). All are root- or
target-property edits with no ordering constraint among them and none touching source. Doing
them *before* Stage 2 means the resource work is done under warnings rather than retrofitted
into them. Ship as one change.
**Stage 2 — the panel resource decision.** Λ-01. This forks on the resource-id-0 question
(§2, Λ-01) and therefore needs T2's read on `panel_window.cpp` first — so it is gated on T2
output, not on Stage 1. Whichever route wins, it is a shared macOS/Linux fix (see D3).
**Stage 3 — source partition.** Λ-06. Once T2 names which TUs need a platform branch or a
non-Windows sibling, the source list in `src/app/CMakeLists.txt:851` gains its
partition. Strictly after T2 and after Stage 2 (the resgen/shim TU, if that route is taken,
is one of the entries).
**Stage 4 — packaging.** Λ-08, plus whatever D6 decides. Depends on Stage 1 (there is no
point documenting an install path for an unoptimized artifact) and on V4.
**Stage 5 — Fork B, only if D1 says so.** Internally ordered: B1 (entry point swap, S) →
B3 (SWELL strategy per D2 — this gates everything downstream, because a module that cannot
draw cannot be tested) → B2 (bundle layout + install, needs V10) → B4 (X11 embed + run loop,
mostly T2's source work). B5 (the D5 reversal) precedes all of them as a documentation act.
---
## 7. Referred to T2
Source-level items I noticed while reading build files. **Recorded, not analyzed** — the
parallel track owns each of these and I have deliberately not investigated further.
1. `src/shell/panel/panel_window.cpp:135``CreateDialogParam` + `MAKEINTRESOURCE(IDD_BANK_PANEL)`.
Under SWELL this is `SWELL_CreateDialog(SWELL_curmodule_dialogresource_head, …)`. Relevant
to Λ-01's resource-id-0 option, which requires the proc to be a `WNDPROC` returning
`LRESULT`, cast to `DLGPROC` (`swell-functions.h:606608`).
2. `src/shell/actions/arrange_drop_win.cpp` and `src/shell/actions/instrument_drop_win.cpp`
zero `_WIN32` occurrences, no `<windows.h>`, yet `_win`-suffixed. Confirm they are
genuinely portable, or add guards.
3. `src/shell/actions/drag_out_win.cpp:249282` — the `#else` "macOS / Linux (SWELL)" branch
exists but has never been compiled. Whether the SWELL drag path is functionally equivalent
to the Win32 `IDataObject`/`IDropSource` path is unaudited.
4. `src/shell/persist/prune_fs.cpp:36``<windows.h>` behind two `_WIN32` guards. Confirm the
non-Windows deletion path exists and is equivalent (this file is on the only
file-deletion path in the product, per `src/core/reclaim/CLAUDE.md`).
5. `src/shell/panel/draw_kit.cpp:1115`, `draw_kit.h:2729`, `src/shell/panel/panel_state.h:1826`
the `windows.h`-vs-`swell/swell.h` include switches. These look correct; whether the
SWELL subset actually covers every GDI call the kit makes is the question.
6. `src/shell/panel/CLAUDE.md` records "Windows-only (D5) — font/GDI/HFONT choices assume
Windows; no cross-platform font-fallback concern" as an invariant. Font selection on
Linux SWELL (FreeType/Fontconfig-backed) is the concrete instance.
7. `src/core/capture/capture_paths.cpp``normalizeSlashes` lowercases on `_WIN32` only, and
`tests/test_capture_paths.cpp:1946` already encodes the case-sensitive POSIX contract.
The test is written; the behaviour under a case-sensitive filesystem is unverified.
@@ -0,0 +1,792 @@
# Λ-W1 Track 2 — source/runtime Linux-portability audit
Static analysis of `src/**/*.{cpp,h}` (293 files) plus the vendored SWELL / WDL / LICE /
REAPER-SDK / VST3-SDK headers those files consume, 2026-08-02, branch
`pl-w1-t2-source-runtime-audit` (cut from `dev` at 6e937b9). Answers one question: **what in
the source blocks or degrades a Linux build/run**, for the extension (`reaper_reasampler`) and,
separately, for the ReaSampler 9000 VST3 instrument (`reasampler_vst`).
Build-system surface (CMake, `cmake/`, resgen as a *build step*, vendor configuration,
packaging, install) is a parallel track's; anything spotted here is listed under
**§7 Referred to T1** rather than analyzed. macOS is out of scope except where a Linux fix
shares its path — noted inline, one line, never a separate finding.
**Evidence discipline.** Every capability claim about SWELL / LICE / the REAPER SDK / the VST3
SDK cites the vendor file it was read in. The author is on Windows and **cannot build or run on
Linux**: nothing below was compiled or executed on Linux. Claims that need a Linux box carry
`[verify — Linux]` with the exact check. Line numbers were re-read against the working tree
immediately before writing.
---
## 1. Baseline — the portability posture today, by layer
### 1.1 `core/` — genuinely portable. Verified, not assumed.
Two independent checks, both exhaustive over the directory:
- **Include surface.** Every `#include` in `src/core/**` is either a `"core/…"` sibling, one of
26 standard-library headers, or the CMake-generated `version_generated.h`
(`src/core/version/app_version.cpp:12`, `src/core/wire/reasampler_uid.h:13`). **Zero** REAPER,
SWELL, WDL, LICE, VST3-SDK, `windows.h`, or other vendor includes. The 26 headers are
`<algorithm> <array> <atomic> <cassert> <cctype> <cerrno> <climits> <cmath> <cstddef>
<cstdint> <cstdio> <cstdlib> <cstring> <filesystem> <fstream> <limits> <map> <optional>
<set> <sstream> <string> <type_traits> <unordered_map> <unordered_set> <utility> <vector>` —
all C++17, all present on libstdc++/libc++.
- **Preprocessor surface.** The whole of `core/` contains exactly **nine** preprocessor
conditional lines, in three places: the channel fork (`core/wire/reasampler_uid.h:29,34,39`),
two `NDEBUG` assert guards (`core/view/view_mode_model.cpp:326,328,331,334`), and **one**
platform conditional — `core/capture/capture_paths.cpp:1820`, the Windows-only case-fold in
`normalizeSlashes`. That is the entire platform-dependence of the pure core.
Byte-order is explicitly handled rather than assumed: `core/wire/bytes.h:2631,6274` builds and
reads little-endian by shift, not by `memcpy` of a native integer, so it is byte-order-neutral
by construction. `core/capture/wav_codec.h:5253` states the one real assumption ("target is
x86/ARM-LE only, no big-endian byte-swap") and `wav_codec.cpp:165168` memcpys floats under it —
correct on x86-64 and aarch64 Linux alike.
Sweeps that returned **nothing** across `src/core` **and** `src/app`: `sprintf_s`/`strcpy_s`/
`_stricmp`/`_snprintf`/`_alloca`/`__forceinline`/`__declspec`/`#pragma comment`/`#pragma warning`/
`#pragma pack`/`__int64`/`LPSTR`/`LPCSTR`/`LPWSTR`/`wchar_t`/`TCHAR`/`_T(`/`MAX_PATH`. There is
**no** `#pragma` of any kind anywhere in `src/**` other than `#pragma once`, and no
`__attribute__` / `__declspec` / anonymous-struct extension.
`long` appears in a handful of pure modules (`core/ui/card_meta.cpp:3941,55`,
`core/instrument/ui/envelope_overlay.cpp:45`). All are local computations from clamped doubles;
LP64's wider `long` is strictly safer than LLP64's. One stale comment
(`core/instrument/ui/envelope_overlay.cpp:19`, "a huge t would overflow a 32-bit long") is
Windows-specific but the clamp it describes runs regardless. Not a defect.
**Verdict: `core/` builds and behaves identically on Linux.** The one conditional
(`capture_paths.cpp:18`) is *correct* for Linux — case-sensitive paths must not be folded — and
the pure tests already assert both branches (`tests/test_capture_paths.cpp:1933,4151`), which
is direct evidence the pure layer was written with a non-Windows target in mind.
### 1.2 `tests/` — portable.
91 test TUs. Only `tests/test_capture_paths.cpp` forks on `_WIN32`, and it asserts the
non-Windows behaviour explicitly (lines 2833, 5051). A `C:\`/`C:/` grep over `tests/` hits
six files total, one of which is `test_capture_paths.cpp` itself; the five OTHER files — every
hit opaque *string data* fed to a pure function
(`test_bank_model.cpp:186187,243245`, `test_bake_wire.cpp:77`, `test_drag_out.cpp:291293,388`,
`test_origin_ledger.cpp:56`, `test_sample_usage.cpp:502`) — are not platform behaviour. They pass
identically on Linux.
### 1.3 `app/` — portable.
`src/app/main.cpp` is one TU of pointers + entry + dispatch. `REAPER_PLUGIN_DLL_EXPORT` and
`REAPER_PLUGIN_HINSTANCE` are already GCC/Clang-correct in the SDK
(`vendor/reaper-sdk/sdk/reaper_plugin.h:5253``__attribute__((visibility("default")))` and
`void *`), and `REAPER_PLUGIN_ENTRYPOINT` is platform-neutral (`:56`). No Win32 call, no Win32
type, no conditional. The one hazard is behavioural, not structural — see **L2-03**.
### 1.4 `shell/` — the whole cost sits here, and it is unevenly distributed.
65 platform-token lines across 30 of the 293 source files (grep:
`_WIN32|WIN32|__APPLE__|_MSC_VER|__linux__|__GNUC__|_WIN64` over `src/**/*.{cpp,h}`). Their
distribution is the story:
| Area | Lines | Shape |
|---|---|---|
| `shell/instrument/` (VST3 editor + embed) | 51 of 65 | Whole-TU `#ifdef _WIN32``#endif` — Windows-only by design |
| `shell/panel/` | 8 | Include-selection + two small `#else` bodies |
| `shell/persist/`, `shell/capture/`, `shell/actions/` | 4 | Trash fallback, `localtime_r`, the SWELL drag-out branch |
| `core/` | 2 | The case-fold |
Two `shell/` directories are absent from this table because they were swept and came back
completely clean, not because they went unchecked: `shell/view/` and `shell/bank_ops/` both
return **zero** hits on the same grep (confirmed). Naming them here, since the table above is
by hit-count and gives a reader no way to tell a zero-hit sweep from an unswept directory.
`src/resource.h` and `src/ext_keys.h` mention platform names only in comments — zero hits on
this specific grep (re-run and confirmed), so they are not a row of this distribution; see
`resource.h`/`resource.rc` under §7 for their actual (build-system) relevance.
The extension's guards are all *complete*: every `#ifdef _WIN32` that gates a **definition**
has an `#else` (`draw_kit.cpp:12`, `capture.cpp:218`, `panel_audition.cpp:36,58`,
`panel_state.h:20`, `prune_fs.cpp:169`, `drag_out_win.cpp:8`); the ones without an `#else`
gate only an `#include` or a single statement (`panel_window.cpp:19,148`, `prune_fs.cpp:35`,
`draw_kit.h:27`, `capture_paths.cpp:18`). **There is no undefined-symbol gap from this guard
structure** — every `#ifdef` that needs an `#else` has one. This is narrower than "no
undefined-symbol gap in the extension" full stop: L2-02's `GetCurrentProcessId`
(`instrument_drop_win.cpp:59`) is an undefined symbol on Linux precisely because it carries
**no** `#ifdef` at all, so it falls outside what this guard-completeness check measures.
The instrument's guards are complete in the opposite direction: `reasampler_editor.h:156269`
wraps the entire paint/input/timer/`wndProc`/`invalidate` family in `#ifdef _WIN32`, and
`editor_platform.cpp:298306` stubs only the three IPlugView overrides that must exist. Every
`invalidate()` call site is inside a guard (verified exhaustively over `src/shell/instrument/`:
53 call sites across eight files — `editor_input.cpp` (5), `editor_input_browse.cpp` (11),
`editor_input_chrome.cpp` (10), `editor_input_curve.cpp` (4), `editor_input_deck.cpp` (9),
`editor_input_waveform.cpp` (4), `editor_platform.cpp` (3, excluding the definition itself at
`:65`), and `editor_session.cpp` (7, at 119, 126, 139, 141, 150, 156, 174, excluding a
same-named mention inside a comment at `:106`) — each file whole-file- or whole-region-guarded
by `#ifdef _WIN32` (e.g. `editor_input_browse.cpp:8``:177`); `reasampler_editor.h:266` is
the declaration, not a call site. `editor_controls.cpp`, `editor_models.cpp`,
`instrument_bake.cpp` have zero call sites, confirmed). So the editor *links* off Windows — it
just does nothing.
### 1.5 What the platform layer actually provides (vendor-verified)
The extension's non-Windows path is SWELL-provided-by-host
(`SWELL_PROVIDED_BY_APP` → function pointers resolved through `SWELL_dllMain`,
`vendor/WDL/WDL/swell/swell-modstub-generic.cpp:135145`). `[verify — Linux]` **What is stated
here about REAPER's own `libSwell.so` is only evidence about WDL's own Makefile, not about what
Cockos actually ships** — `vendor/WDL/WDL/swell/Makefile:100107,141151` shows
`swell-gdi-lice.o`/`-DSWELL_LICE_GDI` built whenever GDK is enabled (`ifndef NOGDK`, `:111`),
with `-DSWELL_FREETYPE` gated behind `ifndef NOFREETYPE` (`:144`) and `-lfontconfig` gated a
level deeper behind `ifndef NOFONTCONFIG` (`:149`) — i.e. the Makefile makes the LICE-backed,
freetype/fontconfig SWELL the *default* build, not a certainty about the binary REAPER
distributes. **Every downstream claim built on "REAPER's Linux SWELL is the fontconfig-backed
GDK build" inherits this same unstated assumption** — that includes L2-09's entire mechanism,
the GDK-backend evidence cited for L2-07, and the cursor (`GDK_*`) / modifier-key
(`GetAsyncKeyState`) claims below, none of which are re-flagged individually; this paragraph is
their one shared source of doubt. Contrast with the null stub in `swell-gdi-generic.cpp`
(`#ifndef SWELL_PROVIDED_BY_APP`, line 24), which is not in play for a REAPER-hosted extension
either way.
Everything the panel layer calls was checked by name against
`vendor/WDL/WDL/swell/swell-functions.h` and `swell-types.h`. Present and real:
- Window/dialog: `SWELL_CreateDialog` behind the `CreateDialogParam` macro
(`swell-functions.h:616,619`), `DestroyWindow`, `SetFocus`, `GetFocus`, `GetParent`,
`GetCapture`/`SetCapture`/`ReleaseCapture`, `IsWindowVisible`, `InvalidateRect`,
`ScreenToClient`/`ClientToScreen`, `BeginPaint`/`EndPaint`, `SetTimer`/`KillTimer`,
`GetWindowLong`/`SetWindowLong` (`:319320`), `SetWindowPos` (`:286`).
- Messages/macros: `GET_X_LPARAM`, `GET_Y_LPARAM`, `HIWORD`, `MAKEINTRESOURCE`
(`swell-types.h:1220`), `PAINTSTRUCT`, `MSG` (`:262`), `SRCCOPY`, `WM_PAINT`, `WM_MOUSEMOVE`,
`WM_MOUSEWHEEL`, `WM_CAPTURECHANGED`, `WM_DROPFILES`, `WM_KEYDOWN`, `WM_TIMER`,
`WM_ERASEBKGND`, `TPM_RETURNCMD`, `MF_*`, `MB_*`, `ID*`, every `VK_*` used.
- `WM_MOUSEWHEEL` really does carry **screen** coords in `lParam` on the GDK backend — the
comment at `panel_window.cpp:100102` is correct (`swell-generic-gdk.cpp:1442`).
- `WM_CAPTURECHANGED` really is delivered on capture loss (`swell-generic-gdk.cpp:1795`,
`swell-wnd-generic.cpp:7141,7150`), so the panel's rollback handler
(`panel_window.cpp:9098`) has a live trigger.
- Cursors: `LoadCursor``SWELL_LoadCursor` (`swell-functions.h:728730`), `SetCursor`
(`:740741`), and **all seven** IDCs the panel uses map to real GDK cursors —
`IDC_ARROW``GDK_LEFT_PTR`, `IDC_HAND``GDK_HAND1`, `IDC_UPARROW``GDK_CENTER_PTR`,
`IDC_SIZEWE``GDK_RIGHT_SIDE`, `IDC_SIZEALL``GDK_FLEUR`, `IDC_IBEAM``GDK_XTERM`,
`IDC_NO``GDK_PIRATE` (`swell-generic-gdk.cpp:37363748` vs `panel_drag.cpp:141147,159161`).
- `GetAsyncKeyState` returns the `0x8000` high bit for `VK_CONTROL`/`VK_SHIFT`/`VK_MENU`
(`swell-generic-gdk.cpp:24392441`), so `panel_state.h:409411` works verbatim.
- `GetTickCount` is SWELL-provided (`swell-functions.h:81`), so `panel_drag.cpp:308,324` — the
only unguarded Win32-looking calls in the panel — are fine.
- `SWELL_InitiateDragDropOfFileList` **does exist on Linux**, and is a GDK implementation on
the GDK backend: `swell-generic-gdk.cpp:35633592` sets up a hidden drop-source window and
spins a nested `SWELL_RunMessageLoop` until capture drops, with a 500 ms no-motion timeout;
the actual `gdk_drag_begin` call is inside the shared `dropSourceWndProc` helper it invokes
(`:3446`), not textually inside the `35633592` range itself. The headless backend defines
the **same-named function as an empty no-op stub**
`swell-generic-headless.cpp:246248` is `void SWELL_InitiateDragDropOfFileList(...) { }` — so
the "not a stub" framing only holds for the GDK backend specifically. The two backends are
mutually exclusive (`swell-generic-headless.cpp:28` is `#ifndef SWELL_TARGET_GDK`), so nothing
breaks in a GDK build, but a reader should not take "does exist on Linux" to mean "is
implemented in every Linux SWELL backend." macOS (`swell-dlg.mm:3534`) also defines it; it is
declared at `swell-functions.h:1011`.
- LICE itself is portable: `lice.h:31` includes `swell-types.h` off Windows, `lice.cpp:22`
includes `swell.h`, `LICE_SysBitmap::__resize` has a SWELL framebuffer path
(`lice.cpp:179182`), and `LICE_CachedFont::DrawTextImpl` carries real non-Windows branches
(`lice_textnew.cpp:236249,829,10271028,1040`).
Absent from SWELL, verified by grep over `vendor/WDL/WDL/swell/`: `FF_DONTCARE` (**zero hits
anywhere in `vendor/WDL/`**), `GetCurrentProcessId` (only `GetCurrentThreadId`,
`swell-functions.h:822`), `GetKeyState`, `WM_MOUSELEAVE`/`TrackMouseEvent`, `DragAcceptFiles`,
`RegisterClass*`, `CreateWindowEx*`, `DefWindowProc*`, `MoveWindow`,
`GetWindowLongPtr`/`SetWindowLongPtr`, `WHEEL_DELTA`, and any move-to-trash surface.
---
## 2. Findings
### L2-01 — `FF_DONTCARE` does not exist off Windows; `draw_kit.cpp` will not compile
**Location:** `src/shell/panel/draw_kit.cpp:73` (`DEFAULT_PITCH | FF_DONTCARE`), reached on
non-Windows through `draw_kit.cpp:1216` (which includes `swell/swell.h`, **not** `windows.h`).
**Mechanism.** `swell-types.h` defines `DEFAULT_PITCH`, `DEFAULT_CHARSET`,
`OUT_DEFAULT_PRECIS`, `CLIP_DEFAULT_PRECIS`, `DEFAULT_QUALITY`, `FW_BOLD`, `FW_NORMAL`,
`FW_SEMIBOLD`, `TRANSPARENT` and every `DT_*` the kit uses — but **not** `FF_DONTCARE`. A grep
for `FF_DONTCARE` over the whole of `vendor/WDL/` returns nothing; on Windows it comes from
`<wingdi.h>` via `windows.h`. `draw_kit.cpp` is not platform-guarded (only its *include* is), so
the `CreateFont` call is compiled on every platform.
**Severity: Blocker** — `error: 'FF_DONTCARE' was not declared in this scope` at
`draw_kit.cpp:73`; `draw_kit` is linked into both loadable modules, so the extension does not
build at all.
**Effort: S** — the argument is `DEFAULT_PITCH | FF_DONTCARE`, and `FF_DONTCARE` is 0x00 in
wingdi.h; the family bits are advisory to Windows' font mapper and meaningless to fontconfig.
**Direction.** Drop the `| FF_DONTCARE` term, or define it locally in the non-Windows include
branch. Do not add `windows.h`.
### L2-02 — `GetCurrentProcessId()` is called with no platform branch and SWELL does not export it
**Location:** `src/shell/actions/instrument_drop_win.cpp:59` (temp `.vstpreset` filename). The TU
has **no** `_WIN32` conditional anywhere (verified: its only `#include`s are `<atomic> <cstdint>
<filesystem> <fstream> <string> <system_error> <vector>` plus project/SDK headers, lines 627).
**Mechanism.** On non-Windows the declaration would have to come from `reaper_plugin.h`
`swell.h`. `swell-functions.h` declares `GetCurrentThreadId` (`:822`) and no
`GetCurrentProcessId`; the only two occurrences in the whole WDL tree are inside
`WDL/shm_msgreply.cpp:26` and `WDL/win32_utf8.c:244`, neither of which is a SWELL export.
**Severity: Blocker** — `error: 'GetCurrentProcessId' was not declared in this scope`; the
extension does not build.
**Effort: S** — the PID exists only to keep two concurrent REAPER instances from colliding in
the shared temp dir (comment at `:5657`). `getpid()` behind a guard, or the already-imported
`GetCurrentThreadId()` plus the existing atomic counter, satisfies the same requirement.
**Direction.** Replace with a platform-neutral uniqueness source; the atomic counter at `:52`
already carries the intra-process half.
### L2-03 — `REAPERAPI_LoadAPI` is all-or-nothing over ~869 API names and fails silently
**Location:** `src/app/main.cpp:292293` (`if (REAPERAPI_LoadAPI(rec->GetFunc) != 0) return 0;`).
`main.cpp` does **not** define `REAPERAPI_MINIMAL`, so the full table is loaded
(`vendor/reaper-sdk/sdk/reaper_plugin_functions.h:4448`; 1738 `REAPERAPI_WANT_` guards ≈ 869
entries).
**Mechanism.** The SDK's loader accumulates one `failcnt` across the entire table
(`reaper_plugin_functions.h`, `REAPERAPI_LoadAPI` body: `failcnt += !(*table[i].dest =
getAPI(table[i].name)); return failcnt;`). If a Linux REAPER build does not export *any single
one* of those 869 names, `main.cpp` returns 0 and the extension never loads — with **no console
message, no log line, nothing**. The SDK header carries no "Windows only" annotation on any
entry (grep for `windows only|win32 only|not on mac|not on linux` returns nothing), so nothing
here says a gap exists — but nothing rules it out either, and the failure mode is maximally
opaque.
**Severity: Blocker (conditional)** `[verify — Linux]` — a silent load refusal with no
diagnostic is the worst possible first-run experience for a port. **Scope note:** the
all-or-nothing mechanism itself is identical on Windows too
(`reaper_plugin_functions.h:4546` — "an older version of REAPER may not succeed in loading",
no platform fork in the loader) — nothing about the *mechanism* is Linux-specific, only whether
*this particular* build happens to be missing an entry is unknown. Graded here as a Linux
Blocker on failure-mode quality alone (per the Mechanism above), the same axis L2-04 is
graded on below, despite L2-04's mechanism being certain rather than speculative — see L2-04's
calculus note. Arguably this belongs as a cross-platform robustness note rather than a
Linux-exclusive finding; left here because the fix is trivial and worth doing regardless of
platform.
**Effort: S** — confirmed against the two Direction options below: the `ShowConsoleMsg`
diagnostic is one new line on the existing failure branch (`main.cpp:293`), and the
`REAPERAPI_MINIMAL` swap follows a pattern already used elsewhere in this codebase
(`panel_window.cpp:2631`, `panel_audition.cpp:1216`) rather than inventing a new one.
**Direction.** Either switch `main.cpp` to `REAPERAPI_MINIMAL` + an explicit `WANT` list (the
other TUs already do this — e.g. `panel_window.cpp:2631`, `panel_audition.cpp:1216`), or keep
the full load but print the failure count via `rec->GetFunc("ShowConsoleMsg")` before returning
0. The minimal list is also the honest inventory of what this extension actually needs.
### L2-04 — every persisted floating-point number is `LC_NUMERIC`-dependent, in both directions
**Location (writers):** `src/core/json/json.cpp:3943` (`%.17g` — the bank index, view model and
tracking ledger all serialize through it), `src/core/model/provenance.cpp:40` (`%.17g` — the
provenance blob inside the bank JSON). Two writers, not three: `tail_control.cpp:74` is a
comment describing the format ("Byte-identical to the former snprintf writer:
`{"mode":%d,"manualMs":%.17g}`"), not a write site — the actual per-project tail-setting write
is `tail_control.cpp:7879`, which already goes through `json::numToStr` (the same
`json.cpp:3943` codec cited above), so it is the same writer, not a third one.
**Location (readers):** `src/core/json/json.cpp:190196` (`std::strtod`),
`src/core/wire/wire.cpp:121130` (`Cursor::fieldDouble`, `std::strtod`),
`src/core/capture/render_settings.cpp:178186` (`std::stod` over REAPER's own `P_RAZOREDITS`).
**Mechanism.** `snprintf("%.17g")`, `strtod` and `stod` all honour `LC_NUMERIC`. Under a
comma-decimal locale the writers emit `1,5`, which makes the bank JSON *structurally invalid*
(an extra separator inside an object) — the whole index fails to parse on the next load. The
readers are honestly fail-closed (all three require whole-token consumption:
`json.cpp:194`, `wire.cpp:127`, `render_settings.cpp:184`), so they degrade to "malformed"
rather than silently truncating — but that means a razor range or a bank field simply
disappears. On Windows the CRT's start-up locale is `"C"` and nothing in this codebase calls
`setlocale`, which is why this has never fired. On Linux the process locale is far more likely
to be set by something else in the address space: SWELL's GDK backend calls `gtk_init_check`
when built with `SWELL_SUPPORT_GTK` (`swell-generic-gdk.cpp:366`; the `#else` branch uses
`gdk_init_check`, `:368`) and **never** calls `gtk_disable_setlocale` (grep over
`vendor/WDL/WDL/swell/` returns no hit), and any GTK/Qt-based plugin loaded into the same
process can do the same.
**Severity: Major** — builds and runs; under a non-C `LC_NUMERIC` the bank index is written
unparseable and the project's whole bank is lost on reload. **Calculus note:** unlike L2-03
(graded Blocker above on zero direct evidence, purely on failure-mode quality), this finding's
mechanism is confirmed by reading the actual writer/reader call sites, and its failure mode —
the entire bank index becomes unparseable — is at least as severe as L2-03's. It is graded only
Major here because it additionally requires a non-C `LC_NUMERIC` in the hosting process, a
likelihood factor L2-03 does not apply to its own claim. Reading both on the same axis (either
both by failure-mode quality, or both by likelihood) would put them closer together than
Blocker/Major suggests; resolving that is a scope call for whoever prioritizes the two, not a
fact this audit can settle statically.
**Effort: M** — two writers and three readers, all in `core/`, all unit-testable; the fix is
a locale-independent path (`std::to_chars`/`std::from_chars`, C++17, or an explicit
`std::locale::classic()`-bound stream), not a `setlocale` call in a plugin.
**Direction.** Make the number codec locale-independent at its two writers and three readers;
add a pure test that pins the emitted text for a fractional value. Do **not** "fix" this by
calling `setlocale` — an extension must not mutate the host's locale.
`[verify — Linux]` — read `LC_NUMERIC` inside a running REAPER-Linux process (e.g.
`ShowConsoleMsg(setlocale(LC_NUMERIC, nullptr))`) before sizing the work.
### L2-05 — prune loses the Recycle Bin *and* the "file is locked" backstop at the same time
**Location:** `src/shell/persist/prune_fs.cpp:167209`; the non-Windows branch is `:200208`.
**Mechanism.** Two Windows properties are load-bearing for the deletion authority and neither
survives. (a) The Windows path routes through `SHFileOperationW` + `FOF_ALLOWUNDO` (`:186188`)
— deletions are recoverable from the Recycle Bin; the `#else` is a hard `fs::remove` (`:203`).
The header already states this honestly (`:3034`, `:162166`). (b) Less obviously, the failure
taxonomy at `:205` (`if (ec) return false; // real failure (locked/permission) -> skip`) encodes
**Windows** file-sharing semantics: a bank file currently open by REAPER's audio engine (an
active `PCM_source`, an item playing from it) cannot be deleted on Windows, so it is counted as
"skipped". On Linux `unlink()` on an open file succeeds — the directory entry vanishes while the
open fd keeps playing, and when the fd closes the bytes are gone with no trash to recover from.
So the Linux prune can delete a file that is *audibly in use*, silently, and the user's only
recovery floor (the superseded-file-survives-until-prune rule, root `CLAUDE.md` §resample bake)
now has nothing under it.
**Severity: Major** — irreversible user-data loss where the Windows build is recoverable; the
"locked" skip branch is dead code on Linux.
**Effort: M** — trash is genuinely non-portable, but the XDG trash spec (`~/.local/share/Trash`
with a `.trashinfo` sidecar) is a self-contained move-plus-metadata write, and the confirm gate
already exists upstream.
**Direction.** Either implement an XDG-trash move in the `#else` (preferred — the deletion
authority is a single ~40-line function and this is exactly where the platform seam belongs), or
make the prune confirmation text platform-aware so a Linux user is told the deletion is
permanent. Do not leave the current silent asymmetry.
### L2-06 — the docked panel never opens on Linux, and fails silently when it doesn't
**Location:** `src/shell/panel/panel_window.cpp:135137`.
**Mechanism.** `CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_BANK_PANEL), …)` maps on SWELL to
`SWELL_CreateDialog(SWELL_curmodule_dialogresource_head, (resid), …)`
(`swell-functions.h:616,619`) — it resolves the template out of a per-module registry populated
by the **resgen-generated source**, not out of a linked `.rc`. That generated source is not
currently part of the Linux target (the `target_sources` line is commented out;
build-system detail → §7). The source-side consequence is what matters here: `SWELL_CreateDialog`
returns `nullptr`, `panel_window.cpp:137` does `if (!g_panel.hwnd) return;`, and the toggle
action is a **silent no-op** — no console line, no message box, and `bankPanelIsOpen()` keeps
reporting false so the Actions-list checkmark never lights. The user's only symptom is "the
button does nothing." Note also that `MAKEINTRESOURCE` becomes `((const char*)(UINT_PTR)(x))` on
SWELL (`swell-types.h:1220`), so the id is a pointer-shaped integer — the resgen output must
agree on `IDD_BANK_PANEL == 1000` (`src/resource.h:8`).
**Severity: Major** — the extension loads, every action works, and the primary UI surface is
absent with no diagnostic.
**Effort: S** on the source side (one failure branch), separate from T1's resgen wiring.
**Direction.** Add a one-line `ShowConsoleMsg` on the `!g_panel.hwnd` path naming the missing
dialog resource. That single line converts a mystery into a two-minute diagnosis and is worth
having on Windows too.
### L2-07 — file-drop ingest onto the panel has no opt-in on SWELL
**Location:** `src/shell/panel/panel_window.cpp:145150` (the `DragAcceptFiles` call is
`#ifdef _WIN32`), handler at `:4761,6567`.
**Mechanism.** The comment at `:145147` is accurate — SWELL exposes no `DragAcceptFiles`
(grep over `vendor/WDL/WDL/swell/` finds only `DragQueryFile` and `DragFinish`,
`swell-functions.h:10061007`). What the comment does not say is *how* a drop would arrive
instead. Reading the GDK backend: on a URI-list selection-notify, SWELL resolves the top-level
window, walks down with `ChildWindowFromPoint` (which **is** descending — `for(;;)` loop,
`swell-wnd-generic.cpp:69566981`), and `SendMessage(cw, WM_DROPFILES, (WPARAM)gobj, 0)`
(`swell-generic-gdk.cpp:1622`). The default child proc forwards an *unhandled* `WM_DROPFILES`
up to the parent only when the window *lacks* `WS_EX_ACCEPTFILES`
(`swell-wnd-generic.cpp:7681`) — but that bit's only effect is to **suppress** the up-forward;
it does not enable acceptance, and the message already reaches the window under the pointer via
the `ChildWindowFromPoint` descent regardless of the bit's state. So the panel's own `dlgProc`
plausibly receives the drop **without any opt-in at all**, but the earlier "ex-style bit, not
an API call" framing was backwards about what the bit does. The real SWELL opt-in surface for
`WS_EX_ACCEPTFILES` is the dialog *resource*, not a runtime call: `swell_resgen.pl:10` and
`swell_resgen.php:204` translate a dialog's `WS_EX_ACCEPTFILES` style to
`SWELL_DLG_WS_DROPTARGET`, and `swell-dlg-generic.cpp:320321` sets
`h->m_exstyle |= WS_EX_ACCEPTFILES` from that flag at dialog-creation time. `src/resource.rc:19`
declares `STYLE WS_CHILD` only — no `WS_EX_ACCEPTFILES` — so the bit is off on Linux regardless
of anything `panel_window.cpp` does at runtime. That makes L2-07's real seam `src/resource.rc` +
resgen, the SAME work as L2-06 and §7 bullet 1, not an independent one-liner: a runtime
`SetWindowLong(..., GWL_EXSTYLE, ... | WS_EX_ACCEPTFILES)` would only suppress the
unhandled-drop forward-to-parent — it would not change whether the drop reaches `dlgProc` in
the first place, which already happens via the `ChildWindowFromPoint` descent independent of
the bit. Note also the doc's own conclusion is better-supported than it knew: `src/resource.rc:2122`
is `BEGIN`/`END` — zero child controls — so the GDK `ChildWindowFromPoint` descent has nowhere
to land but the panel HWND itself. Two supporting details still check out: SWELL's
`DragQueryFile` reads the same `DROPFILES` layout the handler assumes
(`swell-wnd-generic.cpp:7730+`), and SWELL's `DragFinish` is a documented no-op ("caller will
free hdrops", `:77257728`) while SWELL itself `GlobalFree`s the handle right after
`SendMessage` (`swell-generic-gdk.cpp:16231624`) — so `panel_window.cpp:59` calling
`DragFinish` is safe, not a double-free.
**Severity: Major `[verify — Linux]`** — if the routing does *not* reach a docked child dialog,
one of the three ingest surfaces (file drop onto the bank panel) is silently dead with no error.
The evidence above says it probably works; it is not proof, and it cannot be exercised until
the panel itself renders (T1's resgen wiring — see L2-06).
**Effort:** no independent source-side fix exists — this is the same resgen work already
costed under L2-06 / §7 bullet 1. Do not add an `Effort: S` line here; adding the
`SetWindowLong` call would compile, do nothing observable, and send an implementer looking for
a bug that isn't where they'd look.
**Direction.** No separate fix. Once the resgen work lands the panel dialog with
`WS_EX_ACCEPTFILES` set from the resource, verify: `[verify — Linux]` drop a WAV onto the
docked panel and confirm `WM_DROPFILES` reaches `dlgProc`.
### L2-08 — the VST3 instrument has no Linux editor, and no automatable parameters to fall back to
**Location:** `src/shell/instrument/editor_platform.cpp:3742` (`isPlatformTypeSupported`
returns `kResultTrue` **only** for `kPlatformTypeHWND`, and only inside `#ifdef _WIN32`);
`:298306` (the non-Windows stubs); `reasampler_editor.h:156269` (the entire paint/input family
is `#ifdef _WIN32`); `reasampler_embed.cpp:135141` (`REAPER_FXEMBED_WM_IS_SUPPORTED` returns 0
off Windows). `reasampler_processor.cpp:360365` still hands the host a `ReaSamplerEditor`.
**Mechanism.** The VST3 SDK *does* support Linux — `kPlatformTypeX11EmbedWindowID`
(`vendor/vst3sdk/pluginterfaces/gui/iplugview.h:79`), `Linux::IRunLoop` with
`registerEventHandler`/`registerTimer` (`:267279`), `Linux::IEventHandler` (`:223`),
`Linux::ITimerHandler` (`:239`), and a `linuxmain.cpp` module entry
(`vendor/vst3sdk/public.sdk/source/main/linuxmain.cpp`). The instrument simply does not
implement any of it. The consequence compounds: with `isPlatformTypeSupported` false for every
type, the host falls back to a **generic parameter UI** — and a grep for
`addParameter|parameters\.add|getParameterCount` across `src/shell/instrument/*.cpp` returns
**nothing**. Zero VST3 parameters are registered as of this branch's base. A Linux user would
get an instrument with no editor and no controls whatsoever. (Phase Γ-W4-T1
`vst3-parameter-set``docs/product/parameter-automation.md` — is landing the parameter set
concurrently, which materially improves this fallback; the *editor* gap is unaffected.)
The specific Win32 dependencies a Linux editor would have to replace, each verified absent from
SWELL: `RegisterClassW`/`CreateWindowExW`/`DefWindowProcW` (`editor_platform.cpp:79103,294`) —
SWELL has no window-class model at all, only `SWELL_CreateDialog` and raw `HWND__` construction;
`MoveWindow` (`:133`) — SWELL has `SetWindowPos` (`swell-functions.h:286`) instead;
`GetWindowLongPtr`/`SetWindowLongPtr` (`:74,105,142`) — SWELL has the non-`Ptr` forms returning
`LONG_PTR` (`:319320`); `TrackMouseEvent`/`WM_MOUSELEAVE` (`:176198`) — SWELL has neither, a
gap the panel layer already documents at `panel_state.h:245246`; `GetKeyState`
(`editor_input_waveform.cpp:38`, `editor_input_curve.cpp:50`) — SWELL has only
`GetAsyncKeyState` (`swell-functions.h:712`); `DragAcceptFiles`/`DragQueryFileW`
(`:109,283`); `GetModuleHandle` (`:75`).
**Severity: Major (instrument only)** — the plugin would load and process audio; it would be
unplayable and uneditable.
**Effort: L** — an X11-embed `IPlugView` (`attachedToParent` receiving an X11 window id rather
than an HWND), an `IRunLoop`-driven timer replacing `SetTimer`/`WM_TIMER`, an event-driven
input path replacing the `wndProc` switch, and a LICE surface bound to that window. This is a
new competence, not a port of the existing one.
**Direction.** Treat as a separate, later decision from the extension (see §3). If it is ever
taken, the natural shape is a small platform seam under `shell/instrument/``editor_platform`
already *is* that seam; it needs a sibling, not a rewrite.
### L2-09 — the draw kit's font faces do not exist on Linux and substitute silently
**Location:** `src/shell/panel/draw_kit.cpp:7077` (`loadFont`), and the two literal faces it is
called with — Segoe UI and Consolas, per `draw_kit.h:6364`.
**Mechanism.** On Linux `CreateFont` goes through fontconfig when built with
`-DSWELL_FONTCONFIG` (gated per the `[verify — Linux]` note in §1.5):
`FcPatternAddString(pat, FC_FAMILY, lfFaceName)``FcConfigSubstitute`/`FcDefaultSubstitute`
`FcFontMatch` (`swell-gdi-lice.cpp:450487`). Whether `FcFontMatch` itself can return failure is
a claim about fontconfig's own internals — fontconfig is not vendored here, so it is dropped
rather than asserted uncited (this doc's own evidence-discipline rule). What the vendored code
does show: even a successful match doesn't guarantee a loadable face —
`swell-gdi-lice.cpp:480484` only sets `face` when `FcPatternGetString(hit, FC_FILE, …)`
resolves to a nonempty string AND the following `FT_New_Face` succeeds; either step can fail,
leaving `face` NULL, and in this build path there is no further fallback — the
`MatchFont`/LiberationSans/DejaVuSans list at `:493539` compiles only in the `#else`
(`#ifndef SWELL_FONTCONFIG`) branch. However `swell-gdi-lice.cpp:400401,561,564` show
`CreateFont` always allocates and returns a non-null `HGDIOBJ__*` regardless of whether `face`
resolved — the failure is recorded internally (`font->typedata = NULL`), not as a null return —
so `draw_kit.cpp:74`'s own `if (!hf) return` guard does **not** catch this failure mode; `hf`
comes back non-null either way. Whatever degraded outcome exists here comes from
`LICE_CachedFont`'s own handling of a null-`typedata` font (§1.5 already cites real
non-Windows branches in `lice_textnew.cpp:236249,829,10271028,1040`), not from `loadFont`'s
stated guard — `[verify — Linux]`. The two WCAG `static_assert`s (`draw_kit.cpp:5354`) are on
**pixel height and weight**, not on the face, so they still hold regardless.
**Severity: Minor** `[verify — Linux]` — cosmetic at best; whether it degrades further than
wrong metrics (e.g. to no text at all) rests on the unconfirmed downstream null-face handling
above, not on anything this audit can read statically.
**Effort: S** — confirmed against the actual call sites: five total (`draw_kit.cpp:154158`,
four using "Segoe UI", one "Consolas"), each a single string-literal argument. A platform
fallback is a `#ifdef`-guarded literal swap at those five sites, not a new mechanism —
`draw_kit.cpp:69`'s comment ("the face is chosen here so a change is one line") describes one
call's literal, not all five; the S estimate rests on there being only five call sites, not on
that comment's wording.
**Direction.** Add a platform fallback face list at the five `loadFont` call sites
(`draw_kit.cpp:154158`). DejaVu Sans / DejaVu Sans Mono are the safe Linux defaults; SWELL's
own no-fontconfig fallback list names LiberationSans/DejaVuSans and
LiberationMono/DejaVuSansMono (`swell-gdi-lice.cpp:505507`), a reasonable precedent to copy.
This same change fixes macOS (San Francisco / Menlo), one code path.
### L2-10 — OS drag-out on SWELL loses the copy-only mask, the readiness probe, and the outcome
**Location:** `src/shell/actions/drag_out_win.cpp:249282` (the `#else` branch);
`drag_out_win.h:711,2933` already states the first and third honestly.
**Mechanism.** Three separate degradations, all real but none fatal. (a) `DoDragDrop`'s
`DROPEFFECT_COPY`-only mask (`:230`) is a **structural** guarantee that no target can MOVE a
bank file out of the folder; `SWELL_InitiateDragDropOfFileList` takes no effect mask
(`swell-functions.h:1011`), so the guarantee reduces to whatever the GDK drag advertises.
(b) `canInitiateDragOut` degrades to `!paths.empty()` (`:276278`), so the caller's careful
coupling — "do not tear down the internal drag until the OS is known ready"
(`panel_drag.cpp:227244`) — has nothing to check against. (c) `initiateDragOut` returns `true`
unconditionally (`:270`), so the advisory success return is meaningless. The caller ignores it,
so (c) is inert today. Note the call path is already Linux-correct in one important respect:
`handOffToOs` releases capture and resets drag state (`panel_drag.cpp:240241`) *before*
invoking the drag, which matters because SWELL's implementation takes capture on its own hidden
window and spins a nested `SWELL_RunMessageLoop` until capture drops
(`swell-generic-gdk.cpp:35753584`, inside `SWELL_InitiateDragDropOfFileList` — the function
`drag_out_win.cpp:270` actually calls; the body is identical to the sibling
`SWELL_InitiateDragDrop` at `:35313560`, which is where an earlier draft of this citation
pointed) — with a 500 ms no-motion timeout that has no Windows analog.
**Severity: Minor** — the feature works; one safety property becomes conventional rather than
structural.
**Effort: S** — mostly documentation; there is no SWELL surface to restore the mask with.
**Direction.** Leave the implementation; make sure the copy-only invariant's home
(`drag_out_win.h:711`) is the doc a Linux reviewer is pointed at, and treat "MOVE is
structurally impossible" as a Windows-only claim in any future spec text.
### L2-11 — `normalizeSlashes` case-folds on `_WIN32` only, which is right for Linux and wrong for macOS
**Location:** `src/core/capture/capture_paths.cpp:1820`.
**Mechanism.** The one platform conditional in `core/`. Linux filesystems are case-sensitive, so
*not* folding is correct and the existing tests already assert it
(`tests/test_capture_paths.cpp:5051`). The shared-path note: macOS's default APFS/HFS+ is
case-**insensitive**, so the same `#ifdef _WIN32` under-folds there — a pre-existing macOS
defect this audit surfaces but does not own.
**Severity: Minor** (no Linux defect). **Effort: S** — confirmed: the one platform conditional
in `core/` is a single `#ifdef _WIN32` block (`capture_paths.cpp:1820`) with no other call
site depending on the token; a predicate swap is a one-block change.
**Direction.** No Linux action. If macOS is ever targeted, the predicate wants to be
"case-insensitive filesystem", not "Windows".
### L2-12 — `fs::path::string()` narrowing is strictly better on Linux (informational)
**Location:** `prune_fs.cpp:118`, `ingest.cpp:222,254`, `capture_paths.cpp:95`,
`panel_bank_ops.cpp:39`, `scope_resolve.cpp:207`, `insert.cpp:71`,
`capture_realtime_shell.cpp:306`, `capture.cpp:408`, `instrument_bake.cpp:166`.
**Mechanism.** On MSVC `std::filesystem::path::string()` narrows through the active code page;
on Linux `path` is already `char`-based, so `.string()` is a byte passthrough and UTF-8 survives.
The one site that deliberately works around the Windows behaviour —
`instrument_drop_win.cpp:123128`, using `u8string()` — is harmless on Linux (C++17, so
`u8string()` returns `std::string`; `CMakeLists.txt:28` pins `CMAKE_CXX_STANDARD 17`, and under
C++20 the `.c_str()` at `:128` would become a `const char8_t*` type error — worth knowing before
anyone bumps the standard).
**Severity: Minor / informational.** **Effort: none.** **Direction:** no action; do not "fix" it.
---
## Surfaces checked and found clean
Recorded so the sweep's negative results are as auditable as its findings.
- **Missing standard includes** (the MSVC-transitively-provides class). Ran a use-vs-include diff
across all 293 files for `<cstring> <cstdio> <memory> <atomic> <algorithm> <limits> <cmath>
<functional> <ctime> <cstdlib>`. Five raw hits; all five verified false positives on read —
four were the symbol name appearing in a *comment* (`render_settings.h:53`,
`ext_state_read.h:20`, `action_registry.h:7`) or a correct `<cmath>` `std::abs`
(`velocity_curve.cpp:229`, `<cmath>` at `:6`), and `processor_reload.cpp`'s `std::unique_ptr`
comes from `reasampler_processor.h:12`. **No missing include found — but this only covers the
ten headers above.** The two headers most likely to produce the classic
MSVC-transitively-provides failure under libstdc++, `<vector>` and `<string>`, were excluded
from that sweep; re-run including them: **45 files use `std::vector` without `#include
<vector>`, and 52 use `std::string` without `#include <string>`** (raw grep-diff counts,
unread). `<map>` and `<set>` add 2 and 3 more respectively. These 102 raw hits were **not**
individually verified the way the five above were (that would mean reading 102 files); the
claim this sweep actually supports is "up to 102 files may rely on transitive inclusion for
`<vector>`/`<string>`/`<map>`/`<set>`, unconfirmed one by one" — not "no missing include
found." The two header cases that matter most for the extension's own build
(`shell/capture/capture_orchestrator.h`, `src/ext_keys.h`) are confirmed satisfied
transitively.
- **Templates / two-phase lookup.** Exactly 7 templates in the tree
(`core/wire/bytes.h:25,61`, `core/wire/ext_state_read.h:37`,
`core/instrument/engine/play_params.h:191,203,208,218`). None derives from a dependent base,
none calls an unqualified dependent name, none needs `typename`/`template` disambiguation.
GCC/Clang-safe as written.
- **Compiler extensions.** Zero `#pragma` other than `#pragma once`; zero `__declspec`,
`__attribute__`, `__forceinline`, anonymous struct/union, or MSVC-permissive construct in
`src/**`.
- **`HWND__` forward declaration.** `drag_out_win.h:19` declares `struct HWND__;`; SWELL declares
`typedef struct HWND__ *HWND;` (`swell-types.h:211`) — same tag, no `-Wmismatched-tags`.
- **`preview_register_t` platform fork.** `panel_audition.cpp:3641,5863` and
`panel_state.h:2024` match the SDK's own fork exactly (`CRITICAL_SECTION cs` on `_WIN32`,
`pthread_mutex_t mutex` otherwise — `vendor/reaper-sdk/sdk/reaper_plugin.h:13081312`).
`<pthread.h>` is included on the non-Windows branch. Correct.
- **Prompts and message boxes.** Every user prompt goes through REAPER's own
`GetUserInputs`/`ShowMessageBox`/`ShowConsoleMsg` (`panel_bank_ops.cpp:2425,81,100,126,381`),
never a Win32 `MessageBox`. Cross-platform by construction.
- **Menus.** `CreatePopupMenu`/`InsertMenu`/`TrackPopupMenu(TPM_RETURNCMD)`/`DestroyMenu` are all
SWELL-provided (`swell-functions.h:528532`, and `TrackPopupMenu`/`DestroyMenu`/
`CreatePopupMenu` entries); the "pos < 0 appends" assumption at `panel_bank_ops.cpp:226` matches
SWELL's `SWELL_InsertMenu`. The comment at `:220222` is accurate.
- **Keyboard/accelerator path.** `accelerator_register_t` + `MSG`/`WM_KEYDOWN` + `GetFocus` +
`GetParent` (`panel_input.cpp:503521`) are all SWELL-provided; every `VK_*` used is in
`swell-types.h`.
- **Double-buffered paint.** `LICE_SysBitmap` + `getDC()` + `BitBlt(SRCCOPY)`
(`panel_render.cpp:474,549`) — `LICE_SysBitmap` has real non-Windows paths
(`lice.cpp:179`, `lice.h:362`), `BitBlt`/`SRCCOPY` are SWELL-provided.
- **Byte order.** Handled explicitly everywhere it matters (see §1.1). No native-integer
`memcpy` onto a wire buffer anywhere in `core/wire`.
- **Hot-path guardrails.** Nothing in this audit's remediation directions touches
`peaks::computeEnvelope` (still a free function), the audition call-through
(`panel_audition.cpp` — direct calls, no interface), or the realtime tick's single-pointer-test
idle path (`main.cpp:156`). L2-04's number-codec change is on the JSON/persist path, which root
`CLAUDE.md` explicitly declares off all hot paths. **No recommendation here adds a hot-path
indirection.**
---
## 3. Extension vs. instrument — the cost split
The two artifacts are cleanly separable, and the evidence says the split is very lopsided.
### 3.1 Extension only (`reaper_reasampler`)
**What must change in source:** two compile Blockers (L2-01, L2-02 — both one-line), one load
hazard (L2-03), one silent-failure diagnostic (L2-06), one correctness/safety fix (L2-05), one
data-integrity fix (L2-04), and cosmetics (L2-09). Nothing here is architectural. The panel's
whole SWELL/LICE surface — dialog lifecycle, docking, `WM_PAINT` double-buffered LICE draw,
mouse/wheel/capture, cursors, menus, keyboard accelerator, modifier keys, tooltips, drag-out,
drop-in — was checked call-by-call against the vendor headers and is **already SWELL-portable**;
see §1.5 and "Surfaces checked". This is the single most load-bearing finding of the audit: the
panel was written against SWELL's vocabulary throughout, and the Windows-only escapes are three
small ones (`DragAcceptFiles`, `SHFileOperationW`, OLE `DoDragDrop`) that each already carry a
non-Windows branch or a documented reason they do not.
**Estimate shape:** S+S+S+S+M+M+S. No L item.
### 3.2 Instrument additionally (`reasampler_vst`)
**What must be written from nothing:** an X11-embed `IPlugView` (window creation and parenting
without `RegisterClass`/`CreateWindowEx`), an `IRunLoop`/`ITimerHandler`-driven replacement for
the `SetTimer`/`WM_TIMER` sync poll, an event-driven input path replacing the entire `wndProc`
switch (~150 lines of `editor_platform.cpp:139296`), hover-leave detection without
`TrackMouseEvent`, modifier reads via `GetAsyncKeyState` instead of `GetKeyState`, and drop-accept
without `DragAcceptFiles`. The paint side is the cheapest part — every painter already draws into
a `LICE_IBitmap` through the shared kit (`editor_paint.cpp:28,51`), so the drawing survives a
window-system change intact; it is the *window and event plumbing* that is entirely absent. The
TCP/MCP embed strip (`reasampler_embed.cpp:135141`) is a smaller, separate 0→1
(`REAPER_FXEMBED_WM_IS_SUPPORTED` currently returns 0 off Windows; the paint body at `:174+` is
LICE and would port).
**Estimate shape:** one L, and it is a genuinely new competence rather than a port.
### 3.3 The consequence for sequencing
The extension is a Linux target that is largely *already met* and needs a handful of small,
well-localized fixes. The instrument is a separate project. The two share exactly one file —
`shell/panel/draw_kit` — and that file's only Linux blocker is L2-01. Daniel rules on whether the
instrument is in scope at all; the evidence says the extension does not wait on it.
---
## 4. Feature-degradation list — what builds but behaves differently, or not at all
Blunt column: **GONE** = the capability does not exist on Linux; **DIFFERENT** = it exists with
changed behaviour; **AT RISK** = depends on an unverified assumption.
| Feature | Verdict | What actually happens | Cite |
|---|---|---|---|
| Prune → Recycle Bin | **GONE** | Hard `unlink`, unrecoverable | `prune_fs.cpp:200208` |
| Prune's "file is locked" skip | **GONE** | `unlink` on an in-use file succeeds; the skip branch is dead code | `prune_fs.cpp:205` |
| Docked bank panel | **GONE (today)** | `SWELL_CreateDialog` returns null; toggle is a silent no-op until the resgen source is added (§7) | `panel_window.cpp:135137` |
| VST3 editor | **GONE** | `isPlatformTypeSupported` false for every type; host shows a generic UI | `editor_platform.cpp:3742` |
| VST3 generic-UI fallback | **GONE (today)** | Zero parameters registered as of this base; Phase Γ-W4-T1 changes this | grep `addParameter` over `shell/instrument/*.cpp` → no hits |
| TCP/MCP embed strip | **GONE** | `REAPER_FXEMBED_WM_IS_SUPPORTED` returns 0 | `reasampler_embed.cpp:135141` |
| Kit fonts (Segoe UI / Consolas) | **DIFFERENT** | fontconfig substitutes silently; metrics and ellipsis points shift; ValueMono may lose tabular alignment | `swell-gdi-lice.cpp:450487` |
| OS drag-out copy-only guarantee | **DIFFERENT** | No effect mask; copy-only is conventional not structural | `drag_out_win.cpp:257270` |
| OS drag-out readiness/outcome | **DIFFERENT** | Probe degrades to "non-empty"; return is always `true`; 500 ms no-motion timeout has no Windows analog | `drag_out_win.cpp:276278`, `swell-generic-gdk.cpp:35793580` |
| Panel file-drop ingest | **AT RISK** | Depends on SWELL delivering `WM_DROPFILES` without the Win32 opt-in | `panel_window.cpp:145150` |
| Bank index float round-trip | **AT RISK** | Unparseable under a non-C `LC_NUMERIC` | `json.cpp:3943,190196` |
| Extension load | **AT RISK** | Any one unresolved API name in ~869 = silent refusal | `main.cpp:292293` |
| Path case sensitivity | **DIFFERENT (correct)** | No case-fold; correct for Linux, and the tests already assert it | `capture_paths.cpp:1820` |
| Prune reclaim on a symlinked bank file | **AT RISK** | `fs::directory_iterator` + `is_regular_file()` follows symlinks (C++17); size is read from the target via `file_size()` but `fs::remove` deletes the link, not the target — prune reports N bytes reclaimed and reclaims zero. Symlinked media folders are far more idiomatic on Linux than Windows. | `prune_fs.cpp:113124` |
| Audition / preview | **INTACT** | `preview_register_t` fork matches the SDK; `PlayPreview`/`StopPreview` are REAPER API | `panel_audition.cpp:3663` |
| Docking, menus, cursors, keyboard, wheel, capture rollback, tooltips | **INTACT** | All SWELL-provided; verified call-by-call | §1.5 |
| Capture pillar (offline + realtime), persist, tracking, prune *computation* | **INTACT** | Pure `core/` + REAPER API only | §1.1 |
---
## 5. Open questions
### `[verify — Linux]` — answerable only on a Linux box
1. **Process locale.** Read `setlocale(LC_NUMERIC, nullptr)` inside a running REAPER-Linux
process (print via `ShowConsoleMsg`) on a machine whose user locale uses a decimal comma.
Decides whether L2-04 is urgent or latent.
2. **REAPER API completeness.** Instrument `main.cpp:292` to print
`REAPERAPI_LoadAPI`'s return value instead of discarding it, load once, and record the count.
Non-zero decides whether L2-03 is a real Blocker and names the gap.
3. **Panel file-drop routing.** With the panel docked, drag a WAV from the file manager onto it
and observe whether `dlgProc` sees `WM_DROPFILES` (L2-07). If not, add `WS_EX_ACCEPTFILES`.
4. **Which SWELL GDI/locale build REAPER ships.** Whether REAPER's `libSwell.so` is built with
`SWELL_SUPPORT_GTK` (→ `gtk_init_check`, `swell-generic-gdk.cpp:366`) or without
(→ `gdk_init_check`, `:368`) changes the likelihood in (1). Observable indirectly via (1).
5. **fontconfig substitution for "Consolas".** Whether it lands on a monospaced face on a stock
distro decides whether L2-09 is cosmetic or a real readability regression on numeric readouts.
6. **`SWELL_InitiateDragDropOfFileList` acceptance semantics.** Whether a GDK-initiated file drag
is accepted as a copy by common targets (a file manager, another DAW), and whether the 500 ms
no-motion timeout (`swell-generic-gdk.cpp:35793580`) cancels a slow user gesture.
7. **Prune against an in-use file.** Play an item from a bank file, prune it, confirm the audio
survives until the fd closes and the file is then unrecoverable — the concrete demonstration
behind L2-05(b).
### `[Daniel]` — scope decisions, not knowledge gaps
1. **Is the VST3 instrument in scope for Linux at all?** §3 supplies the cost split; the
extension does not depend on the answer. This is the phase's one real fork.
2. **Is a hard `unlink` an acceptable prune on Linux**, with a platform-aware confirmation
string — or must XDG trash be implemented before Linux ships? (L2-05.)
3. **Is silent font substitution acceptable**, or does the kit get an explicit Linux face list?
(L2-09.)
4. **Does "copy-only is structural" survive as a shipped invariant** when one platform can only
offer it conventionally? (L2-10.)
---
## 6. Ordering sketch
Dependency order only — this is not a plan, and it assigns no waves.
1. **Make it compile.** L2-01 (`FF_DONTCARE`), L2-02 (`GetCurrentProcessId`). Nothing else can
be observed until these land; both are one-line and independent of each other.
2. **Make it load, visibly.** L2-03 (`REAPERAPI_LoadAPI` diagnostic or `REAPERAPI_MINIMAL`) —
must precede any runtime verification, because it is the failure mode that produces no
evidence. Pairs naturally with `[verify — Linux]` (2).
3. **Make the panel appear.** L2-06 (the missing-dialog diagnostic) alongside T1's resgen wiring.
The diagnostic should land first so the resgen step can be confirmed rather than assumed.
4. **Then, and only then, verify.** `[verify — Linux]` items 1, 3, 5, 6, 7 all need a running
panel. Item 2 is already answered by step 2. **The critical path for this step runs through
the parallel build-system track, not this one:** "a running panel" means T1's resgen wiring
(§7 bullet 1) has landed — this doc doesn't own that work and doesn't know its schedule, so
step 3's "alongside T1's resgen wiring" is doing real scheduling work, not just sequencing
flavor. Anyone driving this ordering sketch needs to coordinate with T1 before step 4 can
start, not just after step 3 finishes on this track's own items.
5. **Data integrity.** L2-04 (locale-independent number codec) — pure `core/` work, unit-testable
on Windows, and it should land before any Linux user saves a project. Sequenced after the
verify only so its urgency is known; the *work* is not blocked.
6. **Deletion safety.** L2-05 (XDG trash or a platform-aware confirm) — gated on `[Daniel]` (2).
7. **Ingest opt-in, if needed.** L2-07 — no independent fix; it is the resgen work already
sequenced in step 3, strictly gated on `[verify — Linux]` (3) to confirm it's needed at all.
8. **Cosmetics.** L2-09 (fonts), L2-10 (drag-out doc). Independent of everything above.
9. **Separately, if ruled in.** L2-08 — the instrument's X11 editor. No dependency in either
direction on 18 except L2-01, which the shared `draw_kit` needs regardless.
---
## 7. Referred to T1 (build-system; spotted, not analyzed)
- **SWELL dialog resgen is not wired for Linux.** `src/app/CMakeLists.txt:97` — the
`target_sources(... resource.rc_mac_dlg.h)` line is commented out in the Linux `else()` branch
(and in the `APPLE` branch, `:86`). This is the mechanical cause of L2-06.
- **VST3 target is `if(WIN32 …)`-gated.** `src/shell/instrument/CMakeLists.txt:9` — the target is
not configured at all off Windows; `dllmain.cpp` is hard-coded at `:78` where Linux needs
`linuxmain.cpp` (`vendor/vst3sdk/public.sdk/source/main/linuxmain.cpp` exists).
- **`SHCreateStdEnumFmtEtc` / `SHFileOperationW` / `OleInitialize` need shell32/ole32.** Only on
the Windows branch, but worth confirming the Linux branch links none of them.
- **`reaper_plugin.h`'s relative SWELL include.** `vendor/reaper-sdk/sdk/reaper_plugin.h:49`
does `#include "../WDL/swell/swell.h"`, which does not exist under `vendor/reaper-sdk/`. It
resolves only because `${WDL_INC}` is `vendor/WDL/WDL` and `vendor/WDL/WDL/../WDL/swell/swell.h`
is the same file. Works, but it is a coincidence worth knowing before anyone moves an include
path.
- **`<filesystem>` link requirement.** GCC < 9 needs `-lstdc++fs`; `core/` and `shell/` both use
`std::filesystem` heavily.
- **LICE TU set.** `CMakeLists.txt:7982` adds `lice.cpp`, `lice_line.cpp`, `lice_arc.cpp`,
`lice_textnew.cpp` unconditionally. All four have non-Windows paths, but the Linux link needs
them compiled against `SWELL_PROVIDED_BY_APP` consistently with the module.
---
## Summary table
| ID | Finding | Severity | Effort | Artifact |
|-------|-----------------------------------------------------------------|----------|--------|--------------|
| L2-01 | `FF_DONTCARE` undefined off Windows (`draw_kit.cpp:73`) | Blocker | S | both |
| L2-02 | `GetCurrentProcessId()` unguarded, absent from SWELL | Blocker | S | extension |
| L2-03 | `REAPERAPI_LoadAPI` all-or-nothing over ~869 names, silent | Blocker `[verify]` | S | extension |
| L2-04 | Persisted floats are `LC_NUMERIC`-dependent, both directions | Major | M | both |
| L2-05 | Prune loses trash AND the locked-file backstop | Major | M | extension |
| L2-06 | Panel dialog never created; silent no-op | Major | S | extension |
| L2-07 | No drop-accept opt-in on SWELL; real seam is resgen, same as L2-06 | Major `[verify]` | — (see L2-06) | extension |
| L2-08 | No Linux VST3 editor; no parameters to fall back to | Major | L | instrument |
| L2-09 | Segoe UI / Consolas substitute silently via fontconfig | Minor | S | both |
| L2-10 | SWELL drag-out: no copy mask, no probe, no outcome | Minor | S | extension |
| L2-11 | Case-fold is `_WIN32`-only (right for Linux, wrong for macOS) | Minor | S | both |
| L2-12 | `fs::path::string()` narrowing — Linux is strictly better | Informational | — | both |
+773
View File
@@ -0,0 +1,773 @@
# Bank package — product notes
Framing, rationale, and design-direction calls behind **Phase Ε — bank export and
import as a single-file package**. The tickable spec lives in `docs/PLAN.md`
(§Phase Ε); the architecture detail will live in `src/core/package/CLAUDE.md` and
`src/shell/package/CLAUDE.md` once those directories exist. This doc holds the
*why* — the user problem, the container choice, the version-compatibility policy
and the reasoning that produced it, the failure-mode table, and what a package
deliberately does not carry.
Status: framed by product-designer (2026-08-02); **all three [Daniel]-class forks
RULED the same day** — Ε-F1 **proprietary container** (`RSBK`), Ε-F2 **import always
lands as a new bank**, with an automatic suffix on a name collision, Ε-F3 **refuse an
import while the tracking ledger is degraded**. See §"Rulings" for the index and the
recorded rationale; each is specified in place in the section that owns it. Nothing in
this doc is open. Everything else below is a product-designer call with its reasoning
stated; contradict it in review with an argument, not a preference.
---
## What it is (and what it is not)
**A bank package is one file that carries one bank — its audio and its index —
out of a project and into another.** Today a bank is per-project by construction:
the audio sits in `<projectDir>/reasampler_bank/` (`core/capture/capture_paths.h`'s
`kBankSubfolder`) and the index that gives that audio meaning lives in the `.rpp`'s
project ext state under the `"reasampler"` namespace (`src/ext_keys.h`'s
`kProjExtBanksKey`). The two travel together with the project and nowhere else.
Export writes both halves into a single `.rsbank` file; import lands them into
another project's bank folder and index.
**It is not a project-transfer feature.** REAPER already moves projects — *Save
project as… with copy of media*, track templates, subprojects. None of them can
carry a ReaSampler bank, because none of them knows the ext-state index exists;
copy the `reasampler_bank/` folder by hand into another project and you get a pile
of `.wav` files with no names, no loop points, no root notes, no tempo stamps, no
tiers, and no lineage. The package exists precisely because **the metadata is the
part that cannot be moved by hand.**
**It is not a preset.** A package carries audio plus bank metadata. It does not
carry ReaSampler 9000's dialed sound — filter, envelopes, splines, loop crossfade,
rate, pitch. That is the instrument's `ComponentState`, and a user who wants the
dialed sound in another project bakes it first (Phase Ξ's resample) and exports the
resulting capture. The package is a *bank*, and the bank has always been the audio,
not the instrument. See "What a package deliberately does not carry" below — this
is the most likely user expectation mismatch in the whole feature, so it is headed
off here rather than discovered in a support thread.
**It is not a re-encode.** Sample bytes leave the source project and arrive at the
destination byte-identical. Frame count, sample rate, bit depth, channel count are
untouched; no trim, no normalize, no mono collapse, no format conversion, no
compression of the audio payload. The package payload is **opaque bytes** to
everything in the export/import path except a hash function. This is the phase's
trust anchor, and it is the direct analogue of the capture pillar's null test.
---
## Why a single file, not a folder copy
The obvious cheap alternative is "copy the bank folder, and write the index into a
sidecar JSON beside it." Rejected, for four reasons, in descending order of weight:
1. **A folder has no place to put its own manifest that a user cannot lose.** The
index is the part that makes the audio a bank. In a folder, the manifest is just
one more file among two hundred `.wav`s — droppable, renamable, editable into
inconsistency, and silently absent after a partial copy. In a single file it is
the header, and the file either has one or is not a package.
2. **Integrity and version tagging need one identity.** "Is this package complete,
and can this build read it?" is answerable in one read of one file's first few
kilobytes. A folder answers it only after enumerating and stat-ing every entry,
and answers "was anything edited since export?" not at all.
3. **The move gesture is one object.** Email it, drop it in shared storage, drop it
on the docked panel. The panel already accepts `WM_DROPFILES` for ingest
(`src/shell/panel/panel_window.cpp` header comment: "WM_DROPFILES -> ingest"), so
a package can ride an affordance that exists.
4. **Atomicity is buyable.** A single file can be written to a temp path and
atomically renamed on success — the precedent the mono collapse already set
(Ψ-W2-T2 landed the collapse "via temp file plus atomic rename"). A half-written
folder looks exactly like a complete one.
The counter-argument for the folder is real and should be recorded: a folder is
inspectable with no tooling. The container ruling below does **not** buy that back —
`RSBK` is opaque without our tool — so the inspectability loss is an accepted cost,
paid deliberately, not an oversight to be corrected later by reaching for ZIP.
---
## The container — a proprietary `RSBK` (Ε-F1, RULED)
**Ruled by Daniel, 2026-08-02: *"proprietary container."*** The package is a
hand-rolled `RSBK` file. ZIP — whether via the vendored MiniZip64 in
`vendor/WDL/WDL/zlib/` or as a hand-written stored-only ZIP *shape* — is rejected and
is not to be revisited inside this phase.
**The shape.** Magic `RSBK`, a fixed little-endian header carrying the two version
fields (§"Version tagging" below), a length-prefixed JSON manifest, then each entry's
payload concatenated in manifest order. Framing overhead is tens of bytes, not
kilobytes.
**What it reuses, rather than invents.** The little-endian byte codec
(`core/wire/bytes.h``putLE` / `ByteReader`, called out in `src/core/wire/CLAUDE.md`
as the earned template case) and the hand-rolled JSON layer (`core/json`). Both are
already owned and already tested here.
**Why the ruling went this way.** The load-bearing reason is not effort — it is that
the pure/shell split is this project's central discipline, and `RSBK` is the only
candidate where the **whole codec lands pure** and the shell is a bytes-in/bytes-out
skin. MiniZip's API is path-and-file-handle shaped (`ioapi.h`), so a ZIP codec drags
the filesystem into the layer that discipline keeps free of hosts; a buffer-backed
`zlib_filefunc_def` is possible but fiddly and defeats the "standard format" argument
inside the code even while preserving it on disk. Compression buys almost nothing on
float32 PCM. Writing a correct ZIP central directory by hand was the worst of both —
more code than `RSBK`, the same hardening burden, plus Zip64 and name-encoding edge
cases, and still no compression.
**The two costs, accepted with the ruling.** (1) The package is **opaque without our
tool** — no unzip-and-look support path. (2) We own the hostile-input hardening of our
own parser, to the discipline `bank_model::deserialize` and `parseLedger` already
carry — *error signaled, never UB* (`bank_model.h`'s `BankModel::deserialize`). Both are priced in; a
later "let's make it inspectable" impulse is a new phase's argument, not this one's.
**This was a one-way door and it is now shut** — packages are in users' hands the day
it ships, and a later container change means either a second reader forever or
stranded packages. The version ladder below, not a format swap, is how the format
moves from here.
---
## Version tagging: two questions, and why one number cannot answer both
### The precedent this extends (read from source, 2026-08-02)
The repo already carries **two** versioning mechanisms, and they answer different
questions:
1. **A blob-schema ladder.** `src/core/tracking/origin_ledger.cpp`'s version-ladder
header comment states the
ladder for the `owned_files` blob (v1 legacy path-only, v2
current), pins `constexpr int kLedgerVersion = 2`, and — the load-bearing part —
**reads and validates `"v"`, not merely writes it**: "A version above
`kLedgerVersion` is therefore its own degraded status, never a Loaded ledger"
(the same comment). The parse outcome is a three-way `Ok` / `Malformed` / `FutureVersion`
(`origin_ledger.cpp`'s `ParseOutcome` enum and `parseStored`), deliberately distinguished so the operator gets the right
recovery advice. A *field-vocabulary* gap behaves oppositely: an unrecognized
`OriginKind` integer degrades to `Unknown` rather than failing the parse
(`origin_ledger.cpp`'s `kindFromInt`), because "a vocabulary gap must not halt the prune"
(`src/core/tracking/CLAUDE.md` §"Gotchas").
2. **An app writing-version stamp.** `src/core/version/app_version.h`'s
`WritingVersion` with `PreVersioning` / `Unknown` / `Stamped`, classified by
`classifyWritingVersion`, stamped into project ext state by
`ReaSamplerSession::saveToActiveProject` (`src/shell/persist/ext_state_io.cpp`) using `stampVersion()` (the numeric
triple only, no channel suffix). It is informational: an absent stamp is "not an
error and not a warning" (`app_version.h`'s `WritingVersion` comment, the `PreVersioning` case).
**An observation worth recording, not a defect to fix here:** `BankBook` writes
`"version": 1` into the banks blob (`src/core/model/bank_book_json.cpp`'s `BankBook::serialize`) but its
parser skips the key along with every other unknown one
(`bank_book_json.cpp`'s `parseBook``if (!r.skipValue()) return false; // version, or unknown`).
The book's version field is therefore **decorative today** — written, never read,
never gating. The ledger's is the precedent to extend; the book's is the precedent
not to repeat.
### The two questions a package must answer
- **"Can I parse this shape at all?"** — a hard gate. Monotonic integer. This is
`origin_ledger`'s `"v"`.
- **"Who wrote this, so I can tell the user what to open it with?"** — informational,
never a gate. Semver string. This is `app_version`'s stamp.
A package carries **both**, and conflating them is the mistake to avoid. The stamp
alone cannot gate (semver ordering does not track schema shape; a patch release can
change a blob and a minor release can leave it alone). The ladder alone cannot
advise (an integer tells a user nothing about which build to install).
### The refinement: `formatVersion` **and** `minReaderVersion`
A single ladder has one bad property: **every change strands every older reader,
even a purely additive one.** That is not hypothetical here — look at what `Sample`
has actually accumulated: `rootNote` and `loop` (`bank_model.h`'s `Sample::rootNote` / `Sample::loop`,
"additive like `provenance`. Both default cleanly empty"), `captureTimeSigNum` /
`captureTimeSigDenom` (`Sample::captureTimeSigNum` / `Sample::captureTimeSigDenom`, "0/0 means UNSTAMPED"), `channelCount`
(`Sample::channelCount`, "0 = unknown — a pre-field entry"). Every one of those was additive with
a defined absent-value. Under a single ladder, each would have blocked older readers
for no reason.
So the package header carries two integers:
- **`formatVersion`** — what this writer emitted. Monotonic, bumped on any change.
- **`minReaderVersion`** — the oldest reader that can read this package *safely*.
Bumped only when a change is **structural** (a field's meaning changes, a section
is removed, framing changes); left alone when a change is **additive** (a new
optional manifest key, a new `Sample` field with a defined absent-value — exactly
the four listed above).
The reader's rule is one line: **read it iff
`minReaderVersion <= kPackageFormatVersion`.** `formatVersion` is then only for the
message text and the log.
**One change class that looks additive and is not: a new enum value.**
`BankModel::deserialize` *rejects* an out-of-range `SourceMode` or `Tier` rather than
degrading it (`bank_model.cpp`'s `parseSample` — the `sourceMode` and `tier` branches), and every enum a package carries
rides inside the nested `BankModel` blob. So growing either vocabulary is
**structural** and bumps `minReaderVersion` too. This is wider than packages and
predates them: `BankModel::deserialize` is also the live project ext-state parser
(`bank_book_json.cpp`'s `parseBank`), so appending a `SourceMode` value already strands an older
build opening a newer project's `.rpp`. Phase Ε inherits that property; it did not
cause it, and changing it — degrade-to-`Unknown` at those two sites, the way
`BakeStatus` already does — is a change to the model layer, not a package concern. It
leaves the argument above untouched: the four fields that motivated the two-integer
design are *fields*, and `parseSample`'s `skipValue()` fallback
(`bank_model.cpp`), plus the manifest parsers' equivalent at each level, still
carries them forward.
This is a borrowed pattern, not an invention: Matroska's `EBMLVersion` /
`EBMLReadVersion` pair, PDF's catalog `/Version` over the header version, and OOXML's
`mc:Ignorable` markup-compatibility mechanism all separate "what I am" from "what you
must understand to read me." It costs one extra integer and one writer discipline —
*decide honestly whether your change is additive* — and that discipline is exactly
the one `origin_ledger` already enforces on `OriginKind`
(`src/core/tracking/CLAUDE.md` §"Gotchas": "PERSISTED INTEGERS — never renumber, only
append").
### Both directions, concretely
**Direction 1 — newer ReaSampler, older package. Always imports. Never refuses.**
Every reader reads every `minReaderVersion <= kPackageFormatVersion`. Absent manifest
keys take their defined defaults, exactly as `Sample`'s additive fields already do,
and exactly as `origin_ledger` lifts a v1 path-only blob into v2 records with kind
`Unknown` and empty ids (`origin_ledger.cpp`'s version-ladder header comment). Unrecognized manifest keys are
skipped, which is already how every parser in this repo behaves
(`bank_book_json.cpp`'s `parseBook`). Unrecognized enum integers (the manifest's own —
`BankModel`'s nested ones reject) degrade to their defined `Unknown`-equivalent,
never to the numeric default and never to a parse failure —
`bake_wire`'s rule verbatim (`src/core/wire/CLAUDE.md` §"Modules", the `bake_wire` bullet: "an unrecognized value
decodes as `Failed` rather than as the numeric default `Ok`").
**The user sees:** a normal import summary. Optionally a single console line naming
the older writer version. No dialog, no warning, no ceremony — a supported case is
not an incident.
**Direction 2 — older ReaSampler, newer package. Refuses. Whole-package, nothing
written.** `minReaderVersion > kPackageFormatVersion` is a hard stop, before a single
byte is written to the bank folder and before the index is touched. This is exactly
`LedgerStatus::FutureVersion`'s treatment, and for the same reason stated at
`origin_ledger.cpp`'s version-ladder header comment: parsing an unknown shape by old rules "would yield a
plausible-but-partial" result, and a partial bank is worse than no bank.
**The user sees** a message box (`ShowMessageBox`, verified —
`vendor/reaper-sdk/sdk/reaper_plugin_functions.h:6546`,
`int (*ShowMessageBox)(const char* msg, const char* title, int type)`) naming three
things, because any two of them leave the user stuck:
> **Cannot import this bank package.**
> It was written by ReaSampler 1.7.0 and needs package format 3 or newer.
> This build (1.5.2) reads package format 2.
> Nothing was imported. Install ReaSampler 1.7.0 or newer and try again.
The writer's semver is what makes the message *actionable* — "format 3" alone tells a
user nothing they can act on. That is the whole reason both fields exist.
**Refusing is the correct direction to refuse in**, and it is worth saying why
rather than leaving it as taste: the destination project is the user's existing work.
A refusal costs a transfer the user can retry after updating. A best-effort partial
import costs silent data absence inside a project they will keep working in, and they
will not find out which twelve of forty samples were dropped until they need one.
---
## What a package carries
- **The two version fields and the writer's semver**, in the fixed header.
- **An export timestamp** and the **source bank's display name** — informational, and
the default the import prompt pre-fills.
- **One manifest entry per sample**, carrying that `Sample` record in
**`bank_model`'s own serialization, nested verbatim**. This is the
`bank_book_json` precedent applied outward: the book writer "emits the bank
envelope … plus a raw `index` member whose value is the `BankModel` blob verbatim,
so per-bank sample serialization stays owned by `bank_model` and is not duplicated
here" (`bank_book_json.cpp`'s file-header comment). The package does the same, so a future `Sample`
field reaches packages for free and the shape has exactly one owner.
- **Per entry, additionally:** the payload's **bare file name** inside the package,
its byte length, and a whole-file `hashBytes` digest
(`core/capture/wav_codec.h`'s `hashBytes` — FNV-1a 64-bit over raw bytes, 16-char lowercase
hex). Note carefully: `hashBytes`, **not** `hashWavContent`. The latter deliberately
skips non-`fmt `/`data` chunks (`wav_codec.h`'s `hashWavContent`), which is right for dedup
identity and wrong for "did these bytes survive the trip." Both hashes are already
in the codebase; the package needs the raw one for integrity and carries the
`Sample`'s existing `contentHash` for dedup, and they are different fields
answering different questions.
- **The bank's slot map** — display positions (`core/model/slot_map`), already JSON
round-trippable. A bank's arrangement is part of what the user built.
- **The payloads**, byte-exact, in manifest order.
`hashBytes` is FNV-1a — a corruption detector, not a cryptographic checksum. Say so
plainly in the code and in any user-facing wording: it catches truncation, bit rot,
and a mangled transfer. It does not certify provenance, and it is not a defense
against a package deliberately crafted to collide. That is the right level of
guarantee for this feature; overselling it would be the error.
## What a package deliberately does NOT carry
- **Any absolute path. Any path at all.** Entries are **bare file names** — no
directory component, no `..`, no drive letter, no leading separator — validated on
encode *and* on decode. The importer spells the destination path itself, through
the same `capture_paths` arithmetic every capture already uses. This makes the
relative-paths-only precision invariant **structural rather than remembered**:
there is no field in the format capable of expressing an absolute path. It also
closes the archive-traversal ("zip slip") bug class by construction, which is the
one genuinely security-shaped surface this feature has.
- **The origin ledger.** The ledger is *this project's* record of files *it*
created, and it is the authority prune's protected set is computed from
(`src/core/tracking/CLAUDE.md` §"Scope"). Importing foreign ownership records would
assert this project's authority over another project's history. Instead the
importer writes **its own** birth records for the files it lands, at the moment it
lands them, through the one writer (`ReaSamplerSession::recordCreated`,
`src/shell/persist/session.h` — it already takes an `OriginKind`). Without that,
every imported file would be "foreign, therefore never reclaimed"
(`core/tracking/CLAUDE.md` §"Invariants", the "No silent gaps" bullet) and a user's bank folder would grow forever.
- **Live-instance usage records** (`rsusage_*`, `src/ext_keys.h`'s `kProjExtUsageKeyPrefix`). Per-instance
runtime state of a specific project's specific FX instances. Meaningless elsewhere.
- **Project state that is not bank state:** which bank was active, the Design View
mode model (`view_state`), the tail setting, the project GUID, the bank-generation
counter. A package is a bank, not a project.
- **ReaSampler 9000's `ComponentState`.** Stated above; restated here because it is
the expectation most likely to be wrong. The seam is left open, not closed: the
manifest skips unknown keys, so a future `instrumentState` section is a purely
additive change that does not bump `minReaderVersion`. Designing that seam now and
spending it later is the point.
---
## Identity and collision on import
**The import target is settled first, because it frames all four collisions.
Ε-F2, RULED by Daniel, 2026-08-02: *"always lands as a new bank, with an auto suffix
if name collision."*** Every import creates a **new bank** in the destination book.
It never merges into an existing bank, never lands into the pool, never offers a
target picker, and never overwrites. **Merge-into-existing is out of scope for Phase
Ε** — not deferred behind a flag, not a second action shipped later in this phase, not
a checkbox. A user who wants imported samples in an existing bank imports and then
uses the existing move/copy verbs, which already do exactly that and already carry
their own undo.
Four distinct collisions hide under the word "collision," and they need four
different answers.
1. **Sample id.** Ids are minted as `"cap-" + uniqueTag + "-" + fileName`
(`src/shell/capture/capture.cpp`'s `OfflineRenderBackend::capture`) and `"imp-" + …`
(`src/shell/actions/ingest.cpp`'s `importFileIntoActiveBank`) — unique within a project, **not** globally.
Re-importing a package into the project it came from would collide.
**Answer: remint every sample id on import**, under its own prefix, and remap
`Provenance::parentSampleId` (`bank_model.h`'s `Provenance` struct) through the same map — to the
reminted parent if that parent came in the same package, cleared otherwise. A
foreign id never enters the destination index. This also makes "import the same
package twice" a clean, duplicative, correct operation rather than an undefined
one.
2. **File name in the destination bank folder.** **Never overwrite.** Overwriting
would destroy an existing capture, and only prune touches existing bank bytes.
Mint a fresh unique name through the existing `deriveBankPaths` +
unique-tag machinery (`core/capture/capture_paths.h`'s `deriveBankPaths`), automatically, no
prompt, and report the count in the summary.
3. **Content hash.** `BankModel::add` collapses an equal-`contentHash` add onto the
existing entry (`bank_model.h`'s `AddResult::Collapsed`). Desirable — but
if the file was already written to disk before the collapse, it becomes an
instant orphan. **Answer: check the destination bank's `findByHash` BEFORE writing
the payload**; on a hit, skip the write entirely and report "N already present."
This is the one place the import must consult the model before touching the
filesystem, and it is a concrete acceptance criterion rather than an optimization.
4. **Bank display name.** `bank_book` enforces unique display names, trimmed and
case-insensitive ASCII (`src/core/model/CLAUDE.md` §"Invariants", the "Bank identity, movement, dedup" bullet; `createBank`'s own
contract at `bank_book.h` — *"Drums"/"drums"/" Drums " collide, including
against the pool's "Pool"*), so `createBank("Drums")` into a project that already
has "Drums" returns `false` with no mutation. **Answer: an automatic numeric
suffix, specified below.** No prompt, no overwrite, no refusal.
### The auto-suffix rule (Ε-F2, implementation-binding)
The importer picks the destination bank's display name itself. The user is told what
it picked; the user is never asked.
**The seed.** The seed is the package's recorded source bank display name, taken
**verbatim**. If that name is absent, empty, or whitespace-only after the model's own
trim, the seed is the literal `Imported bank`.
**The probe.** Let `seed` be that string and `fold(x)` be `BankBook`'s own uniqueness
key — strip leading/trailing ASCII whitespace, lower-case ASCII letters
(`bank_book.h`'s `BankBook::nameKey`). Take the **first** name in this sequence whose fold is not
already carried by a bank in the destination book:
seed, seed + " 2", seed + " 3", seed + " 4", …
ascending from 2, unbounded. So `"Drums"` into a project already holding `"drums"`
lands as `"Drums 2"`; a third copy lands as `"Drums 3"`.
**Four properties that make this unambiguous, each stated because omitting it lets two
implementations diverge:**
1. **The seed is never re-parsed.** A package named `"Drums 2"` colliding in the
destination lands as `"Drums 2 2"`, **not** `"Drums 3"`. This is deliberate and is
not a defect to fix: a trailing integer cannot be distinguished from a user's own
name (`"Kit 808"` would become `"Kit 2"` under a stripping rule, silently losing
user-authored text). `resample_name::nextIterationName` may increment its tail only
because ` r<N>` carries a marker; a bare integer carries none. Appending is the
safe direction — it never mutates text the user wrote.
2. **The probe fills gaps.** With `"Drums"` and `"Drums 3"` present and `"Drums 2"`
free, the import lands as `"Drums 2"`. First-free-ascending, not
highest-plus-one — the rule is a pure function of the destination's current name
set, so the same package into the same project always produces the same name.
3. **The suffix is derived from the destination, never from the package.** The package
records only its source name. Nothing about a collision is stored in the package,
and re-importing the same package into a different project can produce a different
name. The probe terminates: with `B` banks in the destination, one of the first
`B + 1` candidates is free by pigeonhole, so no cap is needed and none should be
added.
4. **The fold has exactly one home.** `import_plan` must **not** re-implement
`nameKey``bank_book.h`'s `BankBook::nameKey` says in as many words that a drifted second copy
would let the uniqueness invariant be violated. The probe therefore runs behind
`BankBook`'s own folding, which means Ε-W2-T2 adds **one additive public `const`
member** to `BankBook` (recommended: `std::string uniqueDisplayName(const
std::string& seed) const`, returning the first free candidate) and calls it. That
one member is the only edit any Ε track makes to `core/model/`.
**What the suffix does NOT touch.** It renames nothing but the new bank's display
name. Sample ids are reminted by collision rule 1 regardless of whether a name
collision occurred, and the two mechanisms are independent. **`Sample` display names
are never suffixed** — two banks may legitimately hold a sample called `"Kick"`, and
`resample_name`'s own contract already states that sample display names are not unique
(`resample_name.h`'s `nextIterationName`). Bank-folder file names are handled by collision rule 2 and
are unaffected by the bank's name. `slot_map` positions ride along unchanged.
**The pool case is guaranteed, not hypothetical.** Exporting the pool is in scope (the
pool is structurally a bank), and the destination's pool always exists and always
carries the protected name `"Pool"`. So a pool export imported anywhere lands as a
**named** bank called `"Pool 2"`. That is correct under the Ε-F2 ruling — import never
lands into the pool — and it should read as intended behaviour in the summary, not as
a glitch.
**What the user sees, and their recovery.** The import summary names the bank it
created, and says so plainly when the name was adjusted:
> Imported 42 samples into a new bank: **Drums 2** (a bank named "Drums" already
> exists in this project).
The recovery path is the existing rename verb — one Ctrl-Z undoes the whole import
including the bank creation, and a rename is one gesture if the user wants a different
name. Neither needs a new affordance.
---
## Failure modes and what the user sees
Whole-package, all-or-nothing on both sides. The reasoning is the same one prune
settled on: report before acting, and never leave a half-state that looks whole.
| Failure | Side | Behaviour | What the user sees |
|---|---|---|---|
| An indexed file is missing on disk | export | Refuse by default; offer "export the N present entries" only behind an explicit confirm that lists what is missing | Message box naming the missing entries; nothing written unless confirmed |
| An indexed file is unreadable (locked/permission) | export | Same as missing | Same, distinguishing unreadable from absent |
| Destination package file exists | export | Platform save dialog's own overwrite confirm | Native dialog |
| Write fails partway | export | Temp file in the destination directory, atomic rename only on complete success | Console error; no `.rsbank` left behind. A truncated package must never exist |
| `minReaderVersion` above this build | import | Refuse whole. Nothing written, index untouched | The three-part message box above (package needs / this build reads / what to install) |
| Malformed or truncated container | import | Refuse whole. Reported **distinctly from** the version case | "This file is not a readable bank package (corrupt or truncated)." The distinction matters: the two have opposite recoveries — one is "install a newer build," the other is "get an intact copy." `origin_ledger.cpp`'s `parseStored` makes exactly this distinction for exactly this reason |
| Entry name contains a path separator, `..`, or is absolute | import | Refuse whole, before any write | "This package is not well-formed." Hostile input, not user error — no need to elaborate |
| Payload hash mismatch on any entry | import | Refuse whole, before landing anything | "This bank package is damaged (entry `<name>` failed its integrity check). Nothing was imported." |
| A write fails mid-import (disk full, permission) | import | Roll back: delete the files **this import wrote** and abandon the index mutation | "Import failed and was rolled back. Nothing was added." |
| Bank name collides in the destination | import | Auto-suffix, no prompt, no overwrite — first free of `seed`, `seed 2`, `seed 3`, … | Summary names the bank it created and says the name was adjusted |
| File name collides in the bank folder | import | Auto-rename, no prompt | Counted in the summary line only |
| Sample already present by content hash | import | Skip the write, collapse onto the existing entry | Counted in the summary line ("N already present") |
| Tracking ledger degraded at import time | import | **Refuse whole**, before the picker's bytes are read and before any write — the guard runs first | The two-case message below, mirroring prune's abort |
**On the rollback, and why it is not an invariant breach.** Prune is the single
exclusive file-deletion authority, with exactly one carve-out, stated in one place —
`src/shell/persist/prune_fs.cpp`'s file-header comment: "a shell removing a file it wrote itself
moments earlier and that no index ever referenced is self-cleanup, not authority
over user data … the discriminator is 'did this call create it, and did anything ever
reference it', not where it sits." An import rollback fits that discriminator
exactly: the files were written by this call, and the index mutation is abandoned, so
nothing ever referenced them. The spec must **cite** the carve-out rather than
restate it, or a reviewer will correctly read the rollback as a breach.
**On undo.** The index side of an import is one Ctrl-Z, through the same
`persistBankOp` undo batching every bank verb already uses
(`src/shell/bank_ops/CLAUDE.md` §"Invariants", the "One bank operation is one Ctrl-Z" bullet; `Undo_BeginBlock2` / `Undo_EndBlock2` verified
at `reaper_plugin_functions.h:7758` and `:7806`). **Undo does not un-write the
files** — they remain on disk, referenced by no index, until a prune reclaims them.
That is the same designed orphaned-until-prune window a non-empty bank delete already
produces (`src/core/model/CLAUDE.md` §"Invariants", the "Bank identity, movement, dedup" bullet). Say it out loud in the spec; do not let
a user infer that Ctrl-Z cleans the folder.
### Import under a degraded tracking ledger (Ε-F3, RULED: refuse)
**Ruled by Daniel, 2026-08-02: *"refuse mismatched import."*** An import that cannot be
cleanly reconciled against the tracking ledger is **refused outright**. There is no
confirm-and-proceed path, no "I understand the risk" checkbox, and no preference to
turn the guard off. This ruling went against the framing recommendation, and the
reasoning that carried it is recorded below rather than re-argued.
**The trigger, exactly.** The guard fires when `tracking::ledgerDegraded(status)` holds
for the project's loaded ledger status — that is, `LedgerStatus::Unreadable` or
`LedgerStatus::FutureVersion` (`src/core/tracking/origin_ledger.h`'s `LedgerStatus` and `ledgerDegraded`).
`Fresh` (absent key — a legitimate new project) and `Loaded` both proceed normally.
**Two things the guard is deliberately NOT keyed on:**
- **Not `PruneReport::blockedByTracking`.** That flag also fires on unreadable
`rsusage_*` keys, which are about live-instance protection during a *deletion*.
Import deletes nothing and computes no protected set; it *writes* birth records. An
undecodable usage key must not block an import, and reusing prune's composite flag
would silently make it do so.
- **Not the package.** Nothing in the `.rsbank` participates in this check. The package
is untouched by a refusal and remains importable later, elsewhere, or after the
project is repaired.
**When it runs.** First — **before the file picker opens**, before a byte of the
package is read, before any allocation. Making the user find and pick a file we have
already decided to refuse is the wrong order.
**What the user sees.** A console block through `ShowConsoleMsg`, mirroring prune's
abort (`src/shell/actions/prune_action.cpp`'s `doBankPruneFolder` — the `blockedByTracking` console block) in structure and in tone, because a
user who has hit prune's block should recognise this one. Every recovery line names
**this build's** ext-state namespace via `version::extStateNamespace()` — the
beta/stable trap prune already documents, where a beta user handed the stable spelling
clears the wrong key and is still blocked. Two cases, exactly one of which fires:
*Malformed ledger:*
> ReaSampler import: ABORTED — the file-tracking ledger could not be read. Nothing was
> imported.
> The stored file-tracking ledger is malformed. It has been left intact rather than
> overwritten, so it can be repaired or cleared:
> `reaper.SetProjExtState(0, "reasampler", "owned_files", "")`
> Clearing it makes every existing bank file un-reclaimable (they stop being
> attributable to ReaSampler); no file is lost. Reopen the project afterwards — the
> block is held for the rest of this session.
> An import can land hundreds of files in one gesture. With no readable ledger, none of
> them could be given a birth record, and every one would be permanently unreclaimable.
*Ledger from a newer build:*
> ReaSampler import: ABORTED — the file-tracking ledger could not be read. Nothing was
> imported.
> The stored file-tracking ledger was written by a NEWER version of ReaSampler than
> this one, so its records cannot be read safely. It has been left intact and will NOT
> be overwritten. Reopen the project with that newer version — do NOT clear this key
> from here, that would discard tracking records this build cannot see. The block is
> held for the rest of this session.
> An import can land hundreds of files in one gesture. With no readable ledger, none of
> them could be given a birth record, and every one would be permanently unreclaimable.
**The recovery path.** The status is written only by `loadFromProject`, so it is sticky
for the session (`src/shell/persist/CLAUDE.md` §"Invariants", the "A ledger this build cannot read is degraded" bullet): repair or clear the key
(malformed case only), or install the newer build (future-version case), **reopen the
project**, then import again. The package needs no re-export, and nothing about the
destination project was changed by the refusal.
**Export is NOT gated on the ledger, and that asymmetry is intentional.** Export writes
no birth records, mutates nothing, and touches no ext state. A user whose ledger is
degraded can still get their bank *out* — which is exactly the moment they are most
likely to want to. Only the landing side refuses.
**Why the ruling went this way.** The rejected option — allow the import behind an
up-front confirm — matched the accepted residual already stated at
`core/tracking/CLAUDE.md` §"Invariants" (the "No silent gaps" bullet), where a capture made during a degraded session is
recorded in memory but not persisted and degrades to foreign. The argument that carried
is **scale**: that residual contemplates *one* untracked capture, and a bulk import can
strand two hundred files in a single gesture. Same mechanism, different animal. A
confirm would also push a data-lifecycle consequence onto the user at the one moment
they are least equipped to evaluate it — mid-transfer, wanting the samples. The refusal
costs a retry after a project reload; the confirm costs a bank folder that can never be
reclaimed.
---
## Memory: the streaming seam that keeps the codec pure
A bank is not small. Float32 stereo at 48 kHz is ~23 MB per minute; a two-hundred-
sample bank is plausibly gigabytes. **The naive shape — a pure
`encodePackage(vector<uint8_t>) -> vector<uint8_t>` — holds the whole bank twice in
RAM and is unshippable.** The temptation is then to move the codec into the shell so
it can stream. That is the wrong correction, and the right one is a better seam:
- **Pure owns framing and arithmetic.** `encodeHeader(manifest) -> bytes` and
`entryLayout(manifest) -> [{ name, offset, length }]` on the write side;
`decodeHeader(prefix bytes) -> manifest + entry layout` on the read side. Offsets
and lengths are arithmetic — perfectly pure, perfectly testable, and the exact
place an off-by-one becomes a corrupt package.
- **Shell owns the stream.** It writes the header, then appends payloads one at a
time, reading each source file into a buffer, hashing it, writing it, and releasing
it. On decode it reads the prefix, gets the layout, then seeks and streams each
payload independently.
**Constraint, stated as an acceptance criterion:** the export and import paths hold
**at most one entry's payload** in memory at a time. This is what keeps the codec
pure without making the feature fail on real banks, and it is the kind of thing that
is cheap to design in and expensive to retrofit.
**One honest cost.** Export and import are synchronous, on the UI thread, like every
other action in the tool, and prune sets that precedent (a scan-then-confirm gesture
that blocks). A multi-gigabyte bank will therefore freeze REAPER for seconds. The
recommendation is to ship synchronous with a console progress/summary line and treat
async as a later move if it bites — but this is a real `[propose]`-class call the
implementation review should make deliberately rather than by default.
---
## Where it lives (pure / shell)
Two new directories, following the split the whole repo turns on.
**`src/core/package/` — pure, REAPER-free, unit-tested without a DAW.**
- `package_format` — the container framing and the version ladder in one place:
the magic, the header layout, `kPackageFormatVersion`, `kPackageMinReaderVersion`,
and `classifyPackageVersion(formatVersion, minReader) -> Readable | TooNew |
Malformed`. The ladder lives with the framing because the ladder *is* the framing's
contract, and it gets a header-comment ladder written the way
`origin_ledger.cpp`'s version-ladder header comment writes one.
- `package_manifest` — the manifest model and its JSON codec, nesting `BankModel`'s
own blob verbatim.
- `bank_package` — header encode / prefix decode / entry layout, composing the two
above. Never holds a payload.
- `export_plan` — the pure export decision: which entries, what names, what is
missing, and therefore whether the export may proceed.
- `import_plan` — the pure import decision: the id remap table, the parent remap, the
per-entry write / skip-already-present / rename-to-avoid-collision disposition, and
the destination bank name after uniqueness folding. **This module is why the whole
feature is testable without a DAW** — every collision rule above is a pure function
over strings and hashes.
`export_plan` and `import_plan` are separate TUs deliberately, not one `package_plan`:
they share only the manifest type, and separating them is what lets the two Phase Ε
build tracks run in parallel without fighting over a file. The seam is a
responsibility seam, which is what the structural heuristic asks for.
**`src/shell/package/` — filesystem and REAPER-facing.**
- `package_io` — read a package file to bytes, write bytes through temp + atomic
rename, read a bank file's bytes, write a landed file, enumerate existing bank-folder
names, and execute the rollback delete (citing the `prune_fs` carve-out).
- The file picker, which is REAPER's own on every platform — no `#ifdef _WIN32` /
`#else swell/swell.h` split, no Win32 `GetSaveFileNameW`, no wide-char round trip.
**Verified:** `GetUserFileName(int mode, const char* caption, const char*
initial_file_or_path, const char* extension_list, char* fnOutNeedBig, int
fnOutNeedBig_sz)` — `reaper_plugin_functions.h:3790`, documented at `:3788` — serves
both verbs symmetrically: `mode=0` chooses a new file (export's destination),
`mode=1` an existing one (import's source). `extension_list` takes the
`'ReaSampler banks|*.rsbank|All files|*.*'` form. `GetUserFileNameForRead` is
explicitly "Superseded, see GetUserFileName" (`:3796`) and is not used. No fallback
is needed: `src/app/main.cpp`'s `#define REAPERAPI_IMPLEMENT` appears without
`REAPERAPI_MINIMAL`, so the resolver walks the full table (`GetUserFileName` at
`:9084`), and `REAPER_PLUGIN_ENTRYPOINT`'s `REAPERAPI_LoadAPI` check refuses to load the extension if any one function
fails to resolve — so no REAPER build that loads us can lack it.
- `export_bank` / `import_bank` — the promptless verbs, mirroring
`src/shell/bank_ops/`'s pattern exactly: take a `ReaSamplerSession&`, do the work,
return an outcome, **no prompts and no message boxes**. The bindable action and the
panel menu item are then thin skins over one verb apiece, so the logic has one home
(`src/shell/bank_ops/CLAUDE.md` §"Scope").
**The dependency-shape criterion, stated because the brief demands it.** The pure
planners take **explicit value inputs** — the decoded manifest, the destination
`BankBook`, the set of file names present in the bank folder — never a session handle,
never a service container, never a "pass me the thing that has everything." The shell
*gathers*; the core *decides*. That is the same shape `src/shell/persist/CLAUDE.md` §"Scope"
already states ("it gathers rather than decides"). If a circular dependency shows up
during the build, the fix is a service split or a thin interface at the seam — never
threading an extra parameter through a chain of constructors, and never handing a
container down. A base class that grows a dependency must not grow its subclasses'
constructors.
---
## Invariant reconciliation
- **Relative paths only.** Strengthened, not merely preserved: the package format has
no field capable of expressing a path, only a bare file name, validated at both
ends. The destination path is spelled by `capture_paths` on the importing side.
- **Capture and placement are separate acts.** Import writes files and index entries.
It places **no** timeline item, ever — the same rule capture has always carried
(root `CLAUDE.md`, "The load-bearing principle"). A user who wants the imported
audio in the arrange uses the existing insert action.
- **Prune is the single exclusive file-deletion authority.** Unchanged. The one
rollback path is the documented self-cleanup carve-out, cited not restated.
- **No lossy transforms.** The payload is opaque bytes on both sides. `wav_codec` is
invoked on it only to hash and to read metadata already recorded — never to rebuild,
trim, normalize, or collapse. The mono collapse in particular is a **capture-path**
behaviour and must not reach the import path, for the same reason ingest is already
excluded from it (root `CLAUDE.md`, exact-bounds invariant: "ingest is excluded,
because an imported file is the user's bytes, not our capture"). A package's bytes
are someone else's capture; the same exclusion applies with the same reasoning.
- **Bit-identical round-trip.** Export → import → export yields byte-identical
payloads. This is the phase's trust anchor and belongs in the acceptance criteria of
the round-trip track, tested against frozen fixture bytes rather than against a
freshly-generated pair.
- **Bank generation.** Import mutates bank content that live ReaSampler 9000
instances may play, so it must `bumpBankGeneration()`
(`src/shell/persist/session.h`'s `ReaSamplerSession::bumpBankGeneration`, whose own comment says call sites "err toward
bumping"). Export mutates nothing and must bump nothing, write no ext state, and
open no undo point.
- **Beta/stable channel isolation.** Packages are channel-**agnostic** and this is
deliberate. Channel isolation exists so a beta cannot rewrite a stable project's
ext state (`app_version.h`'s `extStateNamespace` — the ISOLATION comment); a package is a file the user moves by hand, not
ambient project state, so there is no isolation property to preserve. A beta build
and a stable build at the same package format read each other's packages, and that
is the useful behaviour. The version ladder — not the channel — is what gates.
---
## Rulings — Daniel's, 2026-08-02
All three [Daniel]-class forks this doc opened were ruled the same day it was framed.
Nothing here is open. This section is an index; each ruling is **specified** in the
section that owns it, and that section is the implementation-binding text.
| Fork | Ruling | Specified in |
|---|---|---|
| **Ε-F1** | **Proprietary container.** Hand-rolled `RSBK`. ZIP via the vendored MiniZip64, and a hand-written stored-only ZIP shape, are both rejected | §"The container" |
| **Ε-F2** | **Import always lands as a new bank**, with an automatic numeric suffix on a display-name collision. Merge-into-existing is out of scope for this phase | §"Identity and collision on import" — the frame, plus the auto-suffix rule |
| **Ε-F3** | **Refuse** an import while the tracking ledger is degraded. No confirm-and-proceed path | §"Import under a degraded tracking ledger" |
**Two of the three went to a different answer than the framing recommended, and the
reasons are worth keeping.** Ε-F2's recommendation was a *prompt* pre-filled with a
uniqueness-folded suggestion; the ruling removed the prompt entirely, which is the
better shape — the name is derived deterministically from the destination, the user is
told rather than asked, and the existing rename verb is the recovery. Ε-F3's
recommendation was allow-with-confirm; the ruling refused, and the counter-argument
raised alongside that recommendation is what carried it (scale — the accepted residual
contemplates one untracked capture, an import strands hundreds).
---
## Implementation decisions — Ε-W2-T1
Not [Daniel]-class forks — both were `[propose at review]` calls in `docs/PLAN.md`'s
Ε-W2-T1 track, answered at implementation review rather than by Daniel, and recorded
here per this phase's own convention for keeping such answers where the design lives
rather than only in the track's own now-stale open-questions line.
- **Affordance: both the bindable action and the panel row.** The action targets the
**active** bank and is the only spelling that can reach the **pool** (the panel's
`showTabMenu` returns early on `isPool()` — a named-bank-tab context menu has no tab
to right-click for the pool), while the exported unit's own definition above includes
the pool. The panel row is the direct gesture on a specific named bank. Neither
subsumes the other.
- **Default file name: the bank's display name**, sanitized through
`capture_paths::sanitizeStem`, seeded into `<projectDir>/<stem>.rsbank`. A
project-derived name was the rejected alternative: three banks exported from one
project must produce three distinguishable files, and a project-derived name
collides on the second export. Known wart, worth recording rather than hiding:
`sanitizeStem` collapses an all-non-ASCII display name to the literal `capture`, so
two such banks still collide — the existing rename verb is the recovery, same as the
import-side auto-suffix collisions above.
---
## Non-goals and guardrails
- **No auto-insertion of imported audio into the arrange.** Same rule as capture.
- **No overwrite of an existing bank-folder file, ever.** Auto-rename instead.
- **No partial import.** All-or-nothing, with rollback. A partially-imported bank is
the failure mode this whole design is shaped to avoid.
- **No re-encode, no trim, no normalize, no mono collapse on either side.**
- **No compression of the audio payload.** `RSBK` concatenates payload bytes; there is
no compressor in the path and none is to be added.
- **No merge-into-existing import.** Every import creates a new bank (Ε-F2). There is
no target picker, no "import into the active bank" variant, and no second action.
Move/copy already move samples between banks after the fact.
- **No instrument state in the package** — the seam is left additive, deliberately
unspent.
- **No whole-book export in this phase.** One package carries one bank, because that
is the unit users think in. A future multi-bank package is an additive manifest
change that does **not** bump `minReaderVersion`, so the option is preserved by
construction rather than by promise. Do not build it now.
- **Do not make the package a sync mechanism.** No "re-import to update," no
reconciliation against a previously-imported package, no package identity tracked
in project state. Import is a one-way copy-in. Anything else is a different product.
+26 -16
View File
@@ -53,12 +53,20 @@ snapshot/restore, forces dither and all normalize-postprocessing off, and render
32-bit float. The tail wires into that existing path — no new render trigger, no
new backend.
### Bounds are always custom — so the tail bit is always `&1`
### Bounds are always the time selection — so the tail bit is always `&4`
The backend renders with `RENDER_BOUNDSFLAG = 0` (custom time bounds) for **every**
scope and every range type: it sets `RENDER_STARTPOS` / `RENDER_ENDPOS` explicitly
from the request's exact seconds (`capture.cpp` ~L352354). It does **not** use the
time-selection / selected-items / regions bounds modes.
The backend renders with `RENDER_BOUNDSFLAG = 2` (time selection) for **every**
scope and every range type: it writes the request's exact seconds into the
project's own time selection via `GetSet_LoopTimeRange` (`capture.cpp` ~L470477;
`RENDER_STARTPOS`/`RENDER_ENDPOS` are also written, as a defensive no-op for a
mode-0-only field, but the window itself travels in the time selection). It does
**not** use the custom-time-bounds mode (`RENDER_BOUNDSFLAG = 0`) — that mode was
tried and retired: DAW observation showed REAPER resolving a custom-bounds window
on a whole-millisecond grid AT RENDER TIME, flooring the end and rendering exactly
the floored frame count, which silently broke the exact-bounds precision
invariant. The time-selection mode does not floor the window. (The one narrative
home for that finding is `render_settings.h`'s `kRenderBoundsTimeSelection`; this
doc points there rather than retelling it.)
`RENDER_TAILFLAG` is a bitmask keyed to the **bounds mode**, not the capture range
type (header line 3047):
@@ -69,18 +77,20 @@ RENDER_TAILFLAG : &1=custom time bounds, &2=entire project, &4=time selection,
&32=selected project markers/regions
```
Because we always render in custom-time-bounds mode, **the only tail bit that ever
applies is `&1`**. There is no per-range-type tail-flag decision to make — a razor
capture, a time-selection capture, and an item capture are all custom-bounds
renders under the hood, so all three take `RENDER_TAILFLAG = 1`.
Because we always render in time-selection mode, **the only tail bit that ever
applies is `&4`**. There is no per-range-type tail-flag decision to make — a razor
capture, a time-selection capture, and an item capture are all time-selection-bounds
renders under the hood, so all three take `RENDER_TAILFLAG = 4`.
> **Correction to the framing brief.** The brief asked us to pick a
> `RENDER_TAILFLAG` bit *per capture range type* (time selection vs. razor vs. item)
> and flagged `&32` as "markers/regions." The header (line 3047) says `&32` =
> *selected project regions* and `&8` = *all markers/regions* — but neither matters:
> our renders are all `RENDER_BOUNDSFLAG = 0`, so the tail bit is `&1` unconditionally.
> The existing `kTailFlagCustomBounds = 1.0` constant in `capture.cpp` (~L80) is
> already correct; the field wiring is what's missing.
> our renders are all `RENDER_BOUNDSFLAG = 2`, so the tail bit is `&4` unconditionally.
> The existing `kTailFlagTimeSelection = 4` constant in
> `src/core/capture/render_settings.h` (the bounds mode's own bit, per bounds mode —
> header line 3047) is already correct — it was right from the start; the wording
> above it (which had assumed a custom-bounds render) was what was wrong.
### Mode 1 — Automatic (default): generous tail + auto-trim to -72 dB
@@ -88,7 +98,7 @@ Set, in addition to the exact `STARTPOS`/`ENDPOS` already driven:
| Setting | Value | Meaning / header ref |
|---|---|---|
| `RENDER_TAILFLAG` | `1` | apply tail for custom time bounds (line 3047, `&1`) |
| `RENDER_TAILFLAG` | `4` | apply tail for time selection (line 3047, `&4`) |
| `RENDER_TAILMS` | `8000` | the 8 s cap, in ms (line 3048) |
| `RENDER_NORMALIZE` | `32768` | **only** the trim-ending-silence bit (line 3051, `&32768`) |
| `RENDER_TRIMEND` | `≈ 0.000251` | -72 dB threshold (line 3062; scaling below) |
@@ -156,7 +166,7 @@ The existing (currently unwired) `CaptureRequest.renderTail` / `tailMs` fields
| Setting | Value |
|---|---|
| `RENDER_TAILFLAG` | `1` |
| `RENDER_TAILFLAG` | `4` |
| `RENDER_TAILMS` | `request.tailMs` (clamped to the 8 s cap — see below) |
| `RENDER_NORMALIZE` | `262144` (`kNormalizeDisableAll`, unchanged) |
| `RENDER_TRIMEND` | not set / irrelevant (trim bit is clear) |
@@ -177,9 +187,9 @@ adds a third state, so the wiring is a small enum, not a bool:
- **None** (default for null-test / verify captures, and the current two-scope
action defaults): `RENDER_TAILFLAG = 0`, `RENDER_TAILMS = 0`, normalize =
disable-all. Exact bounds. Byte-identical to today.
- **Auto** (the new user-facing default for tail-on captures): tailFlag `1`,
- **Auto** (the new user-facing default for tail-on captures): tailFlag `4`,
tailMs `8000`, normalize `32768` (surgical trim), trimEnd `0.00025119`.
- **Manual(ms)**: tailFlag `1`, tailMs `clamp(ms, 8000)`, normalize `262144`
- **Manual(ms)**: tailFlag `4`, tailMs `clamp(ms, 8000)`, normalize `262144`
(disable-all), no trim.
Recommended shape: replace `bool renderTail` with a `TailMode { None, Auto,
+15 -15
View File
@@ -226,25 +226,25 @@ them through the reorg, not to change them:
These are the naming equivalent of the JSON-`Parser` DRY violation — concrete hazards, not taste:
1. **Four hand-rolled `Parser` classes, one name.** `class Parser` is defined **four times**
`bank_model.cpp:306`, `bank_book.cpp:663`, `owned_manifest.cpp:107`, `view_mode_model.cpp:654`.
`bank_model.cpp`, `bank_book.cpp`, `owned_manifest.cpp`, `view_mode_model.cpp`.
Q-W1 already deletes three of them by extracting `core/json`; the naming rule is that the
survivor is **`json::Parser`** (or a more specific `json::Reader`/`json::Writer` pair — see
Q-8), never a bare `Parser` in flat scope.
2. **`FooterRect` and `ButtonRect` are shared across pure UI modules — and the codebase already
*knows* it.** `struct FooterRect` and `struct ButtonRect` are defined in `prune_button.h`
(lines 32, 46) and **reused** by `footer_bar.h`, which carries an explicit in-file "NAME NOTE"
(`footer_bar.h:2734`) documenting that `ButtonRect / FooterRect / SegmentRect / ActionBarRect /
and **reused** by `footer_bar.h`, which carries an explicit in-file "NAME NOTE"
(`footer_bar.h`) documenting that `ButtonRect / FooterRect / SegmentRect / ActionBarRect /
KitBox / KitButtonBox` are "already owned in this namespace" and that new types must carry a
`FooterBar*` prefix to avoid collision. That comment is a smell made visible: the flat
`reasampler::` namespace forces every pure-UI author to hand-check for name collisions before
minting a type. This is the single strongest in-codebase argument for the Q-4 sub-namespaces —
under `reasampler::ui` these shared rect types get one clear owner and the hand-checking stops.
3. **`Sample` (`bank_model.h:69`, the bank metadata struct) vs `AudioSample` (the `peaks` float
3. **`Sample` (`bank_model.h`'s `Sample` struct, the bank metadata struct) vs `AudioSample` (the `peaks` float
alias).** Already flagged in §2.4/Q-4; verified — `Sample` is the model record, `AudioSample`
is a raw PCM float. Under `model::Sample` vs `audio::AudioSample` the collision risk is gone,
but the *names* still read oddly side by side (a `Sample` that is metadata, an `AudioSample`
that is one float). Noted; the namespace split is the required fix, a rename is optional (Q-8).
4. **`Selection` (`bank_grid.h:112`) and `CellRect` (`bank_grid.h:23`) are generic names in a
4. **`Selection` (`bank_grid.h`'s `Selection` struct) and `CellRect` (`bank_grid.h`'s `CellRect`) are generic names in a
flat namespace.** `Selection` in particular is the kind of name a newcomer cannot place without
opening the file. `ui::Selection` / `ui::CellRect` resolve it structurally; no rename needed
beyond the namespace.
@@ -255,23 +255,23 @@ Here the names are legal and non-colliding but do not read on one principle —
at" gap:
1. **The model-family suffixes disagree: `_model` vs `_book` vs `Index`.** Verified: the pure model
modules are `bank_model.{h,cpp}` (owning `class BankIndex`, `bank_model.h:132`), `bank_book.{h,cpp}`
(owning `class BankBook`, `bank_book.h:208`), `view_mode_model.{h,cpp}` (owning `class ViewModeModel`,
`view_mode_model.h:376`), `owned_manifest.{h,cpp}` (owning `class OwnedFileManifest`,
`owned_manifest.h:52`). Four modules, four different file↔class naming relationships:
modules are `bank_model.{h,cpp}` (owning `class BankIndex`, `bank_model.h`), `bank_book.{h,cpp}`
(owning `class BankBook`, `bank_book.h`'s `BankBook`), `view_mode_model.{h,cpp}` (owning `class ViewModeModel`,
`view_mode_model.h`'s `ViewModeModel`), `owned_manifest.{h,cpp}` (owning `class OwnedFileManifest`,
`owned_manifest.h`). Four modules, four different file↔class naming relationships:
`bank_model``BankIndex` (file says "model," class says "index"), `bank_book``BankBook`
(file = class), `view_mode_model``ViewModeModel` (file = class), `owned_manifest``OwnedFileManifest`
(file ≈ class, but the class adds "File"). The `bank_model`/`BankIndex` mismatch is the worst:
the file name and its primary class name share no word. This is a genuine legibility wart — the
fix is a *rename decision* (Q-8), not something the directory move alone resolves.
2. **The `bank_book` "wraps `bank_model`" relationship is invisible in the names.** `BankBook`
(`bank_book.h:208`) is a registry of `Bank` (`bank_book.h:147`), each wrapping a `BankIndex`
(`bank_model.h:132`). The names `Book``Bank``Index` do not read as a containment hierarchy;
(`bank_book.h`'s `BankBook`) is a registry of `Bank` (`bank_book.h`'s `Bank` struct), each wrapping a `BankIndex`
(`bank_model.h`). The names `Book``Bank``Index` do not read as a containment hierarchy;
a reader has to learn it. (Not necessarily worth a rename — "book of banks" is evocative — but
it is the kind of call Q-8 should make deliberately, not by accident.)
3. **`realtime_record.h` (pure) vs `capture_realtime.cpp` (shell) — the word order flips.** Verified:
the pure realtime module is `realtime_record.{h}` (owning `RecordModePlan`/`RecordPhase`/
`RecordTickInputs`, `realtime_record.h:57173`) while its shell is `capture_realtime.cpp`. So the
`RecordTickInputs`, `core/capture/capture_realtime.h`) while its shell is `capture_realtime.cpp`. So the
pure core is `realtime_record` but the shell is `capture_realtime` — the two halves of one feature
are named on inverted word order (`realtime_record` vs `capture_realtime`). Compare the *clean*
shell-pair convention elsewhere: `drag_out` (pure) ↔ `drag_out_win` (shell) — same stem, suffix
@@ -279,7 +279,7 @@ at" gap:
naming-drift instance in the tree (Q-9).
4. **`capture.{h,cpp}` is the *offline* backend shell, but the name claims all of capture.**
Verified: `capture.h` declares `ICaptureBackend`, `OfflineRenderBackend`, **and**
`RealtimeRecordBackend` (`capture.h:112,124,201`), while the realtime *implementation* lives in
`RealtimeRecordBackend` (`capture.h`'s `OfflineRenderBackend`), while the realtime *implementation* lives in
`capture_realtime.cpp` and its pure planner in `realtime_record.h`. So `capture` is really
"capture interface + offline backend," a fat header (the §2.3 Interface-Segregation concern) whose
name oversells its scope. Its Q-W3 hoist (`capture_orchestrator`/`scope_resolve`) is the moment
@@ -290,11 +290,11 @@ at" gap:
Swept for names a newcomer couldn't decode; the tree is mostly clean here (a credit to it). Two
minor notes:
- **`guid_diff` / `GuidBaseline` (`guid_diff.h:40`)** — "GUID diff" is decodable in context (it
- **`guid_diff` / `GuidBaseline` (`guid_diff.h`'s `GuidBaseline`)** — "GUID diff" is decodable in context (it
diffs the live track/item GUID set between polls) but `GuidBaseline` reads more clearly as "the
previous-poll snapshot" than the module name suggests. Low priority; leave unless its `core/view`
relocation invites it.
- **`MinMax` (`peaks.h:30`), `KitBox` (`component_geometry.h:28`)** — terse but correct and local;
- **`MinMax` (`peaks.h`'s `MinMax`), `KitBox` (`component_geometry.h`'s `KitBox`)** — terse but correct and local;
no change. Named here only to record they were swept and cleared.
### 2b.5 What the naming audit does NOT touch (hard boundary)
+23 -13
View File
@@ -157,12 +157,19 @@ load hitch and any un-persisted internal state is lost. This is an accepted cost
of the CPU reclaim, not a bug. It must be documented at the toggle affordance so
the user isn't surprised.
**Never touched:** `B_MUTE` and `I_SOLO`. The tool owns visibility, `B_MAINSEND`,
`I_FXEN`, and FX-offline — nothing else — across every managed leaf, tagged or
untagged. The user's mute/solo survives every toggle, untouched. This is the exact
analog of the
capture pillar's non-destructive invariant: **the tool never destroys the user's
real state to do its job.**
**Never touched:** `B_MUTE`. The tool owns visibility, `B_MAINSEND`, `I_FXEN`,
FX-offline, and `I_SOLO` — nothing else — across every managed leaf, tagged or
untagged.
**Solo is owned but never lost.** Solo is a per-mode surface: switching modes banks
the outgoing mode's solo state, clears it, and replays the incoming mode's on
return, verbatim. Two modes therefore never share a solo — you can solo the drum
bus in Arrange and the sound-design chain in Design without either leaking into the
other — and neither is destroyed. That is the same exact analog of the capture
pillar's non-destructive invariant the flags above satisfy: **the tool never
destroys the user's real state to do its job.** It is snapshot-and-restore, one
level out from a single toggle to the pair of stances. Reapplying the current mode
(tagging, project load) is not a switch and does not touch solo at all.
---
@@ -316,8 +323,10 @@ Mirrors the capture pillar's split exactly.
- Snapshots prior flag values before parking (reads the same flags it will drive).
- Resolves track GUIDs via `GetTrackGUID` / `guidToString` / `stringToGuid` for the
index; never uses track index (unstable across reorders).
- Never touches the master track's visibility flags; never touches `B_MUTE` /
`I_SOLO` on anything.
- On a real switch only, banks/clears/replays `I_SOLO` per the per-mode solo surface
above.
- Never touches the master track's visibility flags; never touches `B_MUTE` on
anything.
**`persist` slice:**
- Serialize/deserialize the view section (modes + membership + show-both + snapshots
@@ -585,11 +594,12 @@ The settled distinction:
touch them**: a mode toggle never shows, hides, silences, re-lanes, or re-plays a
manual lane. Its `C_LANEPLAYS` state is the user's, left exactly as they set it.
This is the fixed-lane analog of the two invariants already load-bearing in D1 —
*never touch `B_MUTE`/`I_SOLO`* and *never touch the master* — extended to a third
surface: **never drive a lane the tool did not mint.** It is the same non-destructive
promise (the tool owns only what it created) reaching one level deeper, into the lane
dimension.
This is the fixed-lane analog of the invariants already load-bearing in D1 —
*never touch `B_MUTE`*, *never touch the master*, and *never lose the user's solo*
(see "Never touched" above) — extended to a further surface: **never drive a lane
the tool did not mint.** It is the same non-destructive promise (the tool owns only
what it created, and restores what it parks) reaching one level deeper, into the
lane dimension.
### Lane-ownership index (the new data)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1117,7 +1117,7 @@ Addendum is the *why*; those are the *what/how*.
**Framing.** Folds one more control into the S-VIEW redesign: a **visual velocity → amp
transfer-curve editor**. Today the engine maps velocity to gain *linearly* (`velocityGain_ =
velocity / 127.0`, `sampler_core.cpp:261`), applied once at note-on in `Voice::start()`. Daniel
velocity / 127.0`, `Voice::start()`), applied once at note-on in `Voice::start()`. Daniel
wants that mapping to become an **editable transfer curve** — a bezier from a default flat line to
an arbitrary multi-point curve — so velocity dynamics are fully shapeable per sound.
@@ -1181,7 +1181,7 @@ a LICE shell that draws handles and routes the mouse).
evaluation is called at note-on, not per frame (see call 4).
4. **Voice-engine application point → `Voice::start()`, replacing the linear `velocity/127`.**
Confirmed from source: `sampler_core.cpp:261` computes `velocityGain_ = velocity / 127.0` **once
Confirmed from source: `Voice::start()` computes `velocityGain_ = velocity / 127.0` **once
at note-on** inside `Voice::start()`; the per-frame render path (`advanceFrame`, line 408:
`gain = amp * velocityGain_`) then just multiplies the cached scalar. So the transfer curve
slots in at exactly one line: `velocityGain_ = curve.eval(velocity)` at note-on — **off the
File diff suppressed because it is too large Load Diff
+829
View File
@@ -0,0 +1,829 @@
# Render in place — product notes
Framing, rationale, and design-direction calls behind **Phase Ρ — render a track's
output to a new sibling track, in the timeline, without touching the bank.** The
tickable spec lives in `docs/PLAN.md` (§Phase Ρ); the architecture detail belongs in
`src/shell/capture/CLAUDE.md` and `src/core/capture/CLAUDE.md` once the track lands.
This doc holds the *why* — the third-verb argument that reconciles this feature with
the capture/placement separation, the prior art it borrows from, the reuse inventory
that makes it small, and the handful of decisions the shape actually turns on.
Status: framed by product-designer (2026-08-02) from Daniel's direct request the same
day; **all three [Daniel]-class forks RULED the same day**Ρ-F1 **refuse a
multi-track selection**, Ρ-F2 **the result track always goes to Arrange**, Ρ-F3
**follow the panel tail setting**. See §"Rulings" for the index and the recorded
rationale; each is specified in place in the section that owns it. Nothing in this
doc is open.
**Ρ-F2 overrode the framing, including Daniel's own original phrasing.** The request
as first stated had the new track take whatever mode was active when the action fired;
the ruling replaced that with an absolute rule. §"Mode transitions" is written against
the ruling, and the A/B-on-the-bench behaviour that mode-following would have produced
**no longer exists anywhere in this design** — do not reintroduce it as a benefit.
Everything else below is a product-designer call with its reasoning stated; contradict
it in review with an argument, not a preference.
---
## What it is (and what it is not)
**Render in place takes one selected track, renders its output over the current
range to a file, and drops that file as an item on a brand-new sibling track at the
exact position it was rendered from — then moves the source track into Design mode.**
The new track inherits the source's colour and its name with a `Capture ` prefix, and
belongs to Arrange unconditionally (Ρ-F2). The bank is never opened, never read, never
written.
The model Daniel named is REAPER's own *Render selected track time selection to new
track (stereo) and mute original*. Phase Ρ differs in exactly one respect, and that
respect is the whole feature: **instead of muting the original, it parks it.** The
source track goes to Design mode — hidden from the arrange, out of the mix, FX
offline, CPU reclaimed — and its rendered audio takes its place in the arrangement.
That is a strictly better disposition than mute, because mute leaves the design
scaffolding visible and its FX resident; Design mode removes both, reversibly, from
a snapshot.
**It is not a capture.** No `Sample` is minted into any `BankModel`, no index entry is
added, no file is recorded in the tracking ledger, the bank generation is not bumped,
and no live ReaSampler 9000 instance reloads. The bank does not change in any way an
observer could detect.
**It is not a freeze.** The source track's FX chain is untouched — not removed, not
bypassed permanently, not flattened. Design View's park is snapshot-based and fully
restored on toggle-back (`src/shell/view/CLAUDE.md` §Non-destructive restore), so
switching to Design brings the source back exactly as it was, FX and routing intact.
Ableton's *Freeze & Flatten* destroys the device chain; Phase Ρ never does.
**It is not a placement of a bank sample.** The insert action and the arrange drop
both take something already in the bank and put it on the timeline. Phase Ρ's file
was never in the bank and never will be. The two paths share `InsertMedia` and
nothing else.
---
## The third verb — and why the load-bearing principle survives it
Root `CLAUDE.md` carries the tool's sharpest rule:
> **Capture and placement are separate acts.** Capturing audio writes a file to the
> bank and adds an index entry. It **never** puts an item in the arrange view. […]
> Any code path that auto-inserts a capture into the timeline violates the purpose of
> the tool and **must be rejected in review**.
Phase Ρ renders audio, places an item in the arrange, and deliberately does not touch
the bank. The question is not rhetorical and the answer is not "it's fine because
Daniel asked for it."
**The answer is that the rule is about the bank, not about rendering.** Read the
sentence again: the object of "capturing" is *the bank* — a file in the bank folder
plus an index entry. The prohibition attaches to *that act* placing an item. What the
rule protects is a two-way boundary:
- the arrangement must never gain an item as a side effect of a bank gesture, and
- the bank must never gain a member as a side effect of an arrangement gesture.
Phase Ρ crosses neither direction, because **the bank is not a party to it.** The
system has two verbs today and gains a third:
| Verb | Source | Sink | Touches the bank |
|---|---|---|---|
| **Capture** (`RunCapture`, batch, realtime, bake, ingest) | arrange / instrument | bank | writes it |
| **Placement** (`RunInsertSelected`, `performArrangeDrop`) | bank | arrange | reads it |
| **Render in place** (Phase Ρ) | arrange | arrange | never |
Three verbs, three distinct (source, sink) pairs. The bank appears in exactly two of
them and never on both sides of one. The load-bearing rule is the statement that no
single verb may have the bank on one side and the arrange on the other *in the wrong
direction* — and Ρ has the bank on neither side.
What Ρ shares with capture is the **render**, not the capture: the same
`renderOffline` seam, the same `FxBypassGuard`, the same exact-bounds custom time
window, the same multi-track refusal, the same `RENDER_ADDTOPROJ = 0`. A render is a
mechanism; a capture is a render *plus* a bank landing. Ρ takes the mechanism and
declines the landing. That is reuse, not a breach.
### The boundary that keeps them from bleeding
Four things must stay true. Each is a review-rejectable condition, and three of the
four are structural rather than remembered:
1. **Ρ's shell never names the bank.** `render_in_place.cpp` must not call
`session.bank()`, `session.book()`, `session.recordCreated()`, or
`session.bumpBankGeneration()`. The `Sample` that `OfflineRenderBackend::capture`
returns is discarded, and on the project-media destination its `relativePath` is
left **empty** — so a Ρ `Sample` is inert by construction and could not be usefully
added to a bank even by accident.
2. **Ρ cannot express "write into the bank folder."** The destination reaches the
backend as a **two-valued enum** (`Bank` / `ProjectMedia`), never as a caller-supplied
path. There is no string a Ρ caller could pass that lands a file in
`reasampler_bank/`. This is the single most important structural choice in the
phase: it makes the boundary a type, not a convention.
3. **Ρ's file is never recorded as owned.** Prune deletes `(owned ∩ present)
referenced` (`src/core/reclaim/CLAUDE.md`), where `owned` comes from the tracking
ledger. Ρ records nothing, so its file is not prune-eligible — and it lives outside
the bank folder, so prune's enumeration never sees it either. Two independent
layers. The symmetry is worth stating plainly: **the tool deletes only what it
owns, and a render-in-place file belongs to the project, not to the tool.**
4. **The traffic is one-way.** Ρ may borrow capture's render. **Capture may never
borrow Ρ's placement.** No capture action grows a "…and place it" option, ever. If
a future request wants capture-and-place, the answer is "fire the capture action,
then fire the insert action" — two acts, which is the whole point.
**What would count as drift**, stated so a reviewer can name it: a `renderDir` string
on `CaptureRequest` instead of the enum; a Ρ path that calls `session.bank().add()`;
a Ρ file recorded via `recordCreated`; a `place` flag added to `CaptureActionDef`; or
a "Ρ but also add it to the bank" convenience action. Any of those collapses the
three verbs back into two and the rule stops meaning anything.
---
## Prior art, and what each one contributes
The shape is not novel; the *disposition of the source* is. Named precedents, because
they anchor the argument better than reasoning does:
- **Logic Pro — Bounce in Place.** The idiom Ρ's name borrows. Renders a track's
output to audio at the same timeline position, on a new track, with the source
preserved. Confirms that "in place" in DAW usage means *at the same timeline
position*, not *onto the same track* — which is why the name is right despite Ρ
creating a new track.
- **Pro Tools — Commit.** The closest prior art, and the one that validates the mode
transition. Commit offers four dispositions for the source track: *Hide and Make
Inactive* (the default), *Make Inactive*, *Delete*, and *Do Nothing*. The default
is hide-and-deactivate — visually gone and processing gone. That is precisely what
Design View's park already does (`B_SHOWINTCP=0`, `B_SHOWINMIXER=0`,
`B_MAINSEND=0`, `I_FXEN=0`, per-FX offline), except that Ρ gets it *reversibly and
as a membership fact* rather than as a per-track inactive flag. Ρ is Commit with
a fifth disposition the DAWs do not have — *move to the design bench* — supplied by
the tool's own mode system.
([Sound on Sound](https://www.soundonsound.com/techniques/making-commitments),
[Production Expert](https://www.production-expert.com/production-expert-1/pro-tools-track-commit-vs-track-freeze))
- **REAPER — Render selected track time selection to new track and mute original.**
The action Daniel named. Contributes the range semantics (time selection) and the
new-track placement; Ρ replaces its source disposition and adds colour/name
cloning.
- **Ableton Live — Freeze & Flatten.** Contributes a negative: flatten destroys the
device chain. Ρ explicitly does not, and the Design-mode park is what makes
preserving it cost nothing at playback.
---
## What already exists — the reuse inventory
Daniel's framing was that the machinery is in place. It substantially is. This table
is the proof, and it is also the spec's shape: each row names the module that answers
the need, so the implementation is composition rather than construction.
| What Ρ needs | Already answered by |
|---|---|
| Resolve the source track + the range (razor-else-time) | `shell/capture/scope_resolve``ResolveScopeSource(CaptureScope::Track, …)` |
| Refuse a multi-track render | `core/capture/render_settings``isMultiTrackStemRender` / `multiTrackRefusalMessage`, fired inside `renderOffline` |
| Render exactly the requested window, wet, at track scope | `shell/capture/capture_orchestrator``renderOffline` + `FxBypassGuard` + `RenderTrackSelection` |
| Never add the render to the project as an item | `shell/capture/capture.cpp``RENDER_ADDTOPROJ = 0`, unconditional |
| Refuse a widened render | `core/capture/render_window::frameCountFor` + the bounds gate in `OfflineRenderBackend::capture` |
| Snapshot and restore every `RENDER_*` project setting | `ScopedRenderSettings` (RAII) in `capture.cpp` |
| Force the project to be saved first | the `EnumProjects` / `Main_SaveProject` gate in `OfflineRenderBackend::capture` |
| Name the render after its source track + a discriminator | `core/capture/capture_name``composeCaptureName`, `shell/capture/capture.cpp``captureNameFor` |
| Read the source track's display name (with the `Track N` fallback) | `shell/capture/scope_resolve::trackName` |
| Collapse a bit-identical stereo render to mono | `core/capture/wav_codec::collapseToMono`, driven by `collapseCapturedFileToMono` |
| Compute the `InsertMedia` bitmask with the stretch bit provably clear | `core/capture/insert_plan::computeInsertMode` |
| Place a file at a known track + time, undo-wrapped, selection restored | the recipe in `shell/capture/insert.cpp` / `shell/actions/arrange_drop_win.cpp` |
| Move a track into Design and reapply the active mode | `core/view` `MembershipIndex::tag` + `shell/view/view.h` `applyMode` / `mintManagedLanes` |
| Persist the view model | `ReaSamplerSession::saveToActiveProject()` (the `persistViewState` pattern in `design_view_actions.cpp`) |
| Register one more bindable action | `shell/actions/action_registry` — one `ActionTableRow` in `main.cpp`'s table |
| Pure folder arithmetic over the flat `I_FOLDERDEPTH` delta list | `core/capture/track_topology` (extended — see §"The new track") |
**What genuinely does not exist**, and why nothing already there stretches to cover
it — three small pure additions and one bounded seam:
1. **A render destination that is not the bank.** `OfflineRenderBackend::capture`
derives its output path from `deriveBankPaths(projectDir, …)` unconditionally
(`capture.cpp`'s `OfflineRenderBackend::capture`) and points `RENDER_FILE` at the bank folder. Nothing about
that is parameterized. The alternative — render into the bank and then move the
file out — was rejected: it puts a transient, unindexed, unowned file inside the
folder prune enumerates, which is exactly the file class the ownership rule exists
to reason about, and it would make the bank folder momentarily lie about its
contents. **Seam:** a `CaptureDestination { Bank, ProjectMedia }` field on
`CaptureRequest` (defaulting to `Bank`), resolved by the backend *after* its own
save gate, plus a `RenderPaths deriveRenderPaths(absoluteDir, baseName, uniqueTag)`
sibling in `capture_paths` that `deriveBankPaths` is then expressed in terms of, so
the file-stem spelling keeps one owner.
2. **The absolute path of the rendered file, returned.** `CaptureResult` carries only
`sample.relativePath`, which Ρ deliberately leaves empty. One new field,
`CaptureResult::absolutePath`, set on the Ok path.
3. **Where a sibling track goes, in folder terms.** Genuinely new, genuinely
necessary, and genuinely small — see §"The new track".
4. **The idempotent `Capture ` prefix.** Six lines in `core/capture/capture_name`.
Everything else is composition. No new directory, no new backend, no new interface,
no new persisted state.
---
## The render — scope, range, refusal
**Scope is Track**, always. `CaptureScope::Track` means the render hears the item/take
FX plus the selected track's own track FX, with every ancestor and the master
neutralized to unity — no FX, no fader, no pan/width/law colouring
(`fxBypassPlanFor`, `FxBypassGuard`). That is exactly right for a drop-in
replacement: what the render contains is *the track's own contribution to its
parent*, which is what the new sibling track must reproduce when it feeds the same
parent.
**The range is razor-else-time selection**, resolved by `ResolveScopeSource` — the
same rule every other capture action already obeys. Razor wins when present; the
razor union's bounds are the window. If neither a razor area nor a time selection is
present, the action refuses with the reason `resolveRange` already produces. **Item
extent is not a fallback**, and should not become one: item extent is item scope's
concern, and a track render bounded by whichever items happen to be selected is a
different and much less predictable verb.
**Multi-track selections are refused**, inherited rather than re-implemented.
`renderOffline` fires `isMultiTrackStemRender` before touching anything, keyed on the
render *source* (`SelectedTracks`, which track scope always uses), so any selection of
more than one track refuses with `multiTrackRefusalMessage(CaptureScope::Track)`
before a single project setting is written. Ρ inherits this for free and adds no
check of its own.
**Ρ-F1, RULED by Daniel, 2026-08-02: *refuse*.** One selected track per fire is a
**settled non-goal**, in the same sense as the other entries in §"What Phase Ρ
explicitly is NOT" — not a deferral. There is no per-track loop planned, no second
wave holding one, and no seam to be left half-open on the way past. If multi-track is
ever wanted it is a new phase with its own framing, and the counter-argument that made
this a fork (the stem-collapse hazard does not apply to a per-track loop, so the
refusal is inherited rather than required) is recorded in §"Rulings" so it does not
have to be rediscovered.
**Tail follows the panel setting — Ρ-F3, RULED by Daniel, 2026-08-02: *"follow panel
tail settings."*** None / Auto / Manual, read from `bankPanelTailSetting()` like every
other capture path. Forcing `None` would be Ρ inventing a policy the rest of the tool
does not have, and a decaying design chain wants its tail when its source is about to
be silenced.
**Two consequences of that ruling, both accepted, both stated here because an
implementer meets them directly:**
1. **Under Auto or Manual the placed item is longer than the window it replaces.** The
chain's decay rings past the range end and the render carries it, so the item on
the result track extends past the source range. This is correct for reverb and
wrong for a section meant to butt against the next one — and the ruling accepts
that trade rather than splitting the behaviour. The user's lever is the panel's own
tail setting: set it to None before firing if a hard edge is wanted.
2. **The exact-bounds gate is inactive under Auto and Manual.** The gate in
`OfflineRenderBackend::capture` runs **only** under `TailMode::None`, so Ρ renders
in the other two modes are unguarded against a widened render. This is inherited
from every other capture path, not introduced by Ρ, and it is not a caveat to bury:
the phase's exactness guarantee under Auto/Manual is the *start* only.
The placed item's **start is exact in every tail mode**, because a tail is only ever
added at the end. The null test therefore holds in all three modes — the shared region
nulls; the tail simply has nothing to null against.
A third option was floated at framing and is **not ruled in**: keep the panel setting
but run the bounds gate's start-alignment check regardless of tail mode, since a tail
only ever extends the end. It is recorded as an unexercised alternative in §"Rulings"
and is not to be built into this phase.
**Mono collapse applies**, unchanged. A render whose channels are bit-identical
collapses losslessly to one channel and REAPER derives a mono item from the file
(`insert.cpp` passes only a path). Daniel's Ψ.6 ask named "mono arrange items"
explicitly, so this is the intended outcome, not a side effect. **But note what Ρ
changes about the risk:** root `CLAUDE.md` already flags, as `[verify — DAW]`,
whether REAPER sums a 1-channel item on a stereo track at the same unity gain as a
dual-mono 2-channel item. Until Ρ, that property was unverified but not load-bearing
— nothing in the tool placed a collapsed capture automatically. **Ρ is the first path
where a collapsed render is placed into the mix by the tool itself,** which promotes
that question from a footnote to a verification obligation on this phase.
---
## Where the file goes
**The project's recording path** — `GetProjectPathEx(proj, buf, sz)` (SDK header
2550), which the header's own `RECORD_PATH` entry names as the way to get the
*effective* path when `RECORD_PATH` is blank or relative (header 3102).
Why there rather than a dedicated `reasampler_renders/` folder: because the file is
**the project's media, not the tool's.** REAPER's own render-to-new-track, apply-FX,
and freeze glue actions all write into the recording path; *Clean current project
directory* and *Save project as… with copy of media* both understand it. A file in
the recording path is managed by REAPER's project-media machinery, which is exactly
the machinery that should own it. A `reasampler_renders/` folder would be marginally
more findable and would make ReaSampler the apparent owner of files it explicitly
does not own — the wrong trade.
The relative-paths-only invariant is untouched: it binds the persisted `BankIndex`,
and Ρ writes nothing to any index. REAPER stores the item's source path in the `.rpp`
by its own rules.
---
## Placement — exactly
The item lands at **`src.startSeconds`**, the render window's start, unrounded and
**unsnapped**.
Unsnapped is the load-bearing word. `performArrangeDrop` runs its drop time through
`SnapToGrid` because a hand drop wants snapping; Ρ must not, because a snapped
placement would move the audio off the sample-accurate position it was rendered from
and break the property the whole tool is built on. **Ρ's placement is the null test
performed automatically:** an offline render of a range, re-inserted at its source
position, nulls to silence against the source — root `CLAUDE.md` calls that the
tool's trust anchor. Ρ *is* that gesture, made a workflow. If Ρ's placement is not
sample-exact, Ρ is broken, and the way you find out is by soloing the two tracks with
one polarity-inverted.
The recipe is `insert.cpp`'s, verbatim, with the bank lookup removed:
snapshot the cursor → `SetOnlyTrackSelected(newTrack)` → `SetEditCurPos(startSeconds,
false, false)` → `InsertMedia(absolutePath, computeInsertMode(InsertOptions{}))` →
restore the cursor. `InsertOptions{}` defaults give native length, no tempo conform,
and `insert_plan` guarantees the &4 stretch-to-time-selection bit is never set — so
"do not silently time-stretch on insert" holds by construction. Ρ must never offer a
conform variant: a conform would defeat the exact placement it exists to produce.
**Selection afterwards is a deliberate divergence.** Every other placing path
restores the caller's track selection. Ρ leaves **the new track selected, alone.**
The reason is specific: in the headline case the source track is being parked out of
sight in the same gesture, so restoring the selection would leave the user selecting
an invisible track. The new track is the workflow's next subject; select it. The edit
cursor *is* restored, since nothing about Ρ argues for moving it.
**The Ρ-F2 ruling inverts that reasoning in the Design-fired case, and the rule stays
absolute anyway.** Fired from Design, the result track is the parked one and the source
is the visible one, so leaving the result selected selects an invisible track — the
exact thing the rule exists to avoid in the other direction. Making the selection
conditional on the active mode would reintroduce mode-relative behaviour, which is
precisely what the ruling removed from this action. One rule, both cases: the result
track ends up selected, alone.
---
## The new track — index, folder, colour, name
### Index and folder — the one piece of genuinely new arithmetic
"Sibling" is easy to say and has three cases. Getting it wrong is audible, not
cosmetic, which is why this is the one place Ρ adds a real (small) pure function
rather than composing.
The naive answer — insert at `sourceIndex + 1` — is wrong twice:
- **Source is a folder parent** (`I_FOLDERDEPTH >= 1`). Inserting immediately after
it makes the new track the folder's **first child**, so the rendered audio is
summed back into the folder and runs through the parent's FX and fader a second
time. Track scope already put the parent's own FX and fader *into* the render, so
this double-processes audibly.
- **Source is the last track in its folder** (`I_FOLDERDEPTH <= -1`). The source
carries the folder's closing delta, so inserting after it lands the new track
**outside** the folder — the audio then bypasses the folder bus entirely and the
drop-in replacement is silently wrong in the other direction.
The correct rule is one computation in absolute nesting levels, over the same flat
`I_FOLDERDEPTH` delta list `track_topology::directChildIndices` already prefix-sums.
Given `depth[i]` for every track and `level[0] = 0`, `level[i+1] = level[i] +
depth[i]` (and `level[count] = 0` for a well-formed project):
1. `L = level[srcIdx]` — the source's own nesting level.
2. **Insert position** `p`: if `depth[srcIdx] >= 1` (folder parent), `p` = the first
`j > srcIdx` with `level[j] == L` — i.e. immediately after the whole folder, at
the source's own level; `count` if none. Otherwise `p = srcIdx + 1`.
3. **Two folder-depth writes**, and only two. With `b = p - 1` (the track that will
precede the new one) and `Lp = level[p]` (the level the track currently at `p`
sits at, `0` at end-of-project): set `depth[b] = L - level[b]`, and set the new
track's `depth = Lp - L`.
The total of all deltas is preserved, so nothing downstream of the insertion shifts.
Checked against every case:
| Case | `depth[b]` after | new track `depth` | Result |
|---|---|---|---|
| Normal track, mid-folder or top level | unchanged (`0`) | `0` | inserted directly below, same level |
| Last track in a folder (`-1`) | `0` | `-1` | new track becomes the folder's last member |
| Last in two folders (`-2`) | `0` | `-2` | closing delta moves to the new track intact |
| Folder parent | unchanged | `0` | new track lands after the whole folder, at the parent's level |
| Last track in the project | unchanged | `0` or the source's close | consistent, sums to zero |
That is roughly thirty lines, fully unit-testable with no DAW, and it belongs beside
`directChildIndices` in `core/capture/track_topology` — same input, same arithmetic,
same file. A malformed project whose deltas do not sum to zero should clamp rather
than assert; the failure mode is a track at the wrong nesting level, never a crash.
Creation is `InsertTrackInProject(proj, p, /*flags=*/0)` (SDK header 3954), then
`GetTrack(proj, p)` (3501) to obtain the handle. **`flags = 0`, not `1`:** the header
states `flags&1` adds default envelopes/FX, and a Ρ track must be bare — the FX are
already baked into the audio, and a default chain would process the render a second
time.
### Colour
`SetMediaTrackInfo_Value(newTrack, "I_CUSTOMCOLOR", (double)GetTrackColor(source))`.
`GetTrackColor` (3517) returns the custom colour already OR'd with `0x1000000`, or
`0` when the track has no colour set; `I_CUSTOMCOLOR` (2942) treats a value without
that bit as "not used." So the same single line clones a colour *and* clones the
absence of one, with no branch.
### Name
`"Capture " + sourceName`, where `sourceName` is `scope_resolve::trackName(source)`
`GetTrackName` (3629), which already answers REAPER's `Track N` convention for an
unnamed track. An unnamed track 7 therefore yields `Capture Track 7`, which is a real,
deterministic, identifiable name; this is Ψ-W2-T1's precedent applied unchanged.
Written with `GetSetMediaTrackInfo_String(newTrack, "P_NAME", buf, true)` (2997).
**The prefix is idempotent — it never stacks.** If the source name already begins with
`"Capture "`, the new name is the source name **verbatim**. So rendering `MONEY`
gives `Capture MONEY`, and rendering `Capture MONEY` gives `Capture MONEY` again, not
`Capture Capture MONEY`.
The alternative — a counter suffix, `Capture MONEY 2` — is rejected. REAPER does not
uniquify track names either, duplicate track names are ordinary and harmless, and a
counter is a treadmill that has to be maintained forever. What actually distinguishes
two renders of the same source is their position in the track list and the item on
each; the name's job is to say *what this is*, and it says that correctly the first
time. Making the operation a fixed point is worth more than distinguishability here.
This is one pure function in `core/capture/capture_name``captureTrackName(sourceName)`
— tested for the plain case, the already-prefixed case, the empty-source case, and
the `Track N` case. The prefix string is a display convention, not a persisted key:
unlike `kManagedLanePrefix` or an action-id suffix, changing it later strands nothing.
---
## Mode transitions — the source parks, the result goes to Arrange
Daniel's original phrasing was *"the source track stays/goes to design mode, and the
resulting new sibling track […] stays in whatever mode was active when the action was
run."* **The second half was overridden by his own later ruling — Ρ-F2, 2026-08-02:
*"for this action which is not a capture, the result track should always go to
arrange."*** The source half stands exactly as first stated; the result half is now
absolute and mode-independent.
**Source track: unconditionally a Design member afterwards.**
`membership().tag(sourceGuid, kDesignModeId)` covers both readings in one call —
`tag` replaces any prior single-mode membership, so a source already in Design
*stays* (no observable change) and a source in Arrange or untagged *goes*. This is
exactly what the shipped `VIEW_TAG_DESIGN` action does to a selection; Ρ performs it
on one track as part of a larger gesture.
Two inherited behaviours to state rather than fight:
- **Show-both on the source is not cleared.** Show-both is the user's explicit "pin
this visible across modes" flag. Ρ tagging a source into Design must not silently
unpin it; a show-both source stays visible in both stances, which is what the user
asked for.
- **A folder-parent source is not hidden by tagging it.** Parents are derived, never
tagged: a parent is visible in every mode any descendant leaf is visible in
(`core/view/CLAUDE.md`). Tagging a folder parent Design sets its *own* membership
but leaves it visible in Arrange as long as any child is an Arrange member. This is
a limitation of the shipped model that the existing tag action shares exactly; Ρ
inherits it. Do **not** invent a cascade that tags the children — that changes the
membership model to make one feature convenient.
**Result track: unconditionally an Arrange member**, whatever mode was active —
`membership().tag(newTrackGuid, kArrangeModeId)`, synchronously and explicitly, **not**
an `untag()` to the Arrange default. The distinction is load-bearing: an explicit
membership record is what protects the ruling from the auto-tag detector (below). An
untagged track is an Arrange member by observable behaviour but carries no record, and
a record is what the detector must be made to respect.
**Note what is novel here, because it is worth a reviewer's attention.** Ρ is the
**first** path in the tree to write an explicit `kArrangeModeId` record. The shipped
*tag selected tracks → Arrange* action does not — it dispatches to `doUntag()`, i.e.
Arrange-by-absence, which is why the constant appears in `view_mode_model` and
`mode_enable` but never in a `tag()` call. The record is nonetheless well-formed and
behaviourally identical to the untagged state everywhere that matters:
`ViewModeModel::isMember` answers `true` for `arrange` and `false` for `design` in
both cases, the derived-parent and lane rules read the same, and `untag()` still
returns it to absence. The only differences are one more entry in the persisted
membership index and — the point — its visibility to the detector's filter. **[verify
— DAW]** that a project saved with an explicit Arrange record round-trips and shows no
behavioural difference from an untagged track; the JSON round-trip is unit-testable and
should be tested, but the live view behaviour is not.
**The placed item is tagged Arrange too**, explicitly, for the same reason. Item
membership is a separate index from track membership and it is what drives lane
minting; leaving the item untagged hands it to the detector, which tags a new item to
the active mode whenever its track has no pre-existing single-mode content — and a
brand-new track never does. After `InsertMedia`, enumerate the new track's items (it
is brand new, so they are exactly the ones just placed) and tag each;
`shell/capture/item_read::itemGuid` is the existing GUID seam.
### The one hazard the ruling creates — the auto-tag detector
The ruling **dissolves** the ordering hazard the mode-following rule carried and
**creates a different one** in its place. Both are stated, because the first was
written into the plan's acceptance criteria and is now wrong.
**Dissolved.** Under mode-following, the tag had to precede the `applyMode` reapply:
an untagged track is an Arrange member by default, so a Design reapply running first
would have parked a track destined for Design, and it would have stayed parked until
the next switch. Under the ruling the result track *is* an Arrange member, so a Design
reapply parking it is the correct outcome and the ordering no longer changes what the
user sees. Tag first anyway, for state hygiene — it is simply no longer load-bearing.
**Created, and it is a defect rather than a nuance.** The panel's new-content detector
(`panel_input::detectNewContent` over `guid_diff::GuidBaseline`, feeding
`view_mode_model::autoTagNewContent`) tags **every new track to the active mode**,
unconditionally: it diffs live GUIDs against the previous tick and never consults the
membership index. Fire Ρ while Design is active and, on the next timer tick, the
detector re-tags the brand-new result track — and its item — from Arrange to Design,
silently reversing the ruling inside a second. Nothing in Ρ's own gesture can outrun
it, because it runs after.
**The fix is one rule, and it is worth stating generally: an explicit tag wins over
the detector.** `detectNewContent` drops any added GUID that already carries a
membership record (`MembershipIndex::query(guid) != nullptr`) before building its
auto-tag input. Two lines, at the point in that function where the model is already in
hand. The rule is right beyond Ρ — the detector exists to classify content the *user*
made, not content the tool made and has already classified — and it is a strict
improvement on an existing rough edge: a track brought back by undo keeps its original
mode instead of being re-tagged to whatever mode happens to be active at the time.
Two alternatives were considered and rejected. Re-arming the baseline after Ρ's
gesture (the `bankPanelNotifyProjectLoaded` mechanism) works, but it absorbs an entire
tick of genuinely new content silently — a blunt instrument aimed at two GUIDs.
Changing `autoTagNewContent`'s own track rule changes Design View's behaviour for
every caller in order to serve one.
The resulting behaviour, stated completely:
| Active mode when fired | Source afterwards | Result track afterwards | What the user sees |
|---|---|---|---|
| **Arrange** | Design — parked, hidden, FX offline | Arrange — visible, in the mix | The headline case. The design chain vanishes from the arrangement and its audio takes its place, at the same position, same colour, named after it. |
| **Design** | Design — visible on the bench | Arrange — parked while Design is active | The bench keeps only the source. The render is not on screen; it is waiting in the arrangement, and switching to Arrange shows it in the source's place. |
**The Design-fired case produces no visible change, and that is the ruling's accepted
cost.** Fire Ρ from the bench and the immediate feedback is that nothing appears. The
price buys the action meaning exactly one thing wherever it is fired — *commit this
design work into the arrangement* — which is the reasoning behind the ruling: Ρ is not
a capture, and a capture's mode-relative habits do not apply to it.
**Feedback deserves reconsideration for this case, and only this case.** Ρ is
otherwise silent on success because the new track is the feedback; fired from Design
there is no visible new track, so a silent success is indistinguishable from a no-op.
**[propose at review]** whether the Design-fired path should emit a one-line
`ShowConsoleMsg` naming the track it created. Recommendation: yes — it costs one line
and one string, and it is the only place in the phase where success is invisible.
**Lane minting runs**, via `mintManagedLanes(view, nullptr)` before the reapply, on
the same path `doMoveItems` already uses — so a track that ends up carrying content
for two modes splits into managed lanes exactly as it would from any other membership
change. Ρ adds no lane rule of its own.
---
## Undo
**One undo block** (`Undo_BeginBlock2` / `Undo_EndBlock2` with `UNDO_STATE_ALL`, i.e.
`-1`), opened before the track is created and closed after the mode reapply — the
same shape `insert.cpp` and `performArrangeDrop` already use. The render itself sits
*outside* the block: `renderOffline` mutates only `RENDER_*` project settings, which
it snapshots and restores by RAII, and writes a file. Nothing there is undoable and
nothing there should be in the undo history.
What one Ctrl-Z therefore restores: the new track is gone, its item with it, the
source track's folder-depth write is reverted, and the track selection is back.
Three residuals, all inherited and all honest:
1. **The rendered file survives.** REAPER's undo does not delete files, prune is the
exclusive deletion authority in this system, and Ρ's file is not even prune-
eligible. An undone render leaves an orphan `.wav` in the project's recording
path — precisely what REAPER's own render and record actions do. Not a defect.
2. **The source stays tagged Design.** REAPER's undo restores live track state but
does not roll back the view model's membership index or active mode — documented
in `src/shell/view/CLAUDE.md` §Gotchas, where `snapshots_` already carries the same
split. The way out is the existing *tag selected tracks → Arrange* action. Do not
build a compensating mechanism for one feature; the model-vs-undo split is a
phase-D-scale question, not Ρ's.
3. **A membership entry for the deleted track's GUID lingers**, harmlessly:
`ViewModeModel::reconcile(liveGuids)` prunes unknown GUIDs on its next pass.
**Persist runs after the block closes, not inside it** — the ordering
`design_view_actions::doMoveItems` already documents, because `persistViewState` may
raise a Save-As dialog and a modal dialog must not sit inside an open undo block.
---
## The action
**Command-id suffix: `RENDER_TRACK_IN_PLACE`.** FOREVER-STABLE per channel
(`channelCommandId` composes `CEREBELLUM_REASAMPLER_` / `CEREBELLUM_REASAMPLER_BETA_`
in front of it), so this string can never change once shipped — user keybindings key
off the composed id.
Chosen deliberately as a **new verb family**, not a member of `CAPTURE_*`. The id is
permanent and it is the most durable statement the codebase makes about which pillar
a feature belongs to; filing this under `CAPTURE_` would encode the exact confusion
the third-verb argument exists to prevent. `RENDER_*` also leaves room for a future
`RENDER_ITEMS_IN_PLACE` without renaming anything.
**Actions-list phrase: `"render selected track to a new track (source moves to
Design)"`**, which REAPER shows as *ReaSampler: render selected track to a new track
(source moves to Design)*. Long, but the parenthetical is not decoration — a user
binding this to a key must know the source is about to disappear from the arrangement
before they press it, not after. The existing family already carries parentheticals of
this weight (*insert selected sample at edit cursor (conform to tempo)*).
Registration is **one `ActionTableRow`** in `main.cpp`'s `buildMainActionTable()` — the
Q-W6 data-driven table drives registration, `hookcommand` dispatch, and the unload
mirror-unregister from that one row. Main section only; no `custom_action` /
`hookcommand2` second registration is needed.
**Feedback:** silent on success (the new track is the feedback), `ShowConsoleMsg` on
every refusal, carrying the reason `resolveRange` / `renderOffline` already produced.
This matches `RunInsertSelected` exactly.
---
## What Phase Ρ explicitly is NOT
Stated as sharply as the goals, because a small phase stays small only if its edges
are named:
- **Not a bank capture, in any form.** No index entry, no ledger record, no
generation bump, no instance reload.
- **Not multi-track.** Ρ-F1, RULED: one selected track per fire; more than one refuses
with the message that already exists. Settled, not deferred — no per-track loop is
planned, half-built toward, or left a seam for.
- **Not mode-following.** Ρ-F2, RULED: the result track is an Arrange member
unconditionally. There is no variant that follows the active mode, no per-fire
choice, and no bench-visible result — firing from Design puts nothing on the bench.
- **Not item-scoped.** No `RENDER_ITEMS_IN_PLACE`, no item-extent range fallback. The
seam is left open by the id family; the feature is not built.
- **Not a tempo-conforming insert.** No conform variant, ever — a conform would
destroy the exact placement the feature exists to produce.
- **Not a mute, not a delete, not a freeze.** The source keeps its items, its FX, its
routing and its automation. It moves stance; it loses nothing.
- **Not a source-track cascade.** Rendering a folder parent does not tag its children,
does not restructure the folder, and does not touch anything but the two
folder-depth values the insertion arithmetic requires.
- **Not a new persisted state.** Membership writes go into the existing `"reasampler"`
view section. Ρ adds no key, no version rung, no wire format.
- **Not a new directory.** Three small pure additions to existing `core/capture`
modules, one new shell TU in `shell/capture`, two lines in `panel_input.cpp`, one
row in `main.cpp`.
---
## Invariant amendments this phase owns
Three statements in the tree become false the moment Ρ lands, and amending them is a
**deliverable of the track**, not a follow-up — the precedent is Phase Ψ, where three
such amendments were carried as acceptance criteria of the tracks that broke them. A
track that lands Ρ without these reads as an invariant breach in review.
1. **`src/shell/capture/CLAUDE.md` §Invariants** — *"`RunInsertSelected` is the one
deliberate exception to capture-never-places … every other capture entry point
writes only a file + index entry."* Ρ adds a second placing path in this
directory. The amended form must say that this directory now hosts two placing
paths and state the discriminator: `RunInsertSelected` places a *bank sample*;
`render_in_place` places a render that never entered the bank. Neither is a
capture placing itself.
2. **`src/shell/actions/CLAUDE.md` §Invariants** — *"`arrange_drop_win` is the only
timeline-placing shell in this directory."* Strictly this stays true if Ρ's shell
lives in `shell/capture/`, but the sentence reads as a claim about the system.
Amend it to be explicit that it scopes to *this directory*, and cross-reference the
third verb.
3. **`src/core/view/CLAUDE.md` §Invariants** — *"New tracks are tagged to the active
mode at creation."* Ρ-F2 makes this conditional for the first time: the detector's
active-mode rule now applies only to a GUID that carries **no** membership record,
because an explicit tag wins over it (§"Mode transitions"). Amend the sentence to
say so, and state the reason in one clause — the detector classifies content the
user made, not content the tool made and already classified. `src/shell/panel/`'s
own CLAUDE.md describes `panel_input` as "the new-content auto-tag timer" without
restating the rule, so it needs no amendment; if that changes, the rule has one
home and this is it.
Root `CLAUDE.md` §"The load-bearing principle" should gain **one sentence**, not a
rewrite: that a render which never enters the bank and never leaves it is a third
verb outside the rule, with the two-way boundary spelled out. The rule's force must
not be diluted — it is what keeps the tool honest — so the amendment names the
exception precisely rather than softening the prohibition.
---
## Where it lives
**Pure** — three additions, all to existing modules with existing test targets, no new
directory:
- `core/capture/track_topology` — the sibling-placement arithmetic
(`siblingPlacement(depths, srcIdx) -> { insertIndex, precedingDepth, newDepth }`).
Same input list, same prefix-sum, same file as `directChildIndices`.
- `core/capture/capture_name``captureTrackName(sourceName)`, the idempotent prefix.
- `core/capture/capture_paths``RenderPaths` + `deriveRenderPaths(absoluteDir,
baseName, uniqueTag)`, with `deriveBankPaths` re-expressed over it so the stem
spelling keeps one owner (`bankRelativeForName` already depends on that being true).
**Shell** — one new TU plus one bounded edit:
- `shell/capture/render_in_place.{h,cpp}` — the action body. It lives in
`shell/capture/` rather than `shell/actions/` because it composes `renderOffline`
and `ResolveScopeSource` and is genuinely a render path, not a skin over one; the
directory's own CLAUDE.md says action *bodies* belong here and that `shell/actions`
only skins mutation logic owned elsewhere.
- `shell/capture/capture.cpp` — the destination branch (~6 lines at the path
derivation) and `CaptureResult::absolutePath`. **No behavioural change on the bank
path**: the enum defaults to `Bank`, and the bank branch must be byte-identical to
today.
- `shell/panel/panel_input.cpp` — two lines inside `detectNewContent`: drop added
GUIDs that already carry a membership record, so an explicit tag wins over the
auto-tag detector (§"Mode transitions"). This edit exists **only because of the Ρ-F2
ruling**; without it the ruling reverses itself on the next timer tick. No other
function in the file is touched.
- `src/app/main.cpp` — one `ActionTableRow`.
**Performance posture:** every surface is cold — one gesture, once. None of the named
hot paths (peaks envelope compute, audition, the realtime-capture tick's
single-pointer-test idle fast path, the instrument's `process()`) is touched, and no
guardrail applies beyond the general one.
---
## DAW-verification obligations
Following the plan's convention, stated up front so they are an obligation rather
than a discovery. Nothing in Ρ is unit-testable past the pure functions.
- **The null test on Ρ's own output** — render a track over a range, then
polarity-invert the source against the new track and confirm silence. This is the
phase's trust anchor and the single most important check.
- **The three folder cases** — a normal mid-folder track, a last-in-folder track, and
a folder parent — each rendered, each confirming the new track's nesting level and
that the render feeds (or bypasses) the folder bus correctly. `[verify — DAW]`
whether `InsertTrackInProject` at index `p` combined with the two `I_FOLDERDEPTH`
writes settles without an intermediate `TrackList_AdjustWindows(false)` (header
7735; the note at 2721 says some attribute writes need a manual panel update, and
the `isMinor` semantics are undocumented).
- **The collapsed-mono placement** — render a dead-centre source, confirm the item is
mono, and confirm it sums at the same level as the stereo source did. This is root
`CLAUDE.md`'s existing `[verify — DAW]` on mono-item-on-stereo-track summing,
promoted to load-bearing by Ρ.
- **Both mode transitions** — fired from Arrange (source parks; result track visible
and in the mix) and fired from Design (source stays on the bench; result track
parked, then present in the source's place after switching to Arrange). **In each
case wait out at least one panel timer tick and re-check the membership.** That is
the auto-tag-detector regression, and it is the check that catches a missing
explicit-tag-wins filter or an untagged item — either of which silently reverses the
Ρ-F2 ruling. The old ordering check (that the new track is never momentarily parked)
no longer applies: under the ruling the result track is an Arrange member and a
Design reapply parking it is correct.
- **Undo** — one Ctrl-Z removes the track and item and restores the folder depth; the
file survives; the source stays tagged Design.
- **The name and colour clone**, including a second run over an already-prefixed track
(must not stack) and an unnamed source (must read `Capture Track N`).
- **`GetProjectPathEx` on a project saved in a folder with a non-default recording
path**, confirming the render lands where the project's media lives.
---
## Rulings — Daniel's, 2026-08-02
All three [Daniel]-class forks this doc opened were ruled the same day it was framed.
Nothing here is open. This section is an index; each ruling is **specified** in the
section that owns it, and that section is the implementation-binding text.
| Fork | Ruling | Specified in |
|---|---|---|
| **Ρ-F1** | **Refuse** a multi-track selection. One track per fire, inherited from `isMultiTrackStemRender`. A per-track loop is a settled non-goal for this phase, not a deferral | §"The render" — the multi-track paragraph; §"What Phase Ρ explicitly is NOT" |
| **Ρ-F2** | **The result track always goes to Arrange**, whatever mode was active. *"For this action which is not a capture, the result track should always go to arrange."* | §"Mode transitions" — the absolute rule, the item tag, and the auto-tag-detector fix it requires |
| **Ρ-F3** | **Follow the panel tail setting** (None / Auto / Manual), with both consequences accepted | §"The render" — the tail paragraph and its two numbered consequences |
**Ρ-F2 went against the framing, and against the request's own original wording.**
The framing recommended mode-following on the strength of Daniel's first phrasing
("stays in whatever mode was active") and of one use it enabled — an A/B of a chain
against its own render, both on the bench, neither touching the arrangement. The
ruling took the alternative the framing had itself named: an absolute rule, because Ρ
is *not a capture* and the mode-relative habit belongs to the capture pillar, not
here. **That A/B use no longer exists, and no text in this doc or in `PLAN.md` may
still claim it as a benefit.** The cost the ruling accepts is that firing Ρ from
Design produces no visible change; the compensating console message is a
[propose at review] item in §"Mode transitions".
**The ruling also has a cost the framing did not anticipate**, recorded here so it is
not read as scope creep at review: the panel's auto-tag detector tags every new track
to the active mode, so without an explicit-tag-wins filter the Design-fired case
reverses the ruling on the next timer tick. The two-line fix in
`panel_input::detectNewContent` is a **deliverable of this phase**, caused by this
ruling. Under mode-following it would not have been needed — the detector would have
agreed with Ρ.
**Ρ-F1 and Ρ-F3 both matched the recommendation**, so nothing in the spec moved. The
counter-arguments are kept because they are the reason each was a fork rather than a
call, and they will resurface: for Ρ-F1, that the stem-collapse hazard does **not**
apply to a per-track loop (each iteration renders one track), so the refusal is
inherited rather than forced — what a loop would actually cost is bookkeeping (indices
shift per insertion, so the folder arithmetic re-derives each pass; plus an undo label,
a partial-failure story, and a selection-afterwards rule). For Ρ-F3, that a drop-in
replacement arguably wants exact length, and that forcing `None` would have kept the
exact-bounds gate live on every Ρ render.
**One unexercised alternative, recorded and not built.** For Ρ-F3, a third option was
floated at framing: follow the panel setting *and* run the bounds gate's
start-alignment check regardless of tail mode, since a tail only ever extends the end.
It would recover the widening guard on the start edge without losing the tail, at the
cost of editing a gate shared by every capture path for one caller's benefit. It is
**not ruled in** and is not part of this phase. If the unguarded Auto/Manual render
ever produces a real bug, this is the shape of the fix.
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -45,7 +45,7 @@ below:
Two sharp edges follow directly and recur throughout this note:
- **The `STABLE_FOREVER_STRING` command-id contract** (CLAUDE.md; `main.cpp:41`,
- **The `STABLE_FOREVER_STRING` command-id contract** (CLAUDE.md; `app_version.h`'s `commandIdPrefix()`,
prefix `CEREBELLUM_REASAMPLER_`). Command-id strings are minted once and **never
changed after shipping** — user keybindings key off them. Two coexisting binaries
that register the *same* id strings collide in REAPER's Actions list.
@@ -67,9 +67,9 @@ allowed to touch.
## What we have today
- No version anywhere. `CMakeLists.txt:2` is `project(reaper_reasampler LANGUAGES
- No version anywhere. `CMakeLists.txt` is `project(reaper_reasampler LANGUAGES
CXX)` — no `VERSION`. The binary announces itself only as `"ReaSampler loaded.\n"`
to the console (`main.cpp:960`). There is no number a user, a bug report, or a
to the console (`main.cpp`). There is no number a user, a bug report, or a
future migration can key off.
- The natural user-visible readout already exists: the docked LICE bank panel, and
the console (`ShowConsoleMsg`). A version has cheap homes; none is wired.
+126 -6
View File
@@ -416,14 +416,34 @@ against the WCAG tests — §2.1):
| Role | Pastel | Starting RGB (hex) | Job |
|---|---|---|---|
| `accent/primary` | pastel lime green | `~176,224,152` (`#B0E098`) | the live/active/selected signal — the eye-magnet |
| `accent/secondary` | pastel teal | `~132,214,208` (`#84D6D0`) | categorical role A (non-active zones, a second cluster) |
| `accent/secondary` | pastel teal | `~132,214,208` (`#84D6D0`) *(superseded, see below)* | categorical role A (non-active zones, a second cluster) |
| `accent/tertiary` | pastel purple | `~194,170,232` (`#C2AAE8`) | categorical role B (tertiary zones, a distinct affordance class) |
| `accent/hot` | brighter primary tint | `~200,236,178` (`#C8ECB2`) | hover / live / drag feedback (a lighter pastel-lime) |
**Locked values, where they diverge from the starting table (2026-07-31).** `accent/secondary`
darkened to `#38A8A0` (same hue ~176°, same saturation, lightness 0.68 → 0.44). Its **binding
limiter** — the pair that stops it going darker — is the velocity-curve trace on a
*hover-lightened* `bg/cell` at **3.03:1** against a 3:1 floor, tighter than either the AA 4.5:1
text-on-fill pair (4.91:1 on `bg/base`) or the indicator floor on rest `bg/cell` (3.94:1). ONE
new Role was added past the original three, since "exactly three accents" is no longer a
constraint: `overlay/trace` `#816AA6`, a muted violet for marks drawn *over* an accent fill (see
§the two-neighbour problem below). The spectral ramp's mid stop also became its own value —
the original pastel teal `#84D6D0` — but as a private constant, not a `Role`.
**The two-neighbour problem** (rule + numbers owned by `src/core/ui/CLAUDE.md`; the design
consequence is recorded here). A mark drawn *over* an accent fill has to read against the fill
*and* the surface behind it, which caps *any* single value at ≈3.07:1 against both. Two
consequences shape the design rather than the palette: such a role is confined to the band it
was picked for, and a **state** of that mark cannot be expressed as a hotter color — every
value that clears the ceiling sits within 1.05:1 of every other, so the grabbed envelope handle
signals by **size and a punched-out core** instead. That deliberately inverts the kit's
"brighter = hotter" convention in this one band, because over a light fill a brighter tint is a
*lower*-contrast tint (`accent/hot` measures 1.15:1 against the lime).
These are light-ish, low-saturation tints. On the **REAPER-grey surfaces** (`bg/cell`
`#3a3a3a`) they still clear **AA-large (3:1)** and the **state-indicator** floor — but the
margin is **much smaller than it was on near-black** (roughly ~6:17:1 on grey vs. ~15:1
on `#12121x`). This is a real DS-2-revision tension: **the greyer background pulls the
margin is **much smaller than it was on near-black** (~7.6:1 primary / ~5.5:1 tertiary /
~3.9:1 the darkened secondary on grey, vs. ~15:1 on `#12121x`). This is a real DS-2-revision tension: **the greyer background pulls the
pastels toward the floor** at the same time the "keep it soft" rule pulls them away from
saturation. Approach from the **soft side** (§2.1) — keep them as pastel as possible while
still clearing the floor on **grey, not near-black** — but **if any pastel used as a state
@@ -470,9 +490,12 @@ the rest of the UI. Concretely: the ramp runs **pastel-lime (primary, low) → p
(secondary, mid) → pastel-purple (tertiary, high)** as a three-stop gradient through the
accent constants (or a slightly wider pastel arc that passes *through* those three anchor
points), keeping every stop in the pastel band. This ties the spectrum to the palette:
the same three hues that mean "live / category A / category B" elsewhere are the endpoints
and midpoint of the spectrum here, so the strip reads as an extension of the accent system,
not a separate neon flourish. The **active** zone still lifts to `accent/primary` +
the same hues that mean "live / category A / category B" elsewhere anchor the spectrum here,
so the strip reads as an extension of the accent system, not a separate neon flourish.
**The mid stop is its own constant, not an alias of `accent/secondary`** (decoupled
2026-07-31): the ramp is a luminance progression while the accents are categorical roles, and
darkening secondary for a categorical reason inverted lo→mid→hi. A monotonicity test now guards
the ordering. The **active** zone still lifts to `accent/primary` +
its bloom, so "which zone is live" stays unambiguous over the categorical spectral bands.
- **Feel:** premium, almost visualizer-grade — but soft and cohesive, a pastel spectrum
@@ -738,3 +761,100 @@ re-skin).**
font obligation.
- **Phase S is not gated on Phase L** — S7S13 proceeded in parallel; they adopted the
kit via L3 when it landed. Phase L is complete (L1L7 all landed).
---
## 8. Antialiasing disposition — the drawn-surface audit
A standing inventory of every class of drawn surface and how it answers antialiasing, so the
audit is re-runnable rather than a one-off sweep. **The rule the table applies:** an
axis-aligned fill or hairline has no aliasing to remove — LICE's `aa` flag is inert on a pure
horizontal or vertical run — so "already clean" there is a statement about geometry, not a
concession. Everything with a slope or a curve must draw through a primitive that antialiases.
**Primitive gotchas this audit established (verified in `vendor/WDL/WDL/lice/`):**
- `LICE_Line` takes INTEGER endpoints. `aa=true` antialiases the span, but the endpoints are
still quantized; `LICE_FLine` keeps float endpoints and `LICE_ThickFLine` is *always*
antialiased and adds width.
- `LICE_FillTriangle` takes **no** `aa` parameter at all — its sloped edges alias, and the
only fix inside the kit is to re-stroke those edges with an AA line in the same ink.
- **`LICE_Arc` does not rasterize an arc.** It rasterizes a whole circle clipped to a
rectangular bounding box per 90° chunk (`lice_arc.cpp` `__DrawArc`), and its AA circle splits
one unit of ink across two adjacent pixels by the **fractional part of the radius**
(`w = yf - floor(yf)`, then `wa` and `ai - wa`). A half-integer radius therefore puts 50% on
each of two pixels at the cardinal points, and stacked radii do not tile — vertical spacing
between rings `r` and `r-1` dilates from 1.0 px at the top to 1.41 px at 45°. Measured on the
shipped 3-ring knob arc: weakest cross-section peak **138/255** and perpendicular weight
**1.623.24 px** against a nominal 3 (67% ripple).
- **`LICE_ThickFLine` lays its width along the MINOR axis**, so perpendicular weight is
`wid·cos θ`. Measured at width 2: **1.412.00 px** across a 090° sweep — it thins to
`1/√2` of nominal at every diagonal.
- Neither of those two is usable for a stroke that must hold a consistent weight. Arcs and
spline contours draw through the analytic stroker instead (`core/ui/stroke_aa` +
`shell/instrument/editor_stroke`): coverage is distance-to-polyline, MAX-accumulated into a
scratch mask and blended **once**. The single blend is the structural part — compositing
per segment re-lays ink over the previous segment's fringe.
- A min/max waveform column plot cannot be antialiased by the column fill itself (the columns
are vertical). The outline is what reads as jagged, so it is stroked separately.
> **Methodological lesson — why this table got two rows wrong.** The original audit verified
> *which primitive each surface called* and treated an `aa=true` argument as the answer. It
> never verified *what the primitive rasterized*. Both misses hid behind a true-looking
> statement: `LICE_Arc` really does antialias, and `LICE_ThickFLine` really is always
> antialiased — neither fact says anything about opacity or perpendicular weight, which is
> what was actually broken. **A disposition row is only earned by a measurement of the
> rendered output** (peak alpha, weight across angle), not by reading the call site.
| Surface | Where | Disposition |
|---|---|---|
| Radial knob track arc | `editor_internal.h` `drawKnobFace` | **Fixed (2026-08-01), widened (2026-08-01)** — the stacked-radius `LICE_Arc` ring never reached an opaque core. Now ONE analytic stroke (`strokeArcAA`); `kKnobTrackArcPx` was initially left at 1 px, below the ≥2 px opaque-core threshold (`core/ui/CLAUDE.md`), and surfaced to Daniel as a by-eye call — he ruled to enlarge all sub-2 px stroker widths, so it is now 2 px and reaches a guaranteed opaque core. |
| Radial knob value arc | `editor_internal.h` `drawKnobFace` | **Fixed (2026-08-01)** — same stroke, `kKnobValueArcPx` = 3 px, clear of the opaque-core threshold. Measured: peak **255/255** at every cross-section, weight **2.953.11 px** (5% ripple). |
| Knob needle | `drawKnobFace` | **Fixed (2026-08-01)**`LICE_ThickFLine`'s minor-axis width thinned it to `cos θ` as the knob swept. Now `strokeLineAA`, 2 px. |
| Inner curve dial arc | `drawInnerDial` | **Fixed (2026-08-01)** — the arc shared the knob track/value arc's stacked-radius opacity defect. Same one analytic fix, at `kInnerDialArcPx` = 2 px (at the opaque-core threshold). |
| Inner curve dial needle | `drawInnerDial` | **Converted (2026-08-01), widened (2026-08-01)** — this needle was already `LICE_FLine` (float endpoints, always AA), not `LICE_ThickFLine`; a 1 px AA line has no width to lay along a minor axis, so it never had the knob needle's `cos θ` defect. Moved to `strokeLineAA` at 1 px for one-seam consistency, not because it was broken — but 1 px is below the analytic stroker's opaque-core threshold, so it fell under Daniel's later blanket ruling and is now `kInnerDialNeedlePx` = 2 px. |
| Staged envelope segment slopes | `editor_paint_waveform.cpp` | **Fixed (2026-08-01)** — one `strokePolylineAA` over the whole polyline, so the stage joints blend once. Vertices stay INTEGER by design: they are the positions the draggable handles are drawn at. |
| Spline (drawn EG) contour | `editor_paint_waveform.cpp` `paintSplineOverlay` | **Fixed (2026-08-01)** — the trace was never gapped; it was fully aliased (every pixel full or empty) because the loop passed INTEGER `cy`, quantizing the slope into alternating 1/2 px steps. Now sub-pixel y (`subpixelFromPoint`) through `strokePolylineAA`. Measured: peak **255/255**, weight **1.952.01 px** (3% ripple). |
| Velocity-curve popup trace | `editor_paint_curve.cpp` | **Fixed (2026-08-01)** — same cause, same treatment. |
| Velocity-curve mini thumbnail | `editor_paint_curve.cpp` | **Fixed (2026-08-01), widened (2026-08-01)** — strokes analytically at sub-pixel y instead of integer-endpoint `LICE_Line`. Initially kept as a 1 px hairline (a 2 px trace was thought to blot at thumbnail scale), but 1 px is below the opaque-core threshold; Daniel's ruling raised `kMiniTracePx` to 2 px, same as the popup trace. |
| Waveform min/max columns | `draw_kit.cpp` `drawWaveform` | **Fixed** — column fill unchanged (it cannot alias), plus an AA `LICE_FLine` stroke joining each column's extremes to its neighbour's, in the same ink. Shared with the docked bank panel and the browser cards. **Measured cost** (Release, MSVC 14.44, real LICE, 24 stereo cards × 136 columns = 6528 columns): fill alone 0.070 ms per full-grid repaint, fill+stroke 0.48 ms — the stroke is ~0.41 ms, about 2.5% of a 60 Hz frame, and the grid repaints on hover/scroll/drag, not continuously. One-off scratchpad measurement, 2026-08-01, harness not committed — not a standing regression guard; re-measure before relying on it again. |
| Preview play triangle | `editor_paint_chrome.cpp` | **Fixed**`LICE_FillTriangle` has no `aa`; its two sloped edges are re-stroked with AA `LICE_FLine`. |
| Envelope/spline node handles (squares) | `editor_paint_waveform.cpp` | Already clean — axis-aligned `LICE_FillRect`. |
| Envelope curve knots (circles) | `editor_paint_waveform.cpp` | Already clean — `LICE_FillCircle` with `aa=true`. |
| Knob body disc | `drawKnobFace` / `drawInnerDial` | Already clean — `LICE_FillCircle` with `aa=true`. |
| Buttons | `draw_kit.cpp` `drawButton` | Already clean — `LICE_RoundRect` with `aa=true`. |
| Piano key faces + edges | `editor_paint_chrome.cpp` `drawKeyboard` | Already clean — axis-aligned fills and a vertical hairline. **See §8.1.** |
| Loop span, crossfade region, marker bars, grab tab | `editor_paint_waveform.cpp` | Already clean — axis-aligned fills. |
| Group fences, card/tab/tooltip borders, focus rings | deck, browse, panel painters | Already clean — `LICE_DrawRect`, axis-aligned. |
| Surface fills + inner edge highlights | `draw_kit.cpp` `fillSurface` | Already clean — `LICE_GradRect` + axis-aligned hairlines. |
| Embed strip (TCP/MCP) | `reasampler_embed.cpp` | Already clean — axis-aligned fills only. |
| Docked bank panel chrome | `panel_render.cpp` | Already clean — axis-aligned fills, rects and hairlines. Its only exposure to this pass is the shared `drawWaveform`. |
| Text | `draw_kit.cpp` `text` | Already clean — `LICE_CachedFont` AA glyph cache (§1.1). |
**Analytic stroker cost** (Release, MSVC, real LICE, one-off scratchpad harness 2026-08-01,
not committed — re-measure before relying on it): 30 knob arcs **0.113 ms → 0.169 ms**; a
500 px spline contour **0.013 ms → 0.047 ms**. About +0.09 ms per full editor repaint, on a
surface that repaints on interaction rather than continuously. Micro-optimisation, each lever
measured in isolation: writing the blend straight to the bitmap's bits rather than through
`LICE_PutPixel` is the big one (arcs 0.169 vs 0.253 ms); reusing the scratch mask across
calls matters on the contour's large bounding box (0.047 vs 0.073 ms); `float` over `double`
is small but real (contour coverage 0.045 vs 0.051 ms). The per-row valid-extent bookkeeping
in the mask is a **wash** against the simpler clear-the-whole-box design (0.218 vs 0.218 ms
for a full repaint) — it wins on the contour and loses on the small arc boxes; it is kept
because the contour is the drag-interactive surface.
### 8.1 Was the piano-key width defect an aliasing artifact?
**No.** Every piano key is an axis-aligned `LICE_FillRect` with an integer width, so there is
no sloped or curved edge for aliasing to act on — the defect could not have had that cause.
It was integer-division residue: `keyboard_strip` tiles same-class keys at one integer width
and the indivisible remainder of the band width has to go *somewhere*. The fix put it in
symmetric end margins instead of in a key, which is arithmetic, not rasterization.
**Does the fix survive DPI scaling?** At the client-pixel level, yes — key widths are uniform
by construction at every client width the strip's test sweep covers. Above that level it is
**unverified**, and for a structural reason worth keeping visible: nothing in the instrument
implements `IPlugViewContentScaleSupport`, so a host that scales the plugin window resamples
the already-rasterized uniform widths at the physical-pixel level, where the guarantee no
longer applies. That is a host-scaling question, not an antialiasing one, and it is recorded
as a gotcha in `src/core/instrument/CLAUDE.md`.
+172
View File
@@ -0,0 +1,172 @@
# DAW verification — bank-package transfer across machines
What a DAW pass must establish for `.rsbank` export and import, and the exact strings or
counts to read off. The unit corpus (`tests/fixtures/package_compat/`) already proves the
version ladder, the truncation verdicts and the hostile-name refusals against frozen
bytes. **Nothing below is covered by it**: every cell here depends on a real REAPER
session, a real file dialog, or a genuine second machine.
**Build to use.** Release, installed into `UserPlugins/`, REAPER restarted — extensions
load at startup only. Note the version the *About*/version action reports; §5 needs it.
**Machines to use.** Two: **A** (the source) and **B** (the destination). B must be a
different machine, or at minimum a different user account with its own REAPER resource
path and its own projects folder — the point is that no absolute path from A can resolve
on B. A USB stick, a network share, or a cloud folder are all acceptable transports.
**Projects to use.** On A: one **saved** project with a bank holding at least **three**
samples, at least one of them audibly distinct from the others, and at least one whose
display name carries a non-ASCII character (e.g. `Café hit`). On B: one **saved**,
otherwise empty project.
---
## 1. Export writes one file and touches nothing else
On A, right-click the bank's header in the docked panel → **Export as package...** (or
run *ReaSampler: export active bank as package*). Accept the suggested file name.
Read off:
- The console shows `ReaSampler export: wrote 3 entry/entries (N bytes) to <path>`, with
the entry count matching the bank.
- A single `.rsbank` file exists at that path. **No `.rsbanktmp` sibling remains** — a
leftover temp file means the atomic rename did not complete.
- The bank's card count, the bank folder's file count, and the project's dirty flag are
all **unchanged**. An export writes no ext state and opens no undo point, so REAPER
must not consider the project modified by it alone.
- Nothing was added to the arrange view.
## 2. The transfer itself — the claim no unit test can make
Copy the `.rsbank` to B by whatever transport you chose. Do **not** copy the project, the
bank folder, or anything else.
On B, open the empty saved project. Panel bank menu → **Import bank package...** (or run
*ReaSampler: import bank package (.rsbank)*), and choose the transferred file.
Read off:
- A message box: `Imported 3 sample(s) into a new bank: "<bank name>".`
- The console block repeats that line and ends with `One undo removes the imported bank
and its entries. It does NOT delete the imported files ...`.
- The panel shows a **new** bank with the same display name and the same number of cards,
**in the same order** as on A.
- B's bank folder holds three new files. The non-ASCII display name from A renders
correctly on the card — a mangled name here means the UTF-8 path/name conversion broke
in transit.
- **Audition each card.** They must sound like their counterparts on A. This is the whole
claim: the audio survived a machine boundary with no shared path.
- Press **Ctrl-Z once**. The imported bank and its entries disappear in one step. The
three files remain in B's bank folder (that is stated in the console block above, and is
the designed behaviour — a prune reclaims them). Redo to continue.
## 3. Re-importing the same package never overwrites
Still on B, import the **same** file a second time.
Read off:
- A second new bank appears, named with a suffix (`<bank name> 2`), and the box's
`(a bank named "<bank name>" already exists in this project)` clause appears in the
console block.
- B's bank folder now holds **six** files, not three. The console reports
`3 file(s) landed under a freshly minted name (the package's own name was already taken
in the bank folder). An existing bank file is never overwritten.`
- The first imported bank's cards still audition correctly — nothing was replaced under it.
## 4. Round trip back to the source
On B, export the imported bank (§1) to a second `.rsbank`. Carry it back to A and import
it into A's original project.
Read off:
- The import succeeds and lands as a new bank beside the original.
- The original bank on A is untouched: same card count, same names, same audio.
- Compare the two `.rsbank` files' **sizes**. They will usually differ — entry names,
sample ids and the export timestamp are all legitimately re-minted across a trip. The
payload bytes are what must survive, and that half is closed by
`tests/test_package_round_trip.cpp` against frozen bytes; do **not** treat a size
difference here as a defect.
## 5. The too-new refusal, with the message read verbatim
This is the direction a user hits when a collaborator is ahead of them, and the message is
the only actionable output. Produce it by hand:
1. Copy the `.rsbank` from §1 to a scratch name.
2. Open the copy in a hex editor. Bytes 03 are `RSBK`; bytes 47 are `formatVersion`
little-endian; bytes **811** are `minReaderVersion` little-endian.
3. Change byte **8** from `01` to `02`, and byte **4** from `01` to `02` (a writer cannot
require a reader newer than the format it wrote — leaving `formatVersion` at 1 makes
the file incoherent and it will be refused as malformed instead, which is a different
cell). Save.
4. Import the edited copy.
Read off — the message box, all four lines:
```
Cannot import this bank package.
It was written by ReaSampler <the version noted at the top> and needs package format 2 or newer.
This build (<the same version>) reads package format 1.
Nothing was imported. Install ReaSampler <the same version> or newer and try again.
```
- The writer version named is the one **this** build stamped in §1 (the hex edit does not
touch the semver), so the second and fourth lines will name your own version. That is
expected — what is being verified is that all three facts are present and the box
appears at all.
- **No** new bank, **no** new files in the bank folder, **no** undo point.
## 6. The truncated-download refusal is a different message
Copy the §1 package again and delete the last few hundred bytes (any hex editor, or
`head -c` / `fsutil` — the exact count does not matter as long as the file is shorter).
Import it.
Read off:
- The message box reads exactly: `This file is not a readable bank package (corrupt or
truncated). Nothing was imported.`
- It is **not** the §5 message. Crossing these two is the failure this cell exists to
catch — "install a newer build" does not fix a partial download.
- No new bank, no new files.
## 7. Corruption in the middle is caught before anything lands
Copy the §1 package again and flip a single byte **well past the halfway point** (inside a
payload, not the header). Import it.
Read off:
- The message box names the offending entry:
`This bank package is damaged (entry "<name>" failed its integrity check). Nothing was
imported.`
- The bank folder gained **no** files at all — not even the entries before the damaged
one. Verification runs to completion before the first write, so a damaged package costs
no rollback.
## 8. The unsaved-project refusals
- On B, File → New Project (do not save). Try to import. Read off:
`Save the project before importing a bank package -- an unsaved project has no bank
folder to import into.` The file picker must **not** have opened first.
- On A, in an unsaved project with no bank, try to export. Read off the console:
`ReaSampler export: save the project first -- an unsaved project has no bank folder to
read from.`
## 9. Drag-and-drop reaches the same verb
On B, drag a `.rsbank` from the file manager onto the docked ReaSampler panel.
Read off: the same import box as §2, and the same new bank. A `.rsbank` is a whole bank,
not audio — it must never land as an item in the arrange view.
---
## Recording the result
For each section, record **pass**, **fail with the string actually seen**, or **not
exercised**. §2 and §4 are the load-bearing ones: they are the only cells in this document
that involve a real machine boundary, and no unit test can stand in for them.
+154
View File
@@ -0,0 +1,154 @@
# DAW verification — track-scope capture over a multi-track selection
What a DAW pass must establish for the multi-track track capture, and the exact numbers
or strings to read off. Nothing below can be closed by a unit test: every item depends on
what REAPER actually does with a render request.
**Build to use.** Release, installed into `UserPlugins/`, REAPER restarted — extensions
load at startup only. Set the docked panel's tail toggle to **None** before every cell;
Auto adds an 8 s window and Manual a fixed one, and both would invalidate the frame-count
readings.
**Project to use.** One saved project, project sample rate pinned to 48000. Two audio
tracks, `A` and `B`, each holding one item at least 30 s long, with *audibly different*
content (a tone on `A`, a drum loop on `B`). One folder track `F` with `A` and `B` as its
children, used only in §5.
---
## 1. The regression floor — single-track track capture is unchanged
Select **track `A` only**. Make a time selection from **10.000 s to 12.000 s**. Run
*ReaSampler: capture selected track(s)*.
Read off:
- A file appears in the project's bank folder, and one new card appears on the panel.
- The card's length reads **2.000 s**; its frame count is **96000** (`round(12.0 × 48000)
round(10.0 × 48000)`). The backend refuses the capture with `BoundsMismatch` if the
render is more than one frame off that, so a landed capture already proves the number
to ±1 — what you are confirming here is that it landed at all.
- The REAPER console shows **no** `ReaSampler capture failed:` line.
- Track `A` is still the only selected track afterwards.
- **Content, not just length.** Listen to the landed file. `A` and `B` carry *audibly
different* content by the project setup above (tone vs. drum loop), so this is a by-ear
check, not a null test: the capture must be the tone alone, with **no** drum-loop bleed.
Expected: pure tone, matching `A` soloed. Failing: any trace of `B`'s drum loop audible
in the file. This is not a tautology check — the SDK header's own `RENDER_SETTINGS` line
admits a second reading, `(&(1|2)==0)=master mix`, under which a single-track track
capture could render the **whole master mix** (both `A` and `B`) rather than `A` alone;
drum-loop bleed here is exactly what that misreading would produce, and this is the
cheapest place in the whole doc to catch it.
**This is the byte-identical floor.** If either cell now refuses, the change is wrong —
the refusal must fire only above one track.
## 2. The defect cell — two selected tracks now refuse
Select **`A` and `B` together**. Time selection 10.00012.000 s. Run *capture selected
track(s)*.
Read off:
- The console prints exactly:
`ReaSampler capture failed: A track capture renders the selected tracks through the
master, and more than one track cannot land as a single file. Capture one track at a
time, or route them into a folder/bus track and capture that (a folder's own output is
its children summed).`
- **No** new card on the panel, and **no** new `.wav` in the bank folder (check the folder
directly — a stray file with nothing indexing it would mean the refusal fired too late).
- `A` and `B` are both still selected, both still unmuted, and neither track's fader, pan,
or FX-bypass state changed. The refusal returns before any guard is constructed, so
there should be nothing to restore — this reading is what confirms that.
Repeat with a **razor area spanning both tracks** and no time selection: identical
readings. Note that the track *selection* is what the refusal counts — a razor over two
tracks with only `A` selected is a one-track capture and must still succeed (§1).
## 3. The decisive observation — what `&128` actually writes
**This is the one that retires an inference, and it is the reason `docs/TODO.md` still
carries an entry.** The refusal in §2 rests on reading the SDK header's single-file bit
`&(4<<16)` as applying to item/razor sources only, never to `&128` — so N selected tracks
are believed to produce N files. That has never been observed.
Drive REAPER's own Render dialog by hand, with the extension out of the loop:
1. Select `A` and `B`.
2. File → Render. **Source:** *Selected tracks via master* — the dialog wording for `&128`
(SDK header ~3041). Do **not** pick *Stems (selected tracks)* — that is `&2`, a
different source bit that unambiguously writes one file per track and would confirm
nothing about `&128`.
**Bounds:** *Custom time range*, 10.000 to 12.000 s.
3. **File name:** a literal stem with **no wildcards at all** — e.g. `stemprobe`. Clear
`$track` / `$item` / anything else from the pattern; the extension writes exactly one
literal stem, so the probe must too.
4. Render to an empty scratch folder.
Read off — **the file count in that folder**:
- **Two files** (however REAPER disambiguated them, or one file that visibly got
overwritten): the inference holds, the §2 refusal is correct, and the `docs/TODO.md`
entry can be closed by writing this observation into `src/shell/capture/CLAUDE.md` as
fact.
- **One file containing `A` and `B` summed** (confirm by ear, or by nulling it against a
master render of the same range with only `A` and `B` unmuted): the inference is wrong,
the §2 refusal costs a working capture, and the track-scope half should be narrowed back
per the `docs/TODO.md` entry. The item-scope half stays either way.
Also record **what REAPER named the files** — that decides whether a future correct
multi-track capture could ever be built on this source at all.
## 4. Recapture replays the same answer
Take a **single-track** track capture that carries provenance (capture a range on `A`
whose source item is itself a bank sample, so `detectParent` fires), select its card, and
run *re-capture from source*. It must regenerate — same audio, same 96000 frames.
Then construct the multi-track case: a recorded recipe whose `trackGuids` names two
tracks. The reachable way to get one is to have captured it before this change; if no such
entry exists in any project, record that this cell was **not exercised** rather than
inventing one. When it is exercised, read off:
- `ReaSampler re-capture failed:` followed by the **same** message text as §2.
- The bank entry is untouched — same file, same hash, same card.
## 5. The way out actually works
Route `A` and `B` into folder `F`. Select **`F` only**, time selection 10.00012.000 s,
capture track scope.
Read off: one card, 2.000 s, and the audio contains **both** `A` and `B`. This is what the
refusal message tells the user to do, so it has to be true.
## 6. Realtime still accepts a multi-track selection
Select `A` and `B`. Run *ReaSampler: capture selected track(s) in realtime* over the same
range. Read off: **one** card, and its audio contains both tracks. Realtime taps each
source track with a send into one temp track, so it sums where the offline render cannot —
the divergence from §2 is deliberate and this cell is what confirms it is real.
## 7. Mono collapse — what is and is not reachable
Capture a range on a track whose content is dead-center (a mono source panned center, or
a duplicated-channel file), using time selection **10.000 s to 12.000 s** (2.000 s, 96000
frames at 48000 Hz — the §1 convention, so the resulting file size is exact). The panel has
no channel-count readout anywhere (`Sample::channelCount` is not drawn by
`src/shell/panel/panel_render.cpp`), so read the proxy instead:
- Check the landed `.wav`'s size on disk (Explorer → Properties, or a directory listing). A
successful collapse is the extension's own rebuild — canonical 44-byte header + 96000 ×
4 bytes = **384,044 bytes**. A file near double that (~768,044 bytes, plus whatever
REAPER's own render adds for `bext`/metadata chunks) means the collapse did not fire —
recheck the source is genuinely dead-center before treating this as a defect.
- The console shows **no** `the lossless mono collapse ... already reached the bank; only
the size win from the collapse was lost.` line.
**Not DAW-reachable:** the collapse's *failure* branch. It fires only if the captured file
cannot be read, or its temporary rewrite cannot be written or renamed, inside the same
call that just rendered the file — there is no manual way to inject that fault between the
render and the rename. The branch is covered only at its reporting seam
(`tests/test_wav_codec.cpp`, `testCollapseOutcomeSuffixesAreDistinctStrings`), and its console line
has never been seen in a running REAPER. If you ever do see it, the render already reached
the bank — the report only tells you the collapse's size win was lost, not that the bytes
were verified (see `docs/TODO.md`'s 0-byte-render entry).
+33 -1
View File
@@ -10,7 +10,13 @@ add_library(reaper_reasampler MODULE
${REASAMPLER_SRC_DIR}/shell/capture/capture.cpp
${REASAMPLER_SRC_DIR}/shell/capture/capture_orchestrator.cpp
${REASAMPLER_SRC_DIR}/shell/capture/capture_batch.cpp
${REASAMPLER_SRC_DIR}/shell/capture/bake_land.cpp
${REASAMPLER_SRC_DIR}/shell/capture/bake_landing.cpp
${REASAMPLER_SRC_DIR}/shell/capture/scope_resolve.cpp
${REASAMPLER_SRC_DIR}/shell/capture/render_selection.cpp
${REASAMPLER_SRC_DIR}/shell/capture/render_isolation.cpp
${REASAMPLER_SRC_DIR}/shell/capture/render_bounds_gate.cpp
${REASAMPLER_SRC_DIR}/shell/capture/render_in_place.cpp
${REASAMPLER_SRC_DIR}/shell/capture/realtime_lifecycle.cpp
${REASAMPLER_SRC_DIR}/shell/capture/capture_realtime_shell.cpp
${REASAMPLER_SRC_DIR}/shell/capture/capture_realtime_finalize.cpp
@@ -21,6 +27,7 @@ add_library(reaper_reasampler MODULE
${REASAMPLER_SRC_DIR}/shell/panel/panel_audition.cpp
${REASAMPLER_SRC_DIR}/shell/panel/panel_bank_ops.cpp
${REASAMPLER_SRC_DIR}/shell/panel/panel_drag.cpp
${REASAMPLER_SRC_DIR}/shell/panel/footer_input.cpp
${REASAMPLER_SRC_DIR}/shell/panel/panel_input.cpp
${REASAMPLER_SRC_DIR}/shell/panel/panel_layout.cpp
${REASAMPLER_SRC_DIR}/shell/panel/panel_render.cpp
@@ -32,6 +39,8 @@ add_library(reaper_reasampler MODULE
${LICE_SRC}
${REASAMPLER_SRC_DIR}/shell/capture/insert.cpp
${REASAMPLER_SRC_DIR}/shell/view/view.cpp
${REASAMPLER_SRC_DIR}/shell/view/view_fx_park.cpp
${REASAMPLER_SRC_DIR}/shell/view/view_solo.cpp
${REASAMPLER_SRC_DIR}/shell/capture/track_guid.cpp
${REASAMPLER_SRC_DIR}/shell/capture/provenance_shell.cpp
${REASAMPLER_SRC_DIR}/shell/capture/item_read.cpp
@@ -39,14 +48,37 @@ add_library(reaper_reasampler MODULE
${REASAMPLER_SRC_DIR}/shell/actions/design_view_actions.cpp
${REASAMPLER_SRC_DIR}/shell/actions/bank_actions.cpp
${REASAMPLER_SRC_DIR}/shell/actions/prune_action.cpp
${REASAMPLER_SRC_DIR}/shell/actions/package_export_action.cpp
${REASAMPLER_SRC_DIR}/shell/actions/ingest.cpp
${REASAMPLER_SRC_DIR}/shell/actions/arrange_drop_win.cpp
${REASAMPLER_SRC_DIR}/shell/actions/drag_out_win.cpp
${REASAMPLER_SRC_DIR}/shell/actions/instrument_drop_win.cpp
${REASAMPLER_SRC_DIR}/shell/actions/insert_fx_action.cpp
${REASAMPLER_SRC_DIR}/shell/persist/usage_scan.cpp
)
target_link_libraries(reaper_reasampler PRIVATE json wire file_bytes bank_model capture_paths peaks bank_grid mode_switch tab_strip view_mode_model view_tree guid_diff lane_keys insert_plan render_settings batch_capture tail_control capture_realtime bank_book wav_codec owned_manifest prune_reconcile prune_button app_version provenance drag_out instrument_drop theme component_geometry action_bar footer_bar overflow_menu mode_enable tooltip card_meta card_drag assignment_request bank_sync sample_usage)
target_link_libraries(reaper_reasampler PRIVATE json wire file_bytes bank_model capture_paths capture_name peaks bank_grid mode_switch tab_strip view_mode_model view_tree guid_diff lane_keys solo_cache insert_plan render_settings render_window track_topology batch_capture tail_control capture_realtime bank_book wav_codec origin_ledger tracking_authority prune_reconcile prune_button app_version provenance drag_out instrument_drop theme component_geometry action_bar footer_bar overflow_menu mode_enable insert_fx_enable tooltip card_meta card_drag assignment_request bank_sync sample_usage bake_wire resample_name export_bank package_pickers)
# NOT linked here, deliberately: sampler_core / pitch_shift / the filter / limiter. The
# instrument renders its own bake in its own process, which is what keeps the extension's
# link graph free of the voice engine a link edge to it here means the design drifted.
target_include_directories(reaper_reasampler PRIVATE ${SDK_INC} ${WDL_INC})
# The park surface's decisions are pure (header-inline, no REAPER types), so they are
# CTest-covered like a core/ module: the snapshot trust test, the refusal message and
# its once-per-changed-set gate, and the apply's undo-point fold. Declared here rather
# than in a src/shell/view/CMakeLists.txt because that directory deliberately has none
# its TUs are compiled into this target directly. view_mode_model is linked for
# makeParkPlan, the flag set the trust test folds over; pinning that against hand-built
# ops would not catch a change to the planner.
reasampler_test(view_fx_park LINK fx_offline view_mode_model)
# Bank-package import: the promptless verb plus its action skin. Kept as its own
# appended block rather than merged into the lists above, so the two package
# directions stay textually independent.
target_sources(reaper_reasampler PRIVATE
${REASAMPLER_SRC_DIR}/shell/package/import_bank.cpp
${REASAMPLER_SRC_DIR}/shell/actions/package_import_action.cpp)
target_link_libraries(reaper_reasampler PRIVATE import_landing package_pickers)
# OUTPUT_NAME is channel-derived; the CMake target name stays "reaper_reasampler" for both
# configs, since REAPER dlopen's any reaper_* module and the two channels' artifacts load
# side-by-side. LIBRARY_OUTPUT_DIRECTORY pins the module to the top of the build tree even
+60 -4
View File
@@ -26,9 +26,15 @@
#include "shell/actions/action_registry.h" // the registration table
#include "shell/actions/bank_actions.h" // multi-bank action family
#include "shell/actions/design_view_actions.h" // Design View action family
#include "shell/actions/insert_fx_action.h" // insert-as-FX action body
#include "shell/actions/package_export_action.h" // bank-package export action body
#include "shell/actions/package_import_action.h" // bank-package import action body
#include "core/wire/bake_wire.h" // kBakeActionSuffix (the shared action id)
#include "shell/capture/bake_land.h" // resample-bake landing action body
#include "shell/capture/capture_batch.h" // batch + recapture action bodies
#include "shell/capture/capture_orchestrator.h" // single-capture / realtime / insert action bodies
#include "shell/capture/realtime_lifecycle.h" // in-flight realtime state + tick driver
#include "shell/capture/render_in_place.h" // render-in-place action body
#include "shell/panel/panel_input.h" // bankPanelRefresh / bankPanelNotifyProjectLoaded
#include "shell/panel/panel_window.h" // panel lifecycle (init/toggle/open-query/shutdown)
#include "shell/persist/session.h" // ReaSamplerSession
@@ -81,11 +87,18 @@ static void RunCaptureItemAssign(int) { capture::RunCaptureItemAssign(g_session)
static void RunInsertSelected(int arg) {
capture::RunInsertSelected(g_session, arg != 0);
}
// Placement of the PLAYER, not of an item: adds a ReaSampler 9000 to the selected track's
// FX chain. Sessionless — it reads the panel's selection, exactly like the drag it mirrors.
static void RunInsertAsFx(int) { reasampler::doInsertAsFx(); }
static void RunBatchCaptureItems(int) { capture::RunBatchCaptureItems(g_session); }
static void RunBatchCaptureRazor(int) { capture::RunBatchCaptureRazor(g_session); }
static void RunCaptureRealtime(int) { capture::RunCaptureRealtimeTrack(g_session); }
static void RunCancelRealtime(int) { capture::RunCancelRealtime(g_session); }
static void RunRecaptureFromSource(int) { capture::RunRecaptureFromSource(g_session); }
static void RunRenderTrackInPlace(int) { capture::RunRenderTrackInPlace(g_session); }
static void RunResampleBake(int) { capture::RunResampleBake(g_session); }
static void RunExportBankPackage(int) { reasampler::doBankPackageExport(g_session, g_session.book().activeBankId()); }
static void RunImportBankPackage(int) { reasampler::doImportBankPackage(g_session); }
static void RunShowVersion(int) {
// On-demand only — no unconditional startup print (routine console chatter pops
// the console window).
@@ -116,6 +129,12 @@ static std::vector<reasampler::ActionTableRow> buildMainActionTable() {
rows.push_back({"INSERT_SELECTED_CONFORM",
"insert selected sample at edit cursor (conform to tempo)",
&RunInsertSelected, 1});
// A LOAD_*, not an INSERT_*: INSERT_SELECTED/_CONFORM place a timeline item;
// this loads an instrument onto a track's FX chain. The id is permanent, so
// keeping the two apart here is the most durable statement of which verb this is.
rows.push_back({"LOAD_INSTRUMENT_ON_TRACK",
"insert selected sample as ReaSampler 9000 on the selected track",
&RunInsertAsFx});
// One action fires N captures (per selected item / per razor area); the original
// selection is restored on every exit path. Bank-only, never places.
rows.push_back({"CAPTURE_BATCH_ITEMS",
@@ -131,6 +150,21 @@ static std::vector<reasampler::ActionTableRow> buildMainActionTable() {
&RunCancelRealtime});
rows.push_back({"RECAPTURE_FROM_SOURCE", "re-capture from source",
&RunRecaptureFromSource});
// A RENDER_*, not a CAPTURE_*: the id is permanent and is the most durable
// statement the codebase makes about which pillar a feature belongs to.
rows.push_back({"RENDER_TRACK_IN_PLACE",
"render selected track to a new track (source moves to Design)",
&RunRenderTrackInPlace});
// Invoked by a ReaSampler 9000 instance over the VST3 host bridge (and bindable, so a
// stranded request can be landed by hand). The suffix is the wire contract itself —
// core/wire/bake_wire owns the spelling both artifacts read.
rows.push_back({reasampler::wire::kBakeActionSuffix,
"land pending ReaSampler 9000 resample bake",
&RunResampleBake});
rows.push_back({"EXPORT_BANK_PACKAGE", "export active bank as package",
&RunExportBankPackage});
rows.push_back({"IMPORT_BANK_PACKAGE", "import bank package (.rsbank)",
&RunImportBankPackage});
rows.push_back({"SHOW_VERSION", "show version", &RunShowVersion});
return rows;
@@ -146,7 +180,13 @@ static void OnTimer()
// the idle fast-path is a SINGLE POINTER TEST — drive only when a capture is live.
if (capture::g_rtCapture) capture::DriveRealtimeCapture(g_session);
g_session.poll();
// poll()'s undo/redo-reload and project-switch Load branches call
// loadFromProject, replacing g_session.view() wholesale — deferred here while
// an applyMode is on the stack (reachable if a pumped message loop re-enters
// this timer mid-apply), same retry-next-tick shape as the consume guard below.
// Deferred WHOLE, not just the reload branches: poll()'s identity tracking is
// cheap to skip for one tick and resumes correctly, unlatched, on the next.
if (!reasampler::modeApplyInProgress()) g_session.poll();
// persist stays MODEL-ONLY (loads the saved view model but does not apply
// visibility, to avoid coupling persist to the view shell); poll() raises a
@@ -155,7 +195,11 @@ static void OnTimer()
// signal re-arms the bank panel's new-content detector — notified BEFORE the
// reapply so re-arm and model restore ride the one load event (otherwise
// pre-existing tracks can be mis-detected as "new" and mass-tagged).
if (g_session.consumeLoadSignal()) {
// modeApplyInProgress is tested BEFORE the consume, not after the applyMode call:
// the load signal is one-shot, a re-entered applyMode fails closed, and a reapply
// dropped here is the saved mode never applied at all. Holding the whole block
// back one tick also keeps the panel re-arm ahead of the reapply.
if (!reasampler::modeApplyInProgress() && g_session.consumeLoadSignal()) {
reasampler::bankPanelNotifyProjectLoaded();
// Reconcile lane ownership against the live project's lanes (P_LANENAME,
// the cross-session source of truth) BEFORE reapplying visibility. Never
@@ -207,8 +251,8 @@ static project_config_extension_t g_projectConfig{
nullptr, // userData
};
// REAPER calls this for EVERY action fired anywhere; claim only our own id, return
// false otherwise so REAPER keeps looking. This TU's own family dispatches through
// REAPER calls this for every action fired in the MAIN section; claim only our own id,
// return false otherwise so REAPER keeps looking. This TU's own family dispatches through
// the registration table; the other families claim their own ids after it.
static bool OnHookCommand(int command, int /*flag*/)
{
@@ -220,6 +264,16 @@ static bool OnHookCommand(int command, int /*flag*/)
return false;
}
// "hookcommand" covers the main section only, so actions we published into another
// section arrive here instead. Partitioning contract: root `CLAUDE.md` §"REAPER
// extension contract".
static bool OnHookCommand2(KbdSectionInfo* /*sec*/, int command, int /*val*/, int /*val2*/,
int /*relmode*/, HWND /*hwnd*/)
{
if (command == 0) return false;
return reasampler::ingestHandleSectionCommand(command);
}
// REAPER polls this to render each of OUR actions' checked state in menus/toolbars.
// Return 1 (on) / 0 (off) for ids we own, -1 for everything else (per the contract).
static int OnToggleAction(int command)
@@ -246,6 +300,7 @@ extern "C" REAPER_PLUGIN_DLL_EXPORT int REAPER_PLUGIN_ENTRYPOINT(
g_rec->Register("-projectconfig", (void*)&g_projectConfig);
g_rec->Register("-toggleaction", (void*)&OnToggleAction);
g_rec->Register("-hookcommand", (void*)&OnHookCommand);
g_rec->Register("-hookcommand2", (void*)&OnHookCommand2);
reasampler::designViewUnregisterActions(g_rec);
reasampler::bankUnregisterActions(g_rec);
reasampler::ingestUnregisterActions(g_rec);
@@ -298,6 +353,7 @@ extern "C" REAPER_PLUGIN_DLL_EXPORT int REAPER_PLUGIN_ENTRYPOINT(
reasampler::ingestRegisterActions(rec, &g_session);
rec->Register("hookcommand", (void*)&OnHookCommand);
rec->Register("hookcommand2", (void*)&OnHookCommand2);
// Drives project-load / Save-As detection: the timer polls the active project
// each tick; on a project load it reloads the bank from ext state, on a Save-As
+2
View File
@@ -10,8 +10,10 @@ add_subdirectory(wire)
add_subdirectory(audio)
add_subdirectory(model)
add_subdirectory(capture)
add_subdirectory(tracking)
add_subdirectory(reclaim)
add_subdirectory(version)
add_subdirectory(package)
add_subdirectory(view)
add_subdirectory(ui)
add_subdirectory(instrument)
+42 -2
View File
@@ -45,12 +45,15 @@ Detail specific to these pure modules:
## Modules
- `wav_codec` — chunk walker + layout parse + float32 build + size-field patch + content hashes; the single pure RIFF/WAV owner (`wav_trim` is retired; `wav_codec` is the sole owner).
- `wav_codec` — chunk walker + layout parse + float32 build + size-field patch + the lossless mono collapse + content hashes; the single pure RIFF/WAV owner (`wav_trim` is retired; `wav_codec` is the sole owner).
- `capture_realtime` (`core/capture`, **renamed from `realtime_record` in Q-W3** — the Q-9 naming rider: pure module takes the stem, the shell takes the suffix, matching `drag_out`/`drag_out_win`) — the M8 realtime-record pure logic: capture scope + FX-tap point → `I_RECMODE`/`I_RECMODE_FLAGS` values, wet/dry → tap point, the recorded-file → `Sample` mapping, and the async record-phase state machine. Depends on `bank_model` for the plain `Sample`/`SourceMode` types. The transport/temp-track/send recipe lives in the shell (`shell/capture/capture_realtime_shell.cpp` + `capture_realtime_finalize.cpp`).
- `batch_capture` — pure batch-capture planner: maps source ranges to capture units and aggregates results.
- `capture_paths` — the REAPER-free path arithmetic behind offline capture: bank-subfolder + unique-filename derivation (`deriveBankPaths`, forward-slash form, no filesystem touch), the absolute-render-dir vs. project-relative-index-path split (`BankPaths`), the persist-side inverse (`resolveBankFile`, `projectDirOfRpp`), the Save-As bank-relocation plan (`deriveRelocationPlan`), and the GUID-primary project-identity classifier (`classifyProjectTransition``NoOp`/`Load`/`SaveAsRelocate`) the persist-poll timer drives.
- `capture_name` — the REAPER-free composition of one capture's label + file-stem base from its source-track name(s), a local-calendar discriminator (`MM-DD HHMM`, from the shell's clock read), and an optional batch ordinal. The label and the stem deliberately diverge: the stem still passes through `capture_paths::sanitizeStem` (so a name that sanitizes to nothing files as `capture`), while the label keeps the source name verbatim. Stem uniqueness stays entirely `makeUniqueTag`'s — this module never disambiguates.
- `insert_plan` — the REAPER-free logic behind the `insert` shell (M6): computes the `InsertMedia` `mode` bitmask from an `InsertOptions` struct (placement target, tempo-conform ratio, preserve-pitch flag), guaranteeing the &4 stretch-to-time-selection bit is never set and that no tempo bits are set when `conform == None`.
- `render_settings` — the REAPER-free logic behind the capture action family: `SourceMode``RENDER_SETTINGS` bit mapping, `P_RAZOREDITS` string parsing + range-union bounds, razor-else-time range inference, the FX-scope bypass plan (`fxBypassPlanFor`), the tail-mode → `RENDER_TAILFLAG`/`RENDER_NORMALIZE`/`RENDER_TRIMEND` mapping (`tailRenderSettingsFor`) and its realtime-window analog (`realtimeRecordWindowEnd`), and the capture-action taxonomy table (`captureActionTable`) `main.cpp` iterates to register the CAPTURE_ITEM/CAPTURE_TRACK family.
- `render_settings` — the REAPER-free logic behind the capture action family: `SourceMode``RENDER_SETTINGS` bit mapping, `P_RAZOREDITS` string parsing + range-union bounds, razor-else-time range inference, the FX-scope bypass plan (`fxBypassPlanFor`), the one bounds mode a capture hands its window over on (`kRenderBoundsTimeSelection`) and the tail bit paired with it (`kTailFlagTimeSelection`), the tail-mode → `RENDER_TAILFLAG`/`RENDER_NORMALIZE`/`RENDER_TRIMEND` mapping (`tailRenderSettingsFor`) and its realtime-window analog (`realtimeRecordWindowEnd`), the capture-action taxonomy table (`captureActionTable`) `main.cpp` iterates to register the CAPTURE_ITEM/CAPTURE_TRACK family, and `renderSourceLabel` (the source named in the offline backend's bounds refusal).
- `render_window` — the REAPER-free frame arithmetic behind exact capture bounds: `frameCountFor` (the frame count a project-time window occupies at the project rate — the number the offline backend checks the rendered file against before landing it, so a render that printed something other than the window is refused rather than banked), `renderHonoredBounds` (the gate's verdict and the sole home of its one-frame tolerance, which is empirical rather than proven — the header states which renderer models it covers and which it does not), and `itemExtentPrintsWindow`, the predicate `render_settings::sourceModeForScope` consults to decide whether REAPER's selected-items render source can express a requested window at all. It also owns the one short-render diagnostic: `msFlooredEndFrameCount` (the frames a window holds with its end floored to the millisecond — the shape two live short renders matched on the retired custom-bounds mode, quoted by a refusal as a count coincidence and nothing more) and `isOnMillisecondGrid`, the whole-millisecond tolerance that count depends on.
- `track_topology` — the REAPER-free folder arithmetic over a project's flat `I_FOLDERDEPTH` delta list: `directChildIndices` names a folder parent's DIRECT children, the set `shell/capture/render_isolation` silences so a ranged item capture does not print its track's children. Grandchildren are excluded by construction — they reach the parent only through the child that owns them.
- `tail_control` — the REAPER-free logic behind the docked `bank_panel`'s tail-mode toggle: the cycle order (None → Auto → Manual → None), the Manual-length clamp/scroll-wheel fine-adjust (`clampManualMs`/`adjustManualMs`, 250 ms/notch, 2000 ms default), the toggle's label text (e.g. "Tail: Manual 2.0s"), and the `TailSetting` JSON round-trip persist stores per-project.
## Gotchas
@@ -60,9 +63,46 @@ Detail specific to these pure modules:
(`reaper_plugin_functions.h` lines ~3041/~3047/~3051/~3062) — re-verify
against the header before changing any bit value, per the root `CLAUDE.md`
API-verification rule.
- **The selected-items render source (`&32`) cannot narrow a window** — REAPER
derives that render's bounds from the selected items' own extents, so
`RENDER_BOUNDSFLAG=0` + `RENDER_STARTPOS`/`RENDER_ENDPOS` do not constrain it.
This is an inference from the observed defect (a time selection inside a long
item captured the whole item), NOT a header-confirmed fact. It is why
`sourceModeForScope` routes item scope to `&32` only when the item extent
already IS the requested window — do not re-point item scope unconditionally at
`&32`, and do not widen the `&32` branch to windows it cannot express. This is the
one home for that inference; the sites that act on it point here rather than
restating it.
- **The re-source changes the CONTENT, not the FX scope.** `fxBypassPlanFor` is keyed
on `CaptureScope`, so a ranged item capture still hears take/item FX only — but the
selected-tracks source prints everything upstream of the track. The shell answers
that with a transient silencing (`shell/capture/render_isolation`) whose child-set
walk lives here in `track_topology`; the item-vs-track asymmetry behind it is in
`src/shell/capture/CLAUDE.md`.
- **The custom-time-bounds field floors the render window to the millisecond; the
time selection does not.** Both observations and why only one bounds mode is
reachable: `render_settings.h`'s `kRenderBoundsTimeSelection` — the one narrative
home; this bullet is a pointer, not a retelling. Do not reintroduce
`RENDER_BOUNDSFLAG=0`.
- `kRenderPreFaderStems` (&8192) is deliberately **not** used — REAPER offline
render has no true pre-FX "dry" bit; FX scoping is done entirely by the
FX-bypass-around-render mechanism, never by a render bit.
- **The mono collapse changes a capture's content identity, by design.**
`hashWavContent` covers the `fmt ` body plus the `data` payload, and the collapse
rewrites both — so a collapsed capture does NOT hash-dedup against a stereo twin of
the same audio already in the bank. Accepted: the predicate is deterministic over
deterministic bytes, so repeats of the same request still dedup against each other,
which is what the bit-identical-repeats invariant actually asks for. Do not "fix"
this by hashing pre-collapse — that would make two entries with different audio
layouts share one identity.
- **The collapse's minimal rebuild also drops `bext`/iXML/LIST — a source-position
consequence, not only a hashing one.** REAPER's renderer writes a `bext` time
reference, and REAPER's own import paths can position an item at that BWF timestamp,
so a collapsed capture loses it while a declined (non-collapsed) capture from the same
action keeps it — two captures from one action behave differently on re-import.
`shell/capture/insert.cpp` is unaffected (it drives `SetEditCurPos` + `InsertMedia`
rather than reading BWF), so this is not a defect in the shipped insert path.
Accepted, not verified against a DAW re-import: `[verify — DAW]`.
- `tail_control`'s `kDefaultManualTailMs`/`kManualStepMs` and
`render_settings`'s `kMaxTailMs`/`kAutoTrimThresholdDb` are separate constants
in separate files by design (panel-facing default/step vs. runaway-guard cap)
+11
View File
@@ -1,12 +1,23 @@
reasampler_pure_library(capture_paths SOURCES capture_paths.cpp)
reasampler_test(capture_paths LINK capture_paths)
reasampler_pure_library(capture_name SOURCES capture_name.cpp)
# capture_paths: the stem base's real contract is that sanitizeStem keeps it legal, so the
# name tests assert the composed stem THROUGH the sanitizer rather than in isolation.
reasampler_test(capture_name LINK capture_name capture_paths)
reasampler_pure_library(insert_plan SOURCES insert_plan.cpp)
reasampler_test(insert_plan LINK insert_plan)
reasampler_pure_library(render_settings SOURCES render_settings.cpp LINK PUBLIC bank_model)
reasampler_test(render_settings LINK render_settings)
reasampler_pure_library(render_window SOURCES render_window.cpp)
reasampler_test(render_window LINK render_window)
reasampler_pure_library(track_topology SOURCES track_topology.cpp)
reasampler_test(track_topology LINK track_topology)
reasampler_pure_library(batch_capture SOURCES batch_capture.cpp)
reasampler_test(batch_capture LINK batch_capture)
+104
View File
@@ -0,0 +1,104 @@
// capture_name — pure implementation. See the header.
#include "core/capture/capture_name.h"
#include <cstdio>
namespace reasampler::capture {
namespace {
// A track name padded with spaces would render ragged in the label and as underscores in
// the stem, so both ends are trimmed before anything else looks at it.
std::string trimmed(const std::string& s) {
std::size_t b = 0;
std::size_t e = s.size();
auto isSpace = [](unsigned char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
};
while (b < e && isSpace(static_cast<unsigned char>(s[b]))) ++b;
while (e > b && isSpace(static_cast<unsigned char>(s[e - 1]))) --e;
return s.substr(b, e - b);
}
// Truncating mid-sequence would put invalid UTF-8 into the persisted label, so the cut
// backs off over continuation bytes (10xxxxxx). The stem does not care — sanitizeStem
// replaces every non-ASCII byte anyway — but one rule for both keeps them the same name.
std::string truncateUtf8(const std::string& s, std::size_t maxBytes) {
if (s.size() <= maxBytes) return s;
std::size_t cut = maxBytes;
while (cut > 0 && (static_cast<unsigned char>(s[cut]) & 0xC0) == 0x80) --cut;
return s.substr(0, cut);
}
int clampTo(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
} // namespace
std::string formatCaptureStamp(const CaptureStamp& stamp) {
if (stamp.month < 1 || stamp.day < 1) return {};
char buf[24];
std::snprintf(buf, sizeof(buf), "%02d-%02d %02d%02d",
clampTo(stamp.month, 1, 12), clampTo(stamp.day, 1, 31),
clampTo(stamp.hour, 0, 23), clampTo(stamp.minute, 0, 59));
return buf;
}
CaptureName composeCaptureName(const CaptureNameInputs& in) {
std::string base;
int named = 0;
for (const std::string& raw : in.sourceNames) {
const std::string n = trimmed(raw);
if (n.empty()) continue;
if (base.empty()) base = n;
++named;
}
if (base.empty()) base = trimmed(in.fallback);
if (base.empty()) base = "capture";
base = truncateUtf8(base, kMaxSourceNameBytes);
// truncateUtf8 backs off over continuation bytes, so a name whose first kMaxSourceNameBytes
// bytes are ALL continuation bytes (0x80-0xBF) backs off to nothing — re-apply the "never an
// empty label" fallback after truncation, not just before it.
if (base.empty()) base = "capture";
CaptureName out;
out.label = base;
out.stemBase = base;
// Several sources collapse onto the first one's name plus a count of the rest — the
// alternative (joining every name) produces a stem no one can read and a label that
// no longer fits a card.
if (named > 1) {
const std::string extra = std::to_string(named - 1);
out.label += " +" + extra;
out.stemBase += "+" + extra;
}
if (in.ordinal > 0) {
const std::string ord = std::to_string(in.ordinal);
out.label += " #" + ord;
out.stemBase += "-" + ord;
}
const std::string stamp = formatCaptureStamp(in.stamp);
if (!stamp.empty()) out.label += " " + stamp;
return out;
}
std::string captureTrackName(const std::string& sourceName) {
const std::string prefix(kCaptureTrackPrefix);
// A source with no readable name yields the bare word rather than a trailing
// space; both spellings are fixed points, which is what makes the whole function
// one (a track named exactly "Capture" must not become "Capture Capture"). Read
// from kCaptureTrackPrefixBare rather than chopped off prefix, so the two names
// can't drift out of sync with each other (both expand from the same header token).
const std::string bare = kCaptureTrackPrefixBare;
if (sourceName.empty()) return bare;
if (sourceName == bare) return sourceName;
if (sourceName.rfind(prefix, 0) == 0) return sourceName;
return prefix + sourceName;
}
} // namespace reasampler::capture
+84
View File
@@ -0,0 +1,84 @@
#pragma once
// capture_name — the REAPER-free composition of one capture's label and file-stem base
// from its source-track name(s), a local-calendar discriminator, and an optional batch
// ordinal. The shell reads the names and the clock; the SHAPE of a capture's name is
// decided here so it is testable without a DAW.
#include <cstddef>
#include <string>
#include <vector>
namespace reasampler::capture {
// The capture's own moment, already broken down into LOCAL calendar fields by the shell.
// Passing fields rather than an epoch is what keeps the format deterministic under test:
// an epoch would render differently per machine timezone. month < 1 or day < 1 means
// "no stamp" and suppresses the discriminator entirely.
struct CaptureStamp {
int month = 0; // 1-12
int day = 0; // 1-31
int hour = 0; // 0-23
int minute = 0; // 0-59
};
// Longest source-name prefix kept in either the label or the stem. Real track names sit
// far under it; the bound exists so a pathological name cannot push the rendered file
// path toward the platform's limit, and so a label and its file still read as the same
// name.
inline constexpr std::size_t kMaxSourceNameBytes = 64;
struct CaptureNameInputs {
// Source-track names in source order — the first non-empty one names the capture,
// the rest only contribute the "+N" multi-source marker.
std::vector<std::string> sourceNames;
CaptureStamp stamp;
// Batch unit ordinal; <= 0 for a single capture.
int ordinal = 0;
// The scope literal ("item"/"track"/"realtime"), used ONLY when no source name
// resolved at all — otherwise the source name wins.
std::string fallback = "capture";
};
struct CaptureName {
// Sample::displayName. Legible, carries the source name verbatim, and is explicitly
// NOT unique (core/model/CLAUDE.md §resample_name) — the stamp serves the eye.
std::string label;
// deriveBankPaths' baseName. Still passes through sanitizeStem, and stem uniqueness
// is still entirely makeUniqueTag's job.
std::string stemBase;
};
// "MM-DD HHMM" (e.g. "08-01 1432"); empty when the stamp carries no calendar date.
// Year is deliberately omitted: the card and the browse list are narrow, and Sample
// carries the full createdTimestamp for anything needing the exact moment.
std::string formatCaptureStamp(const CaptureStamp& stamp);
CaptureName composeCaptureName(const CaptureNameInputs& in);
// The single source of truth for the word itself — kCaptureTrackPrefixBare and
// kCaptureTrackPrefix below both expand from this one token, so editing it can never
// desync captureTrackName's "no readable source name" bare-word fallback from the
// separator-terminated prefix it is derived from.
#define REASAMPLER_CAPTURE_TRACK_WORD "Capture"
// The bare word behind kCaptureTrackPrefix, needed by captureTrackName's
// no-readable-source-name fallback.
inline constexpr const char* kCaptureTrackPrefixBare = REASAMPLER_CAPTURE_TRACK_WORD;
// Prefixed onto a source track's name to name the track a render-in-place created.
// A display convention, not a persisted key — unlike a lane prefix or an action-id
// suffix, changing it later strands nothing.
inline constexpr const char* kCaptureTrackPrefix = REASAMPLER_CAPTURE_TRACK_WORD " ";
// The new track's name for a render of `sourceName`. IDEMPOTENT — a fixed point on
// its own output, so a second render over a result track yields "Capture MONEY"
// again rather than "Capture Capture MONEY". A counter suffix is deliberately not
// offered: REAPER does not uniquify track names either, and what distinguishes two
// renders of one source is their position, not their name.
std::string captureTrackName(const std::string& sourceName);
} // namespace reasampler::capture
+22 -12
View File
@@ -45,16 +45,25 @@ std::string sanitizeStem(const std::string& baseName) {
return out;
}
BankPaths deriveBankPaths(const std::string& projectDir,
const std::string& baseName,
const std::string& uniqueTag) {
const std::string dir = normalizeSlashes(projectDir);
RenderPaths deriveRenderPaths(const std::string& absoluteDir,
const std::string& baseName,
const std::string& uniqueTag) {
std::string stem = sanitizeStem(baseName);
if (!uniqueTag.empty()) {
stem += "_" + sanitizeStem(uniqueTag);
}
const std::string fileName = stem + ".wav";
RenderPaths r;
r.fileStem = stem; // stem only — REAPER appends the extension
r.fileName = stem + ".wav";
r.absoluteDir = normalizeSlashes(absoluteDir);
return r;
}
BankPaths deriveBankPaths(const std::string& projectDir,
const std::string& baseName,
const std::string& uniqueTag) {
const std::string dir = normalizeSlashes(projectDir);
// Precondition: caller must resolve a non-empty project directory — an
// empty one would otherwise fall back to a bare relative path (forbidden).
@@ -62,18 +71,19 @@ BankPaths deriveBankPaths(const std::string& projectDir,
// ignores it fails at the render/stat step, not silently onto CWD.
assert(!dir.empty() && "deriveBankPaths: projectDir must not be empty");
const RenderPaths r = deriveRenderPaths(
dir.empty() ? std::string{} : dir + "/" + kBankSubfolder, baseName, uniqueTag);
BankPaths p;
p.fileStem = stem; // stem only — REAPER appends extension
p.fileName = fileName;
p.relativePath = std::string(kBankSubfolder) + "/" + fileName;
p.absoluteDir = dir.empty() ? std::string{}
: dir + "/" + kBankSubfolder;
p.fileStem = r.fileStem;
p.fileName = r.fileName;
p.relativePath = bankRelativeForName(r.fileName);
p.absoluteDir = r.absoluteDir;
return p;
}
std::string bankRelativeForName(const std::string& fileName) {
if (fileName.empty()) return {};
// Same expression deriveBankPaths uses, so the two spellings can't drift.
return std::string(kBankSubfolder) + "/" + fileName;
}
+23 -3
View File
@@ -36,9 +36,29 @@ std::string normalizeSlashes(const std::string& path);
// "capture" if nothing usable remains. Deterministic.
std::string sanitizeStem(const std::string& baseName);
// Derives the bank paths for one capture: baseName is the sanitized file-stem
// source, uniqueTag an optional sanitized disambiguator (timestamp/counter) so
// repeated captures don't collide. Produces "<stem>[_<tag>].wav".
// Where one render writes, with no index spelling at all: the directory REAPER is
// told to render into plus the stem/file name it produces there. `absoluteDir` is
// taken as given (normalized only) rather than derived, because a render that never
// enters the bank has no bank subfolder to append — the render-in-place verb points
// this at the project's own recording path.
struct RenderPaths {
std::string absoluteDir; // RENDER_FILE (forward slash, no trailing slash)
std::string fileName; // <stem>.wav
std::string fileStem; // <stem> (RENDER_PATTERN — REAPER appends the extension)
};
// The file-stem spelling for one render: baseName is the sanitized file-stem source,
// uniqueTag an optional sanitized disambiguator (timestamp/counter) so repeated
// renders don't collide. Produces "<stem>[_<tag>].wav". THE one owner of that
// spelling — deriveBankPaths is expressed over it, and bankRelativeForName depends
// on the bank's spelling never drifting from it.
RenderPaths deriveRenderPaths(const std::string& absoluteDir,
const std::string& baseName,
const std::string& uniqueTag);
// Derives the bank paths for one capture: the same stem spelling as
// deriveRenderPaths, in the bank subfolder, plus the project-relative path the
// index stores.
BankPaths deriveBankPaths(const std::string& projectDir,
const std::string& baseName,
const std::string& uniqueTag);
+55 -5
View File
@@ -30,7 +30,7 @@ TailRenderSettings tailRenderSettingsFor(TailMode mode, double manualTailMs) {
// postprocessing bit clear. A fixed-threshold trim scales/limits/fades
// nothing, so identical requests trim at the identical sample -> holds
// the bit-identical-repeats invariant.
t.tailFlag = kTailFlagCustomBounds;
t.tailFlag = kTailFlagTimeSelection;
t.tailMs = kMaxTailMs;
t.normalize = kNormalizeTrimEnd;
t.trimEnd = autoTrimEndRatio();
@@ -38,7 +38,7 @@ TailRenderSettings tailRenderSettingsFor(TailMode mode, double manualTailMs) {
case TailMode::Manual:
// Clamped to the cap regardless of source; negative floors to 0.
t.tailFlag = kTailFlagCustomBounds;
t.tailFlag = kTailFlagTimeSelection;
t.tailMs = std::clamp(manualTailMs, 0.0, kMaxTailMs);
t.normalize = kNormalizeDisableAll;
t.trimEnd = 0.0;
@@ -100,12 +100,62 @@ RenderSettingsChoice renderSettingsFor(SourceMode mode, double /*wetDry*/) {
return c;
}
SourceMode sourceModeForScope(CaptureScope scope) {
void applySecondPassRenderSettings(const bool secondPass, RenderSettingsChoice& choice) {
if (secondPass) { choice.settings |= kSecondPassRender; }
}
const char* renderSourceLabel(SourceMode mode) {
switch (mode) {
// MasterMix and TimeSelection share this label because they ARE the same
// render — see the header.
case SourceMode::MasterMix:
case SourceMode::TimeSelection: return "master mix";
case SourceMode::SelectedTracks: return "selected tracks via master";
case SourceMode::SelectedItems: return "selected media items";
case SourceMode::RazorArea: return "razor edits";
case SourceMode::Realtime: return "realtime record";
}
return "unknown"; // unreachable for a valid enum; never claim a source
}
SourceMode sourceModeForScope(CaptureScope scope, bool itemExtentIsWindow) {
switch (scope) {
case CaptureScope::Item: return SourceMode::SelectedItems;
case CaptureScope::Item:
return itemExtentIsWindow ? SourceMode::SelectedItems
: SourceMode::SelectedTracks;
case CaptureScope::Track: return SourceMode::SelectedTracks;
}
return SourceMode::SelectedItems; // unreachable for a valid enum; fail closed
// Unreachable for a valid enum; fail closed to the time-bounded render, which
// honors the requested bounds whatever the selection is.
return SourceMode::SelectedTracks;
}
bool isMultiTrackStemRender(SourceMode mode, int sourceTrackCount) {
return mode == SourceMode::SelectedTracks && sourceTrackCount > 1;
}
std::string multiTrackRefusalMessage(CaptureScope scope) {
// Deliberately does not name realtime capture as a way out, though it is the one
// action that sums correctly here: realtime is non-deterministic (hardware/performed
// FX, no bit-identical-repeats guarantee), so pointing an offline refusal at it would
// trade one invariant for another rather than just naming a substitute. A stated
// choice, not an oversight.
switch (scope) {
case CaptureScope::Item:
return "This range is narrower than the selected items, so it renders "
"through their tracks -- and those items span more than one track, "
"which this shape cannot land as a single file. Capture one track's "
"items at a time, or make the range match the items' extent.";
case CaptureScope::Track:
return "A track capture renders the selected tracks through the master, "
"and more than one track cannot land as a single file. Capture one "
"track at a time, or route them into a folder/bus track and capture "
"that (a folder's own output is its children summed).";
}
// Unreachable for a valid enum; a refusal with no way out is still better than a
// silent one, so fail closed to the scope-agnostic half of the message.
return "This selection spans more than one track, which cannot land as a single "
"file. Capture one track at a time.";
}
RangeSource inferRangeSource(bool hasRazorArea) {
+79 -13
View File
@@ -1,8 +1,9 @@
#pragma once
// render_settings — the REAPER-free logic behind the capture action family:
// sourceMode -> RENDER_SETTINGS bits, P_RAZOREDITS parsing + range union,
// razor-else-time inference, the FX-scope bypass plan, and the capture-action
// table main.cpp iterates. Bit MEANINGS below are transcribed verbatim from
// razor-else-time inference, the FX-scope bypass plan, the capture-action
// table main.cpp iterates, and the multi-track-stem refusal + its user-facing
// message text. Bit MEANINGS below are transcribed verbatim from
// reaper_plugin_functions.h; the CHOICE of which bits each mode sets is tested.
#include <string>
@@ -19,6 +20,7 @@ inline constexpr int kRenderMasterMix = 0; // (&(1|2))==0, no sour
inline constexpr int kRenderSelItems = 32; // &32 selected media items
inline constexpr int kRenderSelItemsViaMaster = 64; // &64 selected media items via master
inline constexpr int kRenderSelTracksViaMaster = 128; // &128 selected tracks via master
inline constexpr int kSecondPassRender = 2048; // &2048 2nd Pass Render
inline constexpr int kRenderRazorEdits = 4096; // &4096 render razor edits
// kRenderPreFaderStems (&8192) is deliberately NOT used — REAPER offline render
// has no true pre-FX "dry" bit. FX scoping is done by the FX-bypass-around-render
@@ -26,17 +28,34 @@ inline constexpr int kRenderRazorEdits = 4096; // &4096 render razor e
// render wet; the scope decides which FX remain enabled.
inline constexpr int kRenderSingleFile = (4 << 16); // items/razor -> one file
// --- Render bounds mode -------------------------------------------------------
//
// A capture hands its window over on RENDER_BOUNDSFLAG=2 — the project's own TIME
// SELECTION (value verbatim, header ~3042), written through GetSet_LoopTimeRange.
//
// Custom time bounds (RENDER_BOUNDSFLAG=0, RENDER_STARTPOS/RENDER_ENDPOS, header
// ~3045-3046) must NOT be reintroduced: REAPER resolved a custom-bounds window on a
// whole-millisecond grid AT RENDER TIME, floored the end, wrote the floored value back
// over RENDER_ENDPOS, and rendered exactly the floored frame count — twice, to the
// frame. Re-rendering on this mode came back exact on both edges, including a start
// carrying a sub-millisecond remainder, which is what locates the floor in the
// custom-bounds field rather than downstream in the render engine. This is the one
// narrative home for that; other sites point here.
inline constexpr int kRenderBoundsTimeSelection = 2;
// --- Tail: RENDER_NORMALIZE / RENDER_TRIMEND bits + named constants ----------
//
// Every offline capture renders custom-time-bounds, so &1 (RENDER_TAILFLAG,
// header ~3047) is the only tail-flag bit that ever applies. RENDER_NORMALIZE
// (verbatim, header ~3051): &32768 = trim ending silence (Auto path);
// &(4<<16) = disable all render postprocessing (None/Manual path).
// RENDER_NORMALIZE (verbatim, header ~3051): &32768 = trim ending silence (Auto
// path); &(4<<16) = disable all render postprocessing (None/Manual path).
inline constexpr int kNormalizeTrimEnd = 32768; // &32768 trim ending silence
inline constexpr int kNormalizeDisableAll = (4 << 16); // &(4<<16) = 262144, disable all
inline constexpr int kTailFlagNone = 0;
inline constexpr int kTailFlagCustomBounds = 1; // &1, header ~3047
inline constexpr int kTailFlagNone = 0;
// RENDER_TAILFLAG's bits are keyed PER BOUNDS MODE (header ~3047): &4 is the
// time-selection mode's bit, the pair of kRenderBoundsTimeSelection above. A tail set
// under a different mode's bit renders no tail at all, so these two move together.
inline constexpr int kTailFlagTimeSelection = 4;
// Auto-trim trailing-silence threshold; single source of truth (RENDER_TRIMEND
// ratio derives from this dB, never the reverse). Daniel-set.
@@ -64,7 +83,7 @@ enum class TailMode {
// normalize bit is set (Auto). The backend reads these straight onto
// GetSetProjectInfo.
struct TailRenderSettings {
int tailFlag = kTailFlagNone; // RENDER_TAILFLAG (0 or &1)
int tailFlag = kTailFlagNone; // RENDER_TAILFLAG (0 or the bounds mode's bit)
double tailMs = 0.0; // RENDER_TAILMS
int normalize = kNormalizeDisableAll; // RENDER_NORMALIZE
double trimEnd = 0.0; // RENDER_TRIMEND (only used when trim bit set)
@@ -95,6 +114,20 @@ struct RenderSettingsChoice {
// SelectedItems -> &32|single-file; RazorArea -> &4096|single-file.
RenderSettingsChoice renderSettingsFor(SourceMode mode, double wetDry);
// Apply the 2nd Pass Render setting to the RENDER_SETTINGS block
void applySecondPassRenderSettings(const bool secondPass, RenderSettingsChoice& choice);
// The render source a mode drives, in words. Exists for the offline backend's
// bounds refusal: the two ways a render can miss its window — a source that
// derives its own bounds (selected items, razor edits) versus a time-bounded
// render that came up short — are indistinguishable from a frame count alone,
// and naming the source is what tells them apart in a bug report.
//
// MasterMix and TimeSelection deliberately answer the SAME words: they map to the
// same RENDER_SETTINGS value and render identically, so naming them apart would
// assert a render distinction that does not exist.
const char* renderSourceLabel(SourceMode mode);
// --- Capture scope: the FX-scope invariant ------------------------------------
//
// See src/core/capture/CLAUDE.md for the scope contract. There is NO master
@@ -105,9 +138,42 @@ enum class CaptureScope {
Track,
};
// The render source mode each scope drives. Item captures selected items, Track
// captures selected tracks (via master).
SourceMode sourceModeForScope(CaptureScope scope);
// The render source mode each scope drives. Track scope always captures its
// selected tracks (via master), time-bounded by RENDER_STARTPOS/ENDPOS.
//
// Item scope captures the selected items ONLY when `itemExtentIsWindow` — i.e.
// when those items' own extent already prints the requested window (see
// render_window::itemExtentPrintsWindow). REAPER's selected-items render source is
// INFERRED to derive its bounds from the item extents, so a window strictly inside
// (or wider than) a selected item cannot be expressed through it; that case renders
// time-bounded through the items' own tracks. The inference is unverified — see
// src/core/capture/CLAUDE.md §Gotchas for what it rests on.
//
// The FX SCOPE is unaffected by the swap (fxBypassPlanFor is keyed on CaptureScope,
// not on the source mode, so an item capture still hears take/item FX only), but the
// CONTENT reaching the render is not: the selected-tracks source prints everything
// upstream of the track — its folder children and its receives — which the shell
// transiently silences (shell/capture/render_isolation). An overlapping item on the
// track ITSELF is deliberately not isolated; see src/shell/capture/CLAUDE.md.
SourceMode sourceModeForScope(CaptureScope scope, bool itemExtentIsWindow);
// True for the one render shape that cannot land as a single capture: a selected-tracks
// render covering more than one track — a ranged item capture whose items span several
// tracks, or any multi-track track capture. That source is read as rendering one file
// per selected track — the single-file bit is documented for item/razor sources only
// (SDK header ~3041), which is the whole basis for the reading and is DAW-unverified.
// If it holds, N tracks collapse N stems onto one literal render pattern and whichever
// file survived would land as a successful capture carrying one track's audio. The
// caller refuses instead.
//
// Scope is deliberately NOT a parameter: the exposure comes from the render SOURCE,
// which both scopes reach.
bool isMultiTrackStemRender(SourceMode mode, int sourceTrackCount);
// The refusal text for the shape above. Keyed on scope because only the way OUT differs:
// an item capture can also widen its range to the items' own extent, which a track
// capture has no analog for. Kept beside the predicate so the two read as siblings.
std::string multiTrackRefusalMessage(CaptureScope scope);
// --- Range inference: razor-else-time (orthogonal to scope) -------------------
//
@@ -170,7 +236,7 @@ RazorRange razorUnionBounds(const std::vector<RazorRange>& ranges);
struct CaptureActionDef {
const char* commandSuffix; // e.g. "CAPTURE_TRACK" — FOREVER-STABLE (composed w/ prefix)
const char* descriptionPhrase; // e.g. "capture selected track(s)" — Actions-list phrase
const char* baseName; // file-stem base for this capture
const char* baseName; // file-stem FALLBACK; the source track normally names the capture
CaptureScope scope; // FX scope (item / track)
};
+61
View File
@@ -0,0 +1,61 @@
// render_window.cpp — see the header.
#include "core/capture/render_window.h"
#include <cmath>
namespace reasampler::capture {
namespace {
// Round-to-nearest: the convention THIS module measures a window by, so a mid-frame
// position maps to the closer frame boundary rather than always down. Not a claim
// about how any renderer resolves that position -- see the header's caveat.
long long frameIndexAt(double seconds, int sampleRate) {
return std::llround(seconds * static_cast<double>(sampleRate));
}
// See the header for why whole milliseconds get a tolerance and why it is this small.
double floorToMilliseconds(double seconds) {
const double ms = seconds * 1000.0;
if (isOnMillisecondGrid(seconds)) return std::nearbyint(ms) / 1000.0;
return std::floor(ms) / 1000.0;
}
} // namespace
long long frameCountFor(double startSeconds, double endSeconds, int sampleRate) {
if (sampleRate <= 0) return 0;
if (!(endSeconds > startSeconds)) return 0;
const long long frames =
frameIndexAt(endSeconds, sampleRate) - frameIndexAt(startSeconds, sampleRate);
return frames > 0 ? frames : 0;
}
bool renderHonoredBounds(long long expectedFrames, long long actualFrames) {
const long long delta = actualFrames > expectedFrames
? actualFrames - expectedFrames
: expectedFrames - actualFrames;
return delta <= 1;
}
bool itemExtentPrintsWindow(double reqStart, double reqEnd,
double itemStart, double itemEnd,
int sampleRate) {
if (sampleRate <= 0)
return reqStart == itemStart && reqEnd == itemEnd;
return frameIndexAt(reqStart, sampleRate) == frameIndexAt(itemStart, sampleRate)
&& frameIndexAt(reqEnd, sampleRate) == frameIndexAt(itemEnd, sampleRate);
}
bool isOnMillisecondGrid(double seconds) {
const double ms = seconds * 1000.0;
return std::fabs(ms - std::nearbyint(ms)) < 1e-6;
}
long long msFlooredEndFrameCount(double startSeconds, double endSeconds,
int sampleRate) {
return frameCountFor(startSeconds, floorToMilliseconds(endSeconds), sampleRate);
}
} // namespace reasampler::capture
+75
View File
@@ -0,0 +1,75 @@
#pragma once
// render_window — pure frame arithmetic for a capture's requested window: the frame
// count a project-time range occupies, whether a render whose bounds come from the
// selected items' own extent already prints that window, and the one diagnostic a
// refused render quotes — whether its shortfall matches a millisecond-floor coincidence.
// NO REAPER types; unit-tested by tests/test_render_window.cpp.
namespace reasampler::capture {
// Frames the [startSeconds, endSeconds) window occupies at `sampleRate`. Both
// edges are resolved to the NEAREST frame boundary and subtracted, so the answer
// is a difference of frame indices rather than a rounded duration — two windows
// of equal length at different offsets can legitimately differ by one frame.
// Returns 0 for a non-positive rate or an empty/inverted window.
//
// The offline backend compares this against the rendered file's own frame count, so
// exact-bounds failures surface as a refused capture rather than a wrong file.
long long frameCountFor(double startSeconds, double endSeconds, int sampleRate);
// True when a landed render's frame count is consistent with `frameCountFor`'s
// answer for the same window. Tolerates a one-frame difference, and exactly one.
//
// That bound is EMPIRICAL. It is provable only for renderer models that derive the
// count from the window's LENGTH (floor/ceil/round of (end-start)*rate) or resolve
// both edges by the SAME convention; a renderer that resolves the start edge and the
// end edge by DIFFERENT conventions can legitimately sit TWO frames from this answer
// (tests/test_render_window.cpp pins both facts). Which model REAPER uses is
// unverified, so a refusal one or two frames wide may be this gate's fault rather than
// the render's. Widening past one frame retires the exact-bounds invariant rather than
// relaxing it, and is not a fix to reach for before that question is answered.
bool renderHonoredBounds(long long expectedFrames, long long actualFrames);
// True when a render bounded by the selected items' own extent
// [itemStart, itemEnd) already prints exactly the requested
// [reqStart, reqEnd) window — the one case where REAPER's selected-items render
// source is believed to need no correction (the bounds-override inference behind
// that is unverified; src/core/capture/CLAUDE.md §Gotchas states what it rests on).
// Compared at frame resolution, because a sub-frame difference prints the same
// frames. An unknown rate (<= 0) falls back to exact equality, which can only send
// a window to the time-bounded render, never widen one.
bool itemExtentPrintsWindow(double reqStart, double reqEnd,
double itemStart, double itemEnd,
int sampleRate);
// --- Diagnostics: where a short render lost its frames ------------------------
// The frames this window would hold if its END were resolved on a whole-millisecond
// grid, floored, instead of exactly. That is what REAPER's offline render did on the
// retired custom-time-bounds mode (render_settings.h's kRenderBoundsTimeSelection states
// the whole observation): two live short renders (48 kHz, TailMode::None) printed this
// count to the frame. Kept as the refusal's shape check — a refused render matching it
// says the floor is back, on a mode that was measured escaping it.
//
// Still a DESCRIPTION, never a request: nothing renders from this number and no capture
// path asks for it — a refusal quotes it to say the shortfall has the known shape, which
// is not the same as proving that this particular render took it. Whole-millisecond values
// are recognized within a nanosecond, because a decimal millisecond is not always one
// in binary (1.007 * 1000 lands just below 1007) and a bare floor would drop a
// millisecond from a window already on the grid. A nanosecond is far under one frame
// at any rate we render, so a real sub-millisecond remainder still floors.
//
// The tolerance is ours, not REAPER's: on a `1.007`-class grid point, a REAPER floor
// that does NOT carry the same epsilon would miss this shape entirely, and a real
// floored render would then read as an unmatched short render rather than the known one
// — silence here is not proof the floor didn't happen (docs/TODO.md records why this
// premise needs a DAW measurement before anything is built on it).
long long msFlooredEndFrameCount(double startSeconds, double endSeconds,
int sampleRate);
// True when `seconds` sits on a whole-millisecond boundary, under the nanosecond
// tolerance msFlooredEndFrameCount depends on and for the reason stated there. Public so
// that premise is testable directly rather than only through the count it feeds.
bool isOnMillisecondGrid(double seconds);
} // namespace reasampler::capture
+12 -2
View File
@@ -18,6 +18,10 @@ TailMode cycleTailMode(TailMode current) {
return TailMode::None; // unreachable for a valid enum; fail to the safe default
}
bool toggleSecondPass(bool current) {
return !current; // wow
}
double clampManualMs(double manualMs) {
return std::clamp(manualMs, 0.0, kMaxTailMs);
}
@@ -77,6 +81,7 @@ std::string serializeTailSetting(const TailSetting& setting) {
json::Writer w(out);
w.keyRaw("mode", json::numToStr(modeToInt(setting.mode)));
w.keyRaw("manualMs", json::numToStr(setting.manualMs));
w.keyRaw("secondPass", json::boolToStr(setting.secondPass));
} // Writer closes the object here (see bank_model's NRVO note)
return out;
}
@@ -87,7 +92,8 @@ std::optional<TailSetting> deserializeTailSetting(const std::string& blob) {
int modeInt = 0;
double ms = 0.0;
bool haveMode = false, haveMs = false;
bool secondPass = false;
bool haveMode = false, haveMs = false, haveSecondPass = false;
r.skipWs();
if (!r.consume('}')) {
do {
@@ -99,13 +105,16 @@ std::optional<TailSetting> deserializeTailSetting(const std::string& blob) {
} else if (key == "manualMs") {
if (!r.parseDouble(ms)) return std::nullopt;
haveMs = true;
} else if (key == "secondPass") {
if (!r.parseBool(secondPass)) return std::nullopt;
haveSecondPass = true;
} else {
if (!r.skipValue()) return std::nullopt; // forward-compat
}
} while (r.consume(','));
if (!r.consume('}')) return std::nullopt;
}
if (!haveMode || !haveMs) return std::nullopt; // absent key -> malformed -> default
if (!haveMode || !haveMs || !haveSecondPass) return std::nullopt; // absent key -> malformed -> default
const std::optional<TailMode> mode = modeFromInt(modeInt);
if (!mode) return std::nullopt;
@@ -113,6 +122,7 @@ std::optional<TailSetting> deserializeTailSetting(const std::string& blob) {
TailSetting out;
out.mode = *mode;
out.manualMs = ms;
out.secondPass = secondPass;
return out;
}
+7 -2
View File
@@ -21,14 +21,19 @@ inline constexpr double kManualStepMs = 250.0;
// The panel's current tail setting: mode + the length used only when Manual.
// Default None so a capture with no explicit choice stays exact-bounds.
// `manualMs` is clamped to kMaxTailMs before it ever reaches a CaptureRequest.
// 2nd-Pass Render optional, off by default
struct TailSetting {
TailMode mode = TailMode::None;
double manualMs = kDefaultManualTailMs;
TailMode mode = TailMode::None;
double manualMs = kDefaultManualTailMs;
bool secondPass = false;
};
// Cycles the tail mode: None -> Auto -> Manual -> None.
TailMode cycleTailMode(TailMode current);
// Toggles the 2nd-Pass Render
bool toggleSecondPass(bool current);
// The effective manual length a Manual capture uses: clamped to [0, kMaxTailMs].
// Exposed so the panel can show the clamped value. Meaningful only for Manual.
double clampManualMs(double manualMs);
+62
View File
@@ -0,0 +1,62 @@
// track_topology.cpp — see the header.
#include "core/capture/track_topology.h"
#include <cstddef>
namespace reasampler::capture {
std::vector<int> directChildIndices(const std::vector<int>& folderDepths,
int parentIndex) {
std::vector<int> children;
const int count = static_cast<int>(folderDepths.size());
if (parentIndex < 0 || parentIndex >= count) return children;
if (folderDepths[static_cast<std::size_t>(parentIndex)] != 1) return children;
// Depth relative to the parent: 1 immediately after it (inside its folder), and
// 0 once the folder closes. Only tracks sitting at relative depth 1 are direct
// children; a child that opens its own folder pushes the level to 2, which is
// what excludes its descendants.
int level = 1;
for (int i = parentIndex + 1; i < count && level > 0; ++i) {
if (level == 1) children.push_back(i);
level += folderDepths[static_cast<std::size_t>(i)];
}
return children;
}
SiblingPlacement siblingPlacement(const std::vector<int>& folderDepths, int srcIndex) {
const int count = static_cast<int>(folderDepths.size());
if (count == 0) return SiblingPlacement{};
const int src = srcIndex < 0 ? 0 : (srcIndex >= count ? count - 1 : srcIndex);
// levels[i] is track i's absolute nesting depth; levels[count] is the depth the
// list closes at (0 in a well-formed project). Negative is unrepresentable, so a
// malformed over-closing delta clamps here rather than propagating.
std::vector<int> levels(static_cast<std::size_t>(count) + 1, 0);
for (int i = 0; i < count; ++i) {
const int next = levels[static_cast<std::size_t>(i)] +
folderDepths[static_cast<std::size_t>(i)];
levels[static_cast<std::size_t>(i) + 1] = next < 0 ? 0 : next;
}
const int L = levels[static_cast<std::size_t>(src)];
int p = src + 1;
if (folderDepths[static_cast<std::size_t>(src)] >= 1) {
p = count; // an unterminated folder swallows the rest of the list
for (int j = src + 1; j <= count; ++j) {
if (levels[static_cast<std::size_t>(j)] == L) { p = j; break; }
}
}
SiblingPlacement out;
out.insertIndex = p;
out.precedingIndex = p - 1;
out.precedingDepth = L - levels[static_cast<std::size_t>(p - 1)];
out.newDepth = levels[static_cast<std::size_t>(p)] - L;
return out;
}
} // namespace reasampler::capture
+56
View File
@@ -0,0 +1,56 @@
#pragma once
// track_topology — pure folder arithmetic over a project's track list: which tracks
// are the DIRECT children of a folder parent, and where a new SIBLING of a given
// track goes, both derived from the I_FOLDERDEPTH deltas alone. NO REAPER types
// (the shell reads the deltas); unit-tested by tests/test_track_topology.cpp.
#include <vector>
namespace reasampler::capture {
// Indices of `parentIndex`'s DIRECT children, given every track's I_FOLDERDEPTH in
// track order. I_FOLDERDEPTH is a DELTA applied AFTER its own track (SDK header
// ~2215: 0 = normal, 1 = opens a folder, -n = closes n folders), so the depth walk
// below is the only way to recover the tree from the flat list.
//
// Empty when `parentIndex` is out of range or its track does not open a folder.
// Grandchildren are deliberately excluded: their audio reaches the parent only
// through the direct child that owns them, so a caller silencing each direct child's
// send-to-parent silences the whole subtree. An unterminated folder (no closing
// negative delta) treats every remaining track as inside it, matching REAPER.
std::vector<int> directChildIndices(const std::vector<int>& folderDepths,
int parentIndex);
// Where a new track goes so it is a SIBLING of `srcIndex` — same nesting level, same
// folder — and the two I_FOLDERDEPTH writes that put it there.
struct SiblingPlacement {
int insertIndex = 0; // the index the new track occupies after insertion
// The track that will PRECEDE the new one (insertIndex - 1), and its rewritten
// delta. -1 only for a degenerate empty list, where there is nothing to write.
int precedingIndex = -1;
int precedingDepth = 0;
int newDepth = 0; // the new track's own I_FOLDERDEPTH
};
// Both naive answers are audibly wrong, which is why this is arithmetic and not
// `srcIndex + 1`: inserting straight after a folder PARENT makes the new track that
// folder's first child (its audio re-enters the parent's FX and fader), and inserting
// straight after the folder's LAST track steals that track's closing delta and drops
// the new one outside the folder entirely (its audio bypasses the folder bus).
//
// Levels are absolute nesting depths recovered from the deltas (level[0] = 0,
// level[i+1] = level[i] + depth[i]). A folder parent's insert point is the first
// following track back at the source's own level — i.e. after the whole folder;
// everything else inserts directly below the source. On a well-formed delta list
// (one whose deltas sum to zero) the two writes preserve the total delta sum, so no
// track after the insertion changes level — the malformed case below does not carry
// that guarantee; the clamp keeps the result legal, not level-preserving.
//
// A malformed list (deltas not summing to zero, an out-of-range srcIndex) CLAMPS to
// the nearest legal placement rather than asserting: the failure mode of a corrupt
// project must be a track at the wrong nesting level, never a crash.
SiblingPlacement siblingPlacement(const std::vector<int>& folderDepths, int srcIndex);
} // namespace reasampler::capture
+71
View File
@@ -6,6 +6,7 @@
#include <cstdio> // std::snprintf (hash hex render)
#include <cstring> // std::memcpy, std::memcmp
#include <utility> // std::move
namespace reasampler::capture {
@@ -257,6 +258,76 @@ std::vector<std::uint8_t> buildFloat32Wav(int nch, std::uint32_t rate,
return out;
}
MonoCollapse collapseToMono(const std::vector<std::uint8_t>& bytes) {
MonoCollapse out;
const WavLayout layout = parseWavLayout(bytes);
if (!layout.valid || layout.channelCount < 2) return out;
const std::size_t frames = layout.frameCount();
if (frames == 0) return out;
const std::size_t stride = layout.channelCount;
const std::vector<AudioSample> pcm = extractFloatFrames(bytes, layout, 0, frames);
if (pcm.size() != frames * stride) return out; // short read -> decline, never guess
// Bit patterns, not values: see the header. memcpy is the only defined float->bits
// read, and it compiles to a register move.
auto bitsOf = [](AudioSample s) {
std::uint32_t bits = 0;
std::memcpy(&bits, &s, 4u);
return bits;
};
for (std::size_t f = 0; f < frames; ++f) {
const std::uint32_t first = bitsOf(pcm[f * stride]);
for (std::size_t c = 1; c < stride; ++c) {
if (bitsOf(pcm[f * stride + c]) != first) return out;
}
}
// float -> double -> float round-trips exactly for every finite value and for
// +-0/+-infinity (double represents every float bit pattern in those classes), so
// channel 0 reaches the rebuilt file unaltered. The one hole: a signaling NaN is
// quieted by the float->double promotion, so an identical-bit sNaN pair could
// collapse to a different bit pattern than it started with. Not reachable from
// REAPER-rendered audio, but the bit-identical predicate above admits NaN inputs,
// so this rebuild is not exempt from the claim it makes.
std::vector<double> mono(frames);
for (std::size_t f = 0; f < frames; ++f)
mono[f] = static_cast<double>(pcm[f * stride]);
out.collapsed = true;
out.bytes = buildFloat32Wav(1, layout.sampleRate, frames, mono);
return out;
}
CollapsedWav applyMonoCollapse(std::vector<std::uint8_t> bytes) {
CollapsedWav out;
MonoCollapse collapse = collapseToMono(bytes);
if (collapse.collapsed) {
const WavLayout rebuilt = parseWavLayout(collapse.bytes);
if (rebuilt.valid) {
out.bytes = std::move(collapse.bytes);
out.layout = rebuilt;
out.collapsed = true;
return out;
}
}
out.bytes = std::move(bytes);
out.layout = parseWavLayout(out.bytes);
return out;
}
std::string monoCollapseSuffix(MonoCollapseOutcome outcome) {
switch (outcome) {
case MonoCollapseOutcome::Declined: return {};
case MonoCollapseOutcome::Collapsed: return " (collapsed to mono)";
case MonoCollapseOutcome::Failed:
return " (mono collapse failed -- left as captured)";
}
return {}; // unreachable for a valid enum; claim nothing rather than a wrong outcome
}
std::string hashBytes(const std::uint8_t* data, std::size_t len) {
// FNV-1a 64-bit: deterministic, no dependencies, adequate for dedup identity.
std::uint64_t h = kFnvOffsetBasis;
+62
View File
@@ -90,6 +90,68 @@ std::vector<std::uint8_t> buildFloat32Wav(int nch, std::uint32_t rate,
std::size_t frameCount,
const std::vector<double>& interleaved);
// --- Lossless mono collapse ---------------------------------------------------
// The outcome of the bit-identical mono collapse. `collapsed == false` means the
// caller must leave the source file exactly as it is — it writes nothing.
struct MonoCollapse {
bool collapsed = false;
std::vector<std::uint8_t> bytes; // the rebuilt 1-channel WAV; empty unless collapsed
};
// Collapses a multi-channel float32 WAV to one channel when EVERY channel of EVERY
// frame carries the identical float BIT PATTERN. Bit equality, never an epsilon and
// never `==` on floats: +0.0/-0.0 and two NaNs with differing payloads are NOT
// identical and are never folded. Frame count, sample rate and bit depth are
// preserved — only the interleave stride changes — so the collapse cannot lose
// information, and a lossy downmix (summing differing channels) is not something
// this can express.
//
// Declines for: bytes that do not parse; a file already at one channel; a zero-frame
// file (no frame of evidence to act on); any differing channel pair.
//
// The rebuild is a canonical minimal WAV, so non-audio chunks (a renderer's `bext`
// timestamp, iXML, LIST) do not survive it. That much hashWavContent already skips —
// but the collapse rewrites the `fmt ` body and the `data` payload too, which moves
// the file's content identity; see this directory's CLAUDE.md for what that costs,
// including the bext/source-position consequence beyond hashing.
MonoCollapse collapseToMono(const std::vector<std::uint8_t>& bytes);
// A buffer after the collapse has had its say, PAIRED with the parse of the bytes
// actually returned — so a caller that hashes `bytes`, reads a channel count off
// `layout` and then writes `bytes` cannot describe one buffer while writing another.
struct CollapsedWav {
std::vector<std::uint8_t> bytes; // the rebuilt 1-channel WAV, or the input verbatim
WavLayout layout; // the parse OF `bytes`
bool collapsed = false;
};
// `collapseToMono` over a whole buffer, for a caller that goes on to hash and measure
// the result rather than rewrite a file (`shell/capture`'s collapseCapturedFileToMono is
// the file-side path over the same predicate). Takes the buffer by value: a decline hands
// those same bytes straight back. A rebuild that does not parse back is discarded rather
// than returned, so an invalid `layout` can only ever mean the INPUT was not a usable WAV.
CollapsedWav applyMonoCollapse(std::vector<std::uint8_t> bytes);
// How applying the collapse to a captured FILE ended. `Declined` is collapseToMono's own
// "nothing to do"; `Failed` is a read that never happened or a warranted rewrite that did
// not land. The capture is intact and correctly measured in every case — only the report
// tells them apart, which is why the two must not share one value.
enum class MonoCollapseOutcome {
Declined,
Collapsed,
Failed,
};
// The capture message's collapse suffix — empty for Declined, so a capture that had
// nothing to collapse reads exactly as it did before the collapse existed. Shared by
// both backends so one outcome cannot be reported two ways. NOT user-observable on its
// own: CaptureResult::message on a successful capture is never printed by any caller, so
// the Collapsed/Failed text this returns reaches no one today — the one observable
// channel for a genuine Failed outcome is the backends' own reportCollapseFailure
// console line.
std::string monoCollapseSuffix(MonoCollapseOutcome outcome);
// --- Content identity (dedup hashes) -----------------------------------------
// Deterministic FNV-1a 64-bit content hash over `len` bytes, as 16-char lowercase
+207 -53
View File
@@ -1,16 +1,27 @@
# src/core/instrument — pure VST3-instrument core (engine / map / ui)
# src/core/instrument — pure VST3-instrument core (bake / engine / map / note / param / ui)
## Scope
The ReaSampler 9000 instrument's pure, REAPER-free, VST3-free, unit-tested core, in three
The ReaSampler 9000 instrument's pure, REAPER-free, VST3-free, unit-tested core, in six
subdirectories:
- **`engine/`** — the polyphonic voice engine, the one set of play params, pitch shifting,
velocity curve, and master-gain taper math.
- **`map/`** — the capture resolution + `SampleData` build, the cross-artifact
`ComponentState` codec, and the small pure helpers the engine/shell share
(bank-generation sync, bridge-read marshalling, note-name parsing, Trigger
frame↔fraction conversion).
(bank-generation sync, bridge-read marshalling, note-name parsing, the Trigger
play-span formula).
- **`note/`** — the programmed capture-signal model: musical-division note length, tempo
resolution, and anchored start/end offsets — the one record and resolver the offline bake
and any future editor of it read from, so they cannot diverge.
- **`bake/`** — the resample bake's pure half: the programmed note resolved to a frame
window, the offline render over a voice engine built for that render alone, and the
ratified post-bake reset. See `bake/CLAUDE.md`.
- **`param/`** — what the instrument tells a VST3 host about its automatable parameters,
with no VST3 type in it: the FOREVER-FROZEN id table, the exposed set derived from
`deckParamCommit`, the plain-value layer, and the one formatter per unit category. Sits
ABOVE `ui/` — the list is a function of the commit predicate, never the reverse. See
`param/CLAUDE.md`.
- **`ui/`** — pure editor geometry/hit-test modules (the band-stack allocator and its band
interiors, waveform, keyboard strip, capture browser, param controls, envelope
overlay/edit). These are geometry-and-math only; the LICE draw + REAPER/VST3 plumbing is
@@ -112,18 +123,23 @@ start point, Gate has modifiable loop points too. In addition to amp env, there
pitch envelope/curve (AD?) which is off by default."*
- **Gate — classic held note.** Note-on enters the amp envelope; note-off enters
release; a sustain loop applies for held notes. Envelope is **AHDSR**: `0→1` over
release; a sustain loop applies for held notes, cycling indefinitely until note-off, with a
user-parameterized pre-seam crossfade at the reset (`engine/loop/`). Envelope is **AHDSR**: `0→1` over
attack, hold at 1 over `holdFrames`, `1→sustain` over decay, hold sustain until
note-off, `level→0` over release. `holdFrames == 0` is exactly the pre-Gate ADSR — a
back-compat degenerate.
- **Trigger — one-shot drum-pad.** Note-on fires playback of a defined `%` of sample
length with a fade-in and fade-out ramp; note-off is ignored (the voice plays through,
no sustain loop). Frame span `[startFrame, playEnd)` where `playEnd = startFrame +
round(lengthFraction·(frames startFrame))`; amplitude ramps `0→1` over
`fadeInFrames` at the head and `1→0` over `fadeOutFrames` anchored to `playEnd`; fades
clamp so `fadeInFrames + fadeOutFrames ≤ play length`. Fade curve is equal-power
(constant-power sin/cos). **Note-off in Trigger is a no-op** — choke-on-note-off is
held/out of scope (fork S15-F1).
length; note-off is ignored (the voice plays through, no sustain loop). Frame span
`[startFrame, playEnd)` where `playEnd = startFrame +
round(lengthFraction·(frames startFrame))`. The amplitude over that span is the staged
**AHD** (below), not a fade pair. **Note-off in Trigger is a no-op** — choke-on-note-off
is held/out of scope (fork S15-F1).
> **Superseded, do not reintroduce:** Trigger's amplitude was once a fade-in/unity/
> fade-out shape with its own equal-power curve and its own `fadeInFrames`/`fadeOutFrames`
> pair, clamped so the two fades fit the span. That is retired — one staged-envelope
> design now covers what were two mechanisms. A saved instance's fades lift onto the AHD
> at the codec boundary (attack ← fade-in, decay ← fade-out, hold ← the remainder).
- **Both modes: modifiable start point.** Playback begins at `startFrame` (clamped `0 ≤
startFrame < frames`). Gate additionally has modifiable loop points; Trigger has none.
- **Pitch engine — Varispeed vs Preserve (S16).** Varispeed (current/
@@ -135,12 +151,12 @@ pitch envelope/curve (AD?) which is off by default."*
Contract for Gate's sustain loop under Preserve: *loop the source, shift the output*
(loop points stay source-frame facts). `WDL_Resampler` is **not** a Preserve engine (it
is a resampler that couples duration) — never wire it as the duration-preserving path.
- **Pitch envelope — AD, off by default.** A short attack-decay pitch-offset curve
(`peakSemitones` over `attackFrames`, decaying to 0 over `decayFrames`) riding on top of
whichever pitch engine; a zero attack gives a pure percussive pitch drop. **Off by
default** — a regression that applies pitch modulation when the envelope is disabled is
a bug. Under Varispeed the offset is a per-frame multiply of `ratio_`; under Preserve it
is added to the shifter's shift amount.
- **Pitch envelope — AHD, off by default.** A pitch-offset curve rising to `peakSemitones`
over attack, holding, then decaying to 0, riding on top of whichever pitch engine; a zero
attack gives a pure percussive pitch drop. **Off by default** — a regression that applies
pitch modulation when the envelope is disabled is a bug. Its hold fraction defaults to 0,
which is exactly the attack-decay shape it grew out of. Under Varispeed the offset is a
per-frame multiply of `ratio_`; under Preserve it is added to the shifter's shift amount.
- **Preserve RT discipline.** The shifter pre-warms at voice-allocation; no allocation in
`process()` in steady state. **Note (supersedes an earlier framing):** the
shifter's onset latency (~25 ms, half-window) was once described as "an
@@ -154,6 +170,40 @@ pitch envelope/curve (AD?) which is off by default."*
- **S15/S16 are Tier 01 engine features, not Tier 2/3** — do not let the held Tier-2
feature list (velocity layers / round-robin / filter work) drive their build shape.
### Live parameter delivery — a knob moves the note already sounding (settled 2026-07-30)
Daniel's ruling, verbatim: *"hell no, I was going to bring that up for the other envelopes. We
must live compute, latching the parameters at note on is not acceptable. long term these will be
automatable parameters."* It rejects the precedent, not one instance of it.
- **How a control reaches the audio is ONE decision, recorded in ONE place**`deckParamCommit`
and `liveCommitFor` (`ui/deck_groups`), a THREE-state classification (`Live` /
`NoteOnLatched` / `Reload`) whose header is THE home for where each control sits and why —
see there rather than restating the list here.
- **Ownership sits ABOVE every snapshot.** `SampleData::live` is a NON-OWNING pointer to the one
block the shell owns per instance. The member-ordering constraint that enforces it, and why,
are recorded at `liveParams_` in `shell/instrument/reasampler_processor.h`. A drain voice
tracking the knob is the DESIRED behaviour — it is the note the user is hearing.
- **Null is the bare engine.** `live == nullptr` is byte-identical to the pre-live core, which
is why `sampler_core`'s regression baselines needed no change.
- **Observation is at block boundaries, never per frame.** `VoiceEngine` reads the seqlock once
per `render()` and once per note-on; the per-sample path gained three predicted branches (the
voice's filter-ramp check and each envelope smoother's active check), all false at rest, and
no indirection.
- **A fresh note SNAPS, a sounding one holds φ.** They are different entry points on purpose
(`snapLive` vs `applyLive`): a voice that has rendered nothing has no phase to hold, and the
φ rule reads its stage-0 position under a stale zero-length stage as a completed stage. One
function serving both silently discarded every newly-dialled attack.
- **The mid-stage rule is HOLD NORMALIZED STAGE POSITION** (Daniel's pick among six candidates):
φ = elapsed/duration is held across a stage-time change, so the level is continuous by
construction and the remainder takes its share of the new duration. Stated over normalized
position rather than output level ON PURPOSE, so a per-segment curve exponent composes with
it as a pure map of φ. Recomputing from absolute elapsed (which steps) is the rejected
alternative — do not reintroduce it.
- **Two genuine level steps are smoothed, not ruled away**: a sustain level moved while the
voice holds it, and a stage duration dialled to exactly zero mid-stage. Both are absorbed by
the envelope's own bounded offset smoother.
### Non-goals / guardrails (instrument-specific; repo-wide invariants live in root CLAUDE.md)
- **No cross-platform / multi-format.** Windows-only, VST3-only, REAPER-only (D5). Do not
@@ -165,19 +215,61 @@ pitch envelope/curve (AD?) which is off by default."*
- **Do not spec Tier 2/3** from this directory. Tier 2 is held, Tier 3 is
optional-forever; don't let their feature lists drive Tier 01's build shape.
### Envelope overlay + draggable nodes (S-VIEW, settled 2026-07-27, landed)
### The envelope overlay — one graphical surface, every envelope (S-VIEW, extended)
The amp envelope is drawn as a curve over the Sample view's hero waveform at the shared
time base — Gate → the AHDSR shape, Trigger → the fade-in/unity/%-length/fade-out shape
anchored to `playEnd`. **The overlay is directly editable — draggable nodes
(SETTLED, S-VIEW-F2).** Dragging a node and the existing sliders are two surfaces onto
one model: both read/write the same envelope fields of the one parameter set, so a drag
updates the params, the sliders reflect them live, and a slider edit re-lays the nodes —
one source of truth, structural (re-read-every-paint), not a listener chain. Nodes are
monotonic in time (a node cannot be dragged past its neighbours) and range-clamped to the
same per-param min/max the sliders enforce, so node-drag can never produce a param the
slider couldn't. Two pure modules split the forward (draw) and inverse (edit) maps — see
`envelope_overlay` and `envelope_edit` in Modules below.
The overlay draws ONE envelope over the Sample view's hero waveform, and WHICH one is a
transient editor choice: **clicking anywhere in an envelope deck (amp, pitch, filter) — panel,
knob or button — focuses that deck's overlay**, and the focused deck takes an `AccentPrimary`
border. At most one is overlay-active, and **none is a valid resting state — the editor opens
there**, reached by clicking a control surface outside the three decks. Focus SETS rather than
toggles, so editing the deck you selected cannot deselect it; the overlay itself neither steals
nor clears focus for the same reason. Never persisted; it selects what is drawn, not what is
played. *(The per-deck corner radio this replaced is gone; MASTER keeps the corner slot for its
passive gain-reduction lamp.)*
**The overlay is directly editable — draggable nodes (SETTLED, S-VIEW-F2), plus a round
mid-segment knot per sloped stage that sets that stage's curve exponent.** A node drag, a
knot drag and the deck knobs are surfaces onto ONE model: all three read/write the same
fields of the one parameter set, so an edit on any of them re-lays the others — one source
of truth, structural (re-read-every-paint), never a listener chain. Every drag is
range-clamped to the same per-param min/max the knobs enforce, so no drag can produce a
param a knob couldn't. Two pure modules split the forward (draw) and inverse (edit) maps —
see `envelope_overlay` and `envelope_edit` in Modules below.
**Every envelope is EITHER staged or drawn, and both states persist.** Each of the three
(amp, pitch, filter) carries a `SplineEnv` — a mode plus a contour over NORMALIZED sample time —
beside its staged parameters. Switching modes converts and discards nothing: the inactive state
stays saved but inert, and round-tripping restores the other mode's shape untouched. The
consequences, each with one home:
- **Gate is unavailable while any EG is drawn.** A contour is a pure time function over the full
sample length, which IS the Trigger/one-shot model. `splineActive` (`play_params.h`) is the
predicate; `enforceGateUnavailableWhileDrawn` (`play_params.h`) is the one enforcement of it,
called by both `resolvePlay` (`sample_map.cpp`) on the way to the engine and the editor's
`applyControl`, so the two callers cannot drift. The editor's Gate segment refuses and paints
Disabled off the same `splineActive` predicate.
- **A drawn envelope's staged segment knobs go inert** — drawn-but-dead, never removed, never
hidden — including their inner curve dials, which are reached through their outer cell.
`deckKnobInert` (`ui/deck_groups`) is the one place that list lives. The DEPTH knobs (pitch
peak, filter mod amount) stay live: they scale whichever shape is active.
- **Normalized is what makes a contour length-independent.** There are no stored seconds to
rescale, so a different-length capture replays the same shape proportionally.
- **The contours sit on `PlayParams`/`PlaySeconds` directly, not inside the three envelope
structs.** Those are copied whole into the live block, which must stay trivially copyable
(`live_params.h`) — and a contour is not a live control anyway: like the velocity curves it
travels by reload.
**Which shape a STAGED envelope takes is decided by the play mode, not by what it modulates:**
pitch is always AHD; amp and filter are AHDSR in Gate and AHD in Trigger. Both mode shapes
are STORED per envelope, so flipping modes cannot lose either mode's dialled values (the
migration case forces it: an old instance carries both its AHDSR values and its Trigger
fades, and one shared set could not preserve both modes' prior sound).
**And which LAYOUT an envelope takes follows from whether it has a sustain stage** — the
same rule, applied once: an AHDSR right-anchors its release (the end point is fixed at the
canvas edge and release is dragged from its top node), a sustain-less AHD maps 1:1 onto the
waveform's time axis. The two policies coexist rather than merge; the 1:1 mapping only means
anything for a trigger shape.
### Parameter ownership and persistence (D-B)
@@ -188,54 +280,105 @@ slider couldn't. Two pure modules split the forward (draw) and inverse (edit) ma
reloads** via the instrument's own `ComponentState` (envelope-bumped), never via the
extension's `persist` ext-state module (that would make it project-global rather than
per-instance and leak an instrument concern into the extension's key space).
- **Velocity curve** — the one non-back-compat surface in S-VIEW: an
already-saved instance with no stored curve now plays every velocity at unity under the
flat-default (Option A), not bit-identical to the old linear `velocity/127` mapping —
a deliberate, Daniel-approved behavior change (see `velocity_curve` in Modules).
- **Velocity curves** — three of them (amp, pitch, filter), all per-instance, edited from ONE
deck group. The amp curve is the one non-back-compat surface in S-VIEW: an already-saved
instance with no stored curve now plays every velocity at unity under the flat-default
(Option A), not bit-identical to the old linear `velocity/127` mapping — a deliberate,
Daniel-approved behavior change. The pitch and filter curves are bipolar and off by default
(see `velocity_curve` in Modules).
## Modules
### `engine/`
- The engine is the `sampler_core` CMake target over FOUR headers and TWO TUs, split on its own responsibility seam — cold note routing vs the hot per-sample render:
- `play_params.h` — the value layer: `PlayParams`/`AdsrParams`/`TriggerParams`/`PitchEnvParams`/`FilterParams`, the per-instance mode enums (`ChannelMode`/`VoiceMode`/`MonoTrigger`), and `SampleData` (the ONE loaded capture: decoded PCM + root + loop + start + keyTrack + velocity curve + play params). Shared by the engine, the codec, and the editor, so a UI/codec TU reading a param struct doesn't recompile when a `Voice` member changes. `FilterParams` stores the filter module's own `FilterSettings` by value rather than a parallel copy of its normalized positions.
- `envelopes.h` — the three per-frame evaluators (`AdsrEnvelope` AHDSR, `TriggerEnvelope` fade shape, `PitchEnvelope` AD offset), CONCRETE and fully header-inline. Never give them a common base or a virtual `tick()`: they are called per-voice-per-sample. The filter envelope is a SECOND `AdsrEnvelope` instance on the voice, not a fourth class.
- `voice.h` / `voice.cpp` — one voice. The per-SAMPLE render half (`advanceFrame` and everything it calls) is INLINE IN THE HEADER by RT constraint; the per-NOTE half (note-on setup incl. the Preserve ring prime, legato retune, gate-off, the off-thread shifter presize) is out of line in the TU. The voice owns its own `VoiceFilter` and filter envelope, run between the pitch stage and the amp multiply — see `engine/filter/CLAUDE.md`.
- `play_params.h` — the value layer: `PlayParams`/`AdsrParams`/`TriggerParams`/`PitchEnvParams`/`FilterParams`, the per-instance mode enums (`ChannelMode`/`VoiceMode`/`MonoTrigger`), and `SampleData` (the ONE loaded capture: decoded PCM + root + loop + start + keyTrack + velocity curve + play params). Shared by the engine, the codec, and the editor, so a UI/codec TU reading a param struct doesn't recompile when a `Voice` member changes. `FilterParams` stores the filter module's own `FilterSettings` by value rather than a parallel copy of its normalized positions. Also the ONE home of the drawn-EG rule family — `splineActive`, `effectivePlayMode`, `enforceGateUnavailableWhileDrawn` and `effectiveLengthFraction` — all templated over the frames and seconds representations, so no consumer of either can re-read the raw fields instead.
- `envelopes.h` — the three per-frame evaluators (`AdsrEnvelope` AHDSR, `AhdEnvelope` the sustain-less Attack/Hold/Decay, `PitchEnvelope` the AHD pitch offset), CONCRETE and fully header-inline. Never give them a common base or a virtual `tick()`: they are called per-voice-per-sample. Also home to `fitAhd`/`ahdLevelAt`, THE span split and shape every sustain-less envelope shares. A voice carries two of each shape — the amp's and the filter's — and its play mode picks which pair it reads. `AdsrEnvelope`/`PitchEnvelope` own `applyLive` (the φ-holding mid-stage rule), its fresh-note peer `snapLive`, and `StepSmoother`, the bounded offset that absorbs the level steps φ cannot cover; `AhdEnvelope` is POSITIONAL (evaluated at a source offset, not ticked), so it has no phase to hold and smooths a live reshape instead.
- `live_params.h` / `live_params.cpp` — the live-parameter block: `LiveValues` (the plain, trivially-copyable bundle the audio thread observes), the single-writer `LiveParams` seqlock that publishes it without a lock or a torn read, `foldLive` (the ONE derivation from `PlayParams` — every publisher goes through it so the two representations cannot drift), the block's FIELD-wise `operator==` (never a memcmp — the header owns why the padding makes a byte compare report differences that do not exist), and `ValueRamp`, the per-frame glide whose EXACT termination is what lets the filter's equality-compare cutoff skip re-engage. Links no engine: the block is a value the voice observes, not a thing the engine owns.
- `voice.h` / `voice.cpp` — one voice. The per-SAMPLE render half (`advanceFrame` and everything it calls) is INLINE IN THE HEADER by RT constraint; the per-NOTE half (note-on setup incl. the Preserve ring prime, legato retune, gate-off, the off-thread shifter presize) is out of line in the TU. The voice owns its own `VoiceFilter` and filter envelope, run between the pitch stage and the amp multiply — see `engine/filter/CLAUDE.md`. **Documented ~600-line-ceiling exception** (root `CLAUDE.md` structural heuristic 1): `voice.h` sits over the ceiling because `advanceFrame`'s RT-inline constraint forbids the seam a split would need — a documented exception, not silent overshoot.
- `voice_engine.h` / `voice_engine.cpp``VoiceEngine`: note routing, bounded-stealing allocation, user-parameterized voice count (132, default 16), `VoiceMode` Poly/Mono (last-note held-note stack, `MonoTrigger` Retrigger/Legato), two-tier panic (CC 123 = all-notes-off release, CC 120 = immediate hard-stop including Trigger one-shots), and the block render loops. Preview injects a synthetic note-on at the loaded capture's root note into the main `VoiceEngine` — no dedicated `PreviewCard`; preview obeys polyphony/mono/voice-stealing/envelopes.
- `pitch_shift` — hand-rolled **correlation-aligned SOLA** (splice-overlap-add) pitch shifter for the Preserve playback mode: one active read tap chases the write head at the shift ratio; each splice jump is refined by a cross-correlation search so the new read point is waveform-aligned, then old and new taps are crossfaded (raised-cosine, amplitude-complementary). Replaces the prior dual-tap OLA whose fixed half-window tap offset caused anti-phase cancellation on many source frequencies. **GA2:** ring buffer **primed with the actual upcoming source** at note-on (was zero-filled) → gap-free frame-0 onset, ~25 ms Preserve onset latency eliminated (Preserve now speaks on frame 0, matching Varispeed), and real-content-bounded tail (last-window tail-truncation gone). No third-party dependencies; RT-discipline: no allocation in `process()`.
- `velocity_curve` — pure velocity→amp transfer curve: `VelocityCurve` evaluated by a FritschCarlson monotone cubic Hermite spline (no overshoot outside [0,1]). `eval(velocity)` called once per note-on. `flat()` default (y=1, every velocity→unity) replaces the prior fixed `velocity/127` path — a deliberate non-back-compat behavior change (Daniel-approved).
- `master_gain` — pure dB↔linear taper math (FB1): normalized [0,1] ↔ dB ↔ linear for the post-mixer master gain control (−∞…+24 dB, norm 0 = true silence, unity ≈ 0.714). Shared by the editor knob and the processor multiply so the needle, persisted value, and audio multiply cannot drift.
- `engine/loop/` — the sustain loop's ONE validity/clamp fold (`resolveLoop`) plus its pre-seam crossfade geometry and the editor's default handle span; see `engine/loop/CLAUDE.md`. The voice folds it once at note-on; the crossfade weight is header-inline because it rides the per-sample read.
- `pitch_shift` — hand-rolled **correlation-aligned SOLA** (splice-overlap-add) pitch shifter AND time-stretcher for the Preserve playback mode: one active read tap chases the write head at the shift ratio; each splice jump is refined by a cross-correlation search so the new read point is waveform-aligned, then old and new taps are crossfaded (raised-cosine, amplitude-complementary). Replaces the prior dual-tap OLA whose fixed half-window tap offset caused anti-phase cancellation on many source frequencies. **GA2:** ring buffer **primed with the actual upcoming source** at note-on (was zero-filled) → gap-free frame-0 onset, ~25 ms Preserve onset latency eliminated (Preserve now speaks on frame 0, matching Varispeed), and real-content-bounded tail (last-window tail-truncation gone). No third-party dependencies; RT-discipline: no allocation in `process()`.
- **The WRITE rate (duration) and the TAP rate (pitch) are independent, and that is the whole time-stretcher**`writeFrame` for a surplus source frame, `processNoInput` for a starved output frame, plain `process` for the 1:1 case, `setShiftRatio` for pitch, and `setFeedRate` so the splice crossfade is sized against the real drain rate. The header owns the argument, including why this is not the resampled-read-with-a-cancelling-shift the `WDL_Resampler` invariant above forbids.
- **Splices are PITCH-SYNCHRONOUS when the source's period is known** (`setSourcePeriod`, fed from `period_detect` via the loader): the nominal jump becomes the multiple of that period nearest the window that still fits the ring's jump bound (~1.25 windows), so an aligned landing point sits at the CENTRE of the correlation search instead of possibly not existing inside it at all. The search is unchanged and still earns its keep — it absorbs the jump's rounding to whole frames and tracks a source whose period drifts. **An unknown period restores the fixed-window geometry exactly** (`periodAlignedJump`, `pitch_shift.h`); do not "simplify" that fallback into an approximation of it.
- `period_detect` — the source's own fundamental period, estimated ONCE per load (two-pass YIN:
a decimated cumulative-mean-normalized difference picks the period, the full-rate difference
function refines it to a fraction of a frame), so `pitch_shift`'s splice jump can be a whole
number of it. **Runs off the audio thread by link graph** (`period_detect.h` is the one home
for that invariant) — the same shape as the extension's link graph not gaining the voice
engine. Its one caller is the loader (`map/sample_map`'s
`buildSampleData`), which hands the answer down on `SampleData::sourcePeriodFrames`. A period
is DERIVED from the audio, so it is cache and not state: nothing persists it, and it takes no
rung of the payload ladder. **Answering "none" is a first-class result** — noise, polyphony,
percussion and a source whose period changes mid-sample all return it, and the shifter's
fixed-window geometry is the documented fallback. **Detection analyses the SUSTAIN LOOP when
the capture carries one long enough to host the full search band** (`periodAnalysisSpan`),
otherwise the whole source: the loop is what a Gate voice asymptotically plays, and a phrase
whose head is pitched differently from its sustain would otherwise disagree its way to none.
A shorter loop analyses the whole source rather than a narrowed band — a narrower span may
never buy itself a higher lowest-findable fundamental.
- `time_stretch` — the TIME half beside `pitch_shift`'s PITCH half, header-only: `StretchCursor`, the per-output-frame source-feed schedule (a fractional cursor carrying its rate debt, loop-wrapped), plus the rate bounds and their clamp. Rate 1.0 is exactly one source frame per output frame with no residue, which is what makes the unity Preserve read bit-identical to the pre-stretch engine. The bounds are **measured**, not arbitrary — see the header.
- `velocity_curve` — THE monotone spline, shared by every consumer: the three velocity transfer curves and the three spline EGs. `VelocityCurve` is evaluated as ONE OR MORE FritschCarlson monotone cubic Hermite splines joined at its HARD points — a hard knot is a sub-curve boundary for tangent purposes (exactly what the point array's own ends already are), so the two adjacent segments meet at their natural angle instead of a shared derivative and the no-overshoot guarantee holds PER SEGMENT rather than globally. Points are smooth by default; the ceiling is `kMaxCurvePoints` = 128, a MUSICAL bound (long rhythmic phrases, ~two points per articulation event) and not a performance one — **do not lower it**. `eval(velocity)` is the COLD reader, called once per note-on or once per drawn pixel column; `SplineCursor` is the RT one, an indexed segment search plus one Hermite evaluation with the segment and its tangents cached across samples. Both share the same `segmentTangents`/`hermiteAt` free functions, so there is one spline and not two. It carries its own y `CurveDomain`: UNIPOLAR [0,1] is the amp's GAIN, defaulting to `flat()` (y=1, every velocity→unity — a deliberate non-back-compat replacement of the old fixed `velocity/127` path, Daniel-approved); BIPOLAR [1,1] is the signed modulation shape for pitch and filter, defaulting to `zero()` so velocity modulates neither until a curve is drawn. A bipolar curve does not imply the absence of a depth beside it: the filter keeps its `velAmount` knob and the two compose multiplicatively (`velAmount × curve.eval(v)`, `play_params.h`), while the pitch curve's throw is the fixed `kVelocityPitchRangeSemitones`.
- `master_gain` — pure dB↔linear taper math (FB1): normalized [0,1] ↔ dB ↔ linear for the post-mixer master gain control (−∞…+24 dB, norm 0 = true silence, unity ≈ 0.714). Shared by the editor knob, the processor multiply and the host's `toPlain` so the needle, persisted value, audio multiply and reported dB cannot drift. Math only — the dB label is `param/param_format`'s, so the editor and the host cannot print it two ways.
- `limiter` — the master bus's lookahead brickwall limiter, the stage after `master_gain`'s multiply: a 4x-oversampled TRUE-PEAK detector in the SIDECHAIN ONLY (the signal path is never oversampled), one stereo-linked gain, a baked 0.3 dBTP ceiling and **no makeup gain of any kind**. The gain law is a sliding MINIMUM of the per-sample target over the lookahead window followed by a MOVING AVERAGE of the same width: every term of that average is a minimum whose own window contains the sample being gained, so the ceiling is held **structurally** rather than by a tuned attack, and the one-pole release only ever slows the RISE so that bound survives it. Bypassed and settled, `process()` returns without reading or writing a sample — the byte-identical at-rest path, on the same discipline as `live == nullptr` and the filter's exact skip at `modAmount == 0`. `prepare()` owns every allocation and every transcendental. **Switching is a MUTE, never a blend:** unlimited signal is emitted at weight 1 (the untouched bypass buffer) or at weight 0 and never in between, because a fraction of an unlimited signal is a peak over the ceiling — so the fade always rides the limited path and the hard edge always lands on the bypassed side, against silence. Do not reintroduce an equal-gain dry/wet crossfade over the toggle.
- `meter_ballistics` — the output meter's UI-side ballistics and dB scale: instantaneous rise, 20 dB/s fall, the 1.5 s peak hold and its release at the same rate, the clip latch, and the dB → normalized map over 60…+6 dBFS. The audio thread publishes raw block peaks and converts nothing; this module is what turns them into what the bar draws. Per-channel and stage-agnostic — the MASTER column's own state (both channels plus the gain-reduction lamp) composes it in `ui/master_meter`.
### `map/`
- `sample_map` — the bank blob → selected capture resolve, the channel policy (downmix / dual-mono / L-R split), `InstrumentParams` (the ONE parameter set: root/loop/start overrides, keyTrack, velocity curve, `PlaySeconds`), the single override-beats-intrinsic fold (`resolveCapture`, shared by the bank and refs paths so they cannot drift), and the `SampleData` build. **Wall-clock times stored as rate-free SECONDS, resolved against the live project rate — NO hardcoded sample rates in `src/`** (Daniel's standing ruling, load-bearing). Deliberately does NOT link the voice engine: the build's product is plain `SampleData`.
- `component_state_io` (`core/instrument/map`) — the `ComponentState` envelope + params-payload binary codec (envelope v1…v11, params payload v1…v9), split out of `sample_map` (Q-W2v, T4-13 ≡ T2-07) so BOTH artifacts can link the codec without the extension pulling in the whole voice engine to serialize one preset blob — the extension's `instrument_drop` and the instrument's processor read/write the identical bytes, so the cross-artifact contract cannot drift. Payload v1…v7 are the RETIRED per-zone lists: still read, lifting by adopting zone one's capture + parameters (that first zone is what the old first-match resolve actually played, so it is also what supersedes the envelope's stored selection id). Payload v9 appends the per-voice filter tail; a v8 blob is a strict prefix of it and lifts to the off/neutral filter default.
- `play_seconds` — the stored, wall-clock-SECONDS value layer (`PlaySeconds` + `AdsrSeconds` / `AhdSeconds` / `PitchEnvSeconds` / `FilterSeconds`), header-only and split from `sample_map` so a consumer that only edits those values reaches them without the bank model and the WAV codec. `resolvePlay`, which turns them into the engine's frame domain, stays with the rest of the mapping.
- `component_state_io` (`core/instrument/map`) — the `ComponentState` envelope + params-payload binary codec (envelope v1…v11, params payload v1…v16), split out of `sample_map` (Q-W2v, T4-13 ≡ T2-07) so BOTH artifacts can link the codec without the extension pulling in the whole voice engine to serialize one preset blob — the extension's `instrument_drop` and the instrument's processor read/write the identical bytes, so the cross-artifact contract cannot drift. Payload v1…v7 are the RETIRED per-zone lists: still read, lifting by adopting zone one's capture + parameters (that first zone is what the old first-match resolve actually played, so it is also what supersedes the envelope's stored selection id). Payload v9 appends the per-voice filter tail; a v8 blob is a strict prefix of it and lifts to the off/neutral filter default. Every tail since is a strict suffix on the same discipline — v10 the staged curves, v11 the loop crossfade, v12 the velocity→pitch curve, v13 the dual Staged/Spline state (the three contours, plus hard-flag tails for the three velocity curves — their v7/v9/v12 blocks are frozen at 16 bytes/point and had no room for a per-point flag), v14 the resample bake's Hold division, v15 the master-bus limiter enable, v16 the playback rate + the baseline pitch offset. v12 also RE-TAGS the y DOMAIN of one frozen slot inside the v9 filter tail — its velocity curve reads bipolar from v12 on, unipolar before — which needs no version branch, because a pre-v12 curve's y values are already valid bipolar ones; every other filter slot, `velAmount` included, keeps its meaning.
- `params_payload` — the PARAMS-PAYLOAD half of that codec, split from the envelope half on the axis the format already has: the payload carries its own version and grows independently, so the two version ladders are two responsibilities. An INTERNAL seam — the public entry points stay `serialize`/`deserializeComponentState`. The prose ladder and every version constant stay in `component_state_io.h`, their one home.
- `bank_sync` — generation change-detection + assignment-request consume: owns the yes/no decision logic so the rules are provable without a host. The processor shell owns cadence and side effects.
- `bridge_marshal` — pure marshalling helper for the REAPER VST-host bridge read: interprets the `GetProjExtState` int return against its filled buffer.
- `trigger_seam`pure Trigger frames↔fraction converter: owns the shared formula for converting between engine source-frame fade counts and the overlay's fractional representation, threading `startFrame` correctly through pack and unpack directions.
- `trigger_seam`the shared Trigger play-SPAN formula: how a %-length becomes the source-frame span the overlay draws over and the bake's window holds, threading `startFrame` correctly and clamping the fraction the same way `Voice::start` does (the engine evaluates the same formula inline rather than depending on `map/`). The spline fold every consumer must apply first — `effectiveLengthFraction` — is `play_params.h`'s, beside the rest of that rule family. (Its fade frames↔fraction converters retired with the fade pair itself.)
### `ui/`
- `editor_geometry` (`core/instrument/ui`) — the shared geometry VOCABULARY every instrument UI module speaks: the `core::ui::Rect` alias, `contains()`, and `OverlayArea` (a one-field `Rect` wrapper, no implicit conversion from `Rect`). Header-only (an INTERFACE CMake target), so it carries no layout of its own.
- `sample_bands`**THE band-stack allocator**, and the only module that owns the Sample face's vertical inventory — including `kEditorMinWidth`/`kEditorMinHeight`, the editor's client-area floor, which IS its default size (the shell's `checkSizeConstraint` and opening `ViewRect` both read it; the face grows, never shrinks below what the stack is laid out for). Three bands top-to-bottom (CHROME toolbar+control row / WAVEFORM elastic, floored at two stacked lanes / DECKS bottom-anchored at the knob deck's own wrapped height), plus the waveform band's lane split (`waveformLanes` takes a resolved `LaneSplit`, not a raw bool — only `waveformSurface` folds the source-channel-count decision in). A shared READ-ONLY surface for every band owner — a band's interior module lays out inside the rect it is handed and never re-allocates the stack.
- `sample_chrome` — the CHROME band's interior: the toolbar row (title + the whole right-anchored control run — preview, velocity knob cell, curve button, channel toggle, Browse) over the strip row, which the piano strip owns outright. The title takes what the run leaves; the strip takes its whole row, inset only by the shared band pad so it lines up with the waveform band beneath.
- `sample_bands`**THE band-stack allocator**, and the only module that owns the Sample face's vertical inventory — including `kEditorMinWidth`/`kEditorMinHeight`, the editor's client-area floor, which IS its default size (the shell's `checkSizeConstraint` and opening `ViewRect` both read it; the face grows, never shrinks below what the stack is laid out for), and `kEditorCeilingWidth`, the floor's sibling window fact (the hard cap the floor may not exceed) — moved here from `knob_deck.h` since it is a window fact, not a deck one; the derivation identity against the deck's width budget stays in `test_deck_groups_measured.cpp`, the one place that already includes both headers. Three bands top-to-bottom (CHROME toolbar+control row / WAVEFORM elastic, floored at two stacked lanes / DECKS bottom-anchored at the knob deck's own height), plus the waveform band's lane split (`waveformLanes` takes a resolved `LaneSplit`, not a raw bool — only `waveformSurface` folds the source-channel-count decision in). A shared READ-ONLY surface for every band owner — a band's interior module lays out inside the rect it is handed and never re-allocates the stack.
- `sample_chrome` — the CHROME band's interior: the toolbar row (title + the whole right-anchored control run — bake Hold cell, bake, preview, velocity knob cell, loop enable, channel toggle, Browse) over the strip row, which the piano strip owns outright. The title takes what the run leaves; the strip takes its whole row, inset only by the shared band pad so it lines up with the waveform band beneath. Every run member's width is RESERVED unconditionally, the Hold cell included — the only conditionally-drawn one, and the leftmost, so what its reservation buys is a title slot that does not re-measure when a loop is dialled in or out (`sample_chrome.h` records the cost). Also `previewGlyph`, the preview button's play triangle — three vertices for one filled-triangle draw, so the button's label needs no font metric and no image asset.
- `bake_hold` — the Hold knob's value domain and nothing else: the knob's normalized [0,1] mapped onto the note-length ladder and back, ordered by LENGTH rather than by the ladder's presentation order. Split from `sample_chrome` on the same axis `deck_values` was split from `knob_deck` — that says where the cell is, this says what its position means.
- `keyboard_strip` — piano-keyboard strip: true white/black key geometry (whites tiled at one width, blacks overlaid at one width and height, straddling their boundary), hit-test resolving black-over-white by zone, root-marker rect, the absolute-position drag resolver, and MIDI note naming under the C4 convention. **Same-class keys are one integer width by construction; the residue of an indivisible band width (`w % 75`, up to 74 px) lands in symmetric end margins, never in a key** — uniform widths and gap-free edge-to-edge tiling cannot both hold, and uniformity wins.
- `waveform_view` — the WAVEFORM band's interior: `waveformSurface` resolves the drawn lane(s) (two stacked lanes, L over R, only when the mode is stereo AND the source has a second channel — a mono source under stereo mode is dual-mono and draws one lane) plus **the** overlay area, and `laneEnvelope` splits one multi-channel envelope pass per lane. Also maps frame span linearly across a rect; generic named draggable markers with drag-delta resolver, clamp, and zero-crossing snap.
- **Overlay contract (consumed by later waveform work).** `WaveformSurface::overlay` — equivalently the standalone `waveformOverlayArea(band)` — is the FULL band in both modes. Everything riding the waveform (the amp-envelope trace and its node handles, the start/loop markers, the loop region) draws ONCE into it, spanning both stacked lanes; hit-testing resolves against the same area so a grab in the lower lane reaches them. Anything drawn or hit-tested per lane is a duplicate and a defect — structurally enforced: `overlay` is the distinct `OverlayArea` type (`editor_geometry`), not `Rect`, so every overlay-consuming API (`frameToX`/`markerAtPoint`/`resolveDragFrame`, `envelope_edit`'s `nodeAtPoint`/`resolveNodeDrag`, `envelope_overlay`'s `buildEnvelopePolyline`) rejects a lane rect at compile time rather than silently accepting one.
- `waveform_view` — the WAVEFORM band's interior: `resolveLaneSplit` is THE lane-split decision (two lanes only when the mode is stereo AND the source has a second channel — a mono source under stereo mode is dual-mono and draws one lane), free of any pixel geometry so the meter's bar count can ask the same question without a band rect; `waveformSurface` folds it and then measures it against the band, which is why its `laneCount` can still report 1 for a Stereo split on a band too thin to divide. It also yields **the** overlay area, and `laneEnvelope` splits one multi-channel envelope pass per lane. Also maps frame span linearly across a rect, plus generic named draggable markers with a drag-delta resolver, clamp, and the zero-crossing snap. The snap is RADIUS-BOUNDED (`snapToZeroCrossing`), the radius denominated in PIXELS and converted through `xToFrame`; `nearestZeroCrossing` beside it is the unbounded primitive and is NOT what a drag applies. Ctrl defeats the snap outright at the shell (`editor_input_waveform.cpp`), the same "get out of the way, I want exactness" role it plays on the knobs' fine drag. `markerHandleRect` is a top-strip grab tab distinct from a marker's full-height column, so two markers that share a frame stay independently grabbable — the column goes to the first in draw order, the tab, asked first, resolves the other.
- **Overlay contract (consumed by later waveform work).** `WaveformSurface::overlay` — equivalently the standalone `waveformOverlayArea(band)` — is the band's DRAWN COLUMN SPAN at the band's full height, in both modes: same inset and same width as `component_geometry`'s `waveformColumnCount`, so overlay pixel and waveform column are one pixel and every overlay lands on the column that draws the frame it names. Deriving that width instead of restating the inset is what keeps the two chains from drifting apart again. Everything riding the waveform (the amp-envelope trace and its node handles, the start/loop markers, the loop region) draws ONCE into it, spanning both stacked lanes; hit-testing resolves against the same area so a grab in the lower lane reaches them. Anything drawn or hit-tested per lane is a duplicate and a defect — structurally enforced: `overlay` is the distinct `OverlayArea` type (`editor_geometry`), not `Rect`, so every overlay-consuming API (`frameToX`/`markerAtPoint`/`resolveDragFrame`, `envelope_edit`'s `nodeAtPoint`/`resolveNodeDrag`, `envelope_overlay`'s `buildEnvelopePolyline`) rejects a lane rect at compile time rather than silently accepting one.
- **The four marks.** One grammar — line + shaped cap + label — over START / LOOP / END / XFADE. Which of them are PRESENT is the mode's answer, and drawn iff grabbable: Trigger carries START alone (the loop pair and the fade are absent, not dim), Gate always carries the pair so the drag-to-set-loop gesture survives the enable being off, and the fade needs an active loop to have a seam. `markerHandleRect` IS the cap: every mark's is the same rect shape, only the glyph inside differs, which is what keeps the claim arbitration seeing one nominal cap area. `capAtPoint` resolves caps in the REVERSE of the column order, so any coincident PAIR stays separable (one answers its cap, the other its column) and the crossfade — the one mark with no column — can never be shadowed. `layoutMarkLabels` places the promoted (grabbed/hovered) mark first and suppresses any box that would overlap one already placed. `crossfadeWedgeHeight` is the ONE ramp both the audible region and the ingredient ghost draw, because they are the same fade weight over the two spans it mixes.
- `loop_marks` — the loop enable's state machine, split from the geometry above on the axis the surface already has: that says where a mark is, this says what the loop IS. `SampleLoop::hasLoop` is the single authority and `resolveLoopMarks`/`applyLoopMarks` are its only two folds — the resolve re-parks on `defaultLoopBounds` only when the span is one `resolveLoop` would refuse (so a user's off keeps its positions and `parked` separates the two OFF states), and the write folds collapse-to-off in and ties the crossfade to the SPAN rather than to the enable. Links `loop_span` so the span the user is offered and the span the engine accepts stay one definition.
- `capture_browser` — capture browser: card-grid layout + bank-filter tab strip geometry and hit-test; knows only counts and rects, draws nothing.
- `browser_scroll` — scroll + type-to-filter layered over `capture_browser`: vertical scroll offset, scrollbar thumb, thumb-drag mapping, and name-substring search.
- `param_slider`parameter control-panel: vertical stack of TOGGLE (two-segment selector) and SLIDER (horizontal track) rows; maps normalized value to/from handle pixel.
- `param_taper`THE norm↔value tapers every variable control shares, and the modifier vocabulary its drag surfaces read: the stage-time shifted-log (and `kStageTimeMaxSeconds`, the ONE home of the stage-time ceiling that `envelope_overlay`'s `kGateStageMaxSeconds` and `deck_values`' `kEnvTimeMaxSeconds` alias), the centre-expanded semitone-depth map, `DragModifiers`/`kFineDragScale`/`fineDrag`, the `UnitCategory` axis, and the four whole-unit snaps Shift applies. Extracted from `deck_values` because it has THREE consumers in two dependency layers — the knob's needle (`deck_values`), the AHDSR schematic axis and its drag inverse (`envelope_overlay`/`envelope_edit`, which sit *below* `deck_values`), and the VST3 host's `toPlain`/`toNormalized`. **Three functions that agree today is a defect, not an implementation choice**; solving the include edge by copying the map is the specific mistake this exists to prevent. Both maps resolve their output onto a fixed decimal quantum, which is what makes "every default has an EXACT normalized preimage" a structural guarantee rather than a libm coincidence — the header states the argument; the converse round trip at an arbitrary norm is explicitly NOT required.
- `param_slider` — parameter control-panel: vertical stack of TOGGLE (two-segment selector) and SLIDER (horizontal track) rows; maps normalized value to/from handle pixel. `knobDragValue` is the knob's grab-anchored absolute drag law and applies Ctrl's rate — but not Shift's snap, whose whole unit is a property of the control's unit category this module does not know.
- `embed_strip` — compact single-row control layout for embed mode in the track FX chain.
- `knob_deck` — pure knob-deck layout + hit-test (FB1): group-box / caption-row / compact-toggle / knob-cell geometry, deterministic whole-group wrap, `DeckLayout` / `DeckHit`. Mirror of `action_bar`/`param_slider`; no LICE or REAPER types.
- `deck_groups`WHICH groups the Sample face's deck carries, split from `knob_deck`'s HOW they lay out: the `DeckParam` control-id space (the editor's `ParamControl` is an alias of it), the `DeckGroupId` list, `sampleDeckGroups` in signal-flow order (**pitch → filter → amp**, then voice/master), and the deck's bipolar-knob law. Reads `PlayMode` for the AMP group's Gate/Trigger face, which is why this and not `knob_deck` is the module that touches the engine's value layer.
- `knob_deck` — pure knob-deck layout + hit-test (FB1): group-box / caption-row / compact-toggle / knob-cell geometry, the categorical row law, `DeckLayout` / `DeckHit`. Mirror of `action_bar`/`param_slider`; no LICE or REAPER types. **Row membership is a property of the GROUP (`DeckRow`), never a wrap outcome** — the greedy whole-group wrap it replaced is gone, and the layout is the specified arrangement by construction at every width. Both categorical rows are justified SPACE-BETWEEN inside the row block (slack divided equally among the (n1) gutters, integer residue to the leftmost, never below `kDeckGroupGap`, decks never stretched); a `DeckRow::Spanning` group is right-anchored OUTSIDE that block at `kDeckSpanningH` and takes no part in either row's justification. Below the width the block needs, gutters floor and the row overruns right rather than wrapping — the editor clamps its window above that, so the degrade only has to be defined. A spanning group reads `cellIds` DOWN, one fixed `kDeckCellW` slot per declared id at successive row baselines (reserves advance the slot), plus an optional full-height readout `column`; the run-division law below is horizontal only, and applying it vertically would stretch a lone knob over the whole box. A `DeckRadioDesc` may be `passive` — same corner slot, skipped by the hit-test, so a readout lamp cannot grow a gesture. Carries a SECOND hit-test, `hitTestKnobFace`, resolved against the drawn CIRCLES rather than the cell: a double-click reset is aimed at a dial, so the label band and the cell margins must miss where a drag grab deliberately does not, and only a radial resolve can tell the inner curve dial from the outer ring it sits inside. The deck's width budget at the editor's floor — the row block, the spanning deck's reserve, and what drives the floor — is declared and reasoned at the constants themselves (`knob_deck.h`; the ceiling itself now lives in `sample_bands.h` as a window fact); every group's categorical row is `deck_groups`' `deckRowFor`. A group carries TWO caption-toggle slots, laid right-to-left: the second exists because a group whose knob row is wider than its caption row has caption slack a toggle can occupy for free, where a `rowToggle` widens the GROUP and is charged against that budget — which is why the env decks' mode toggles ride the caption row. **A group's cell run is a RESERVED WIDTH, and the cells present are CENTRED in it at their natural `kDeckCellW`**: a `-1` id reserves one cell's width without a cell, and the reserve is paid for in symmetric end margins, never in wider cells. That is what lets a mode flip drop controls from a face — Trigger's AMP and FILTER ENV lose their Sustain/Release stages — without either reflowing the deck or stretching the knobs off their pitch; only the reserve COUNT matters, so where a `-1` sits in `cellIds` is free. Two rejected laws, recorded so they are not re-proposed: dropping the reserves (reflows every neighbour on a mode flip, which is what the reserves exist to prevent), and dividing the run between the cells present (the retired law — it handed a reduced face 90100 px cells). A SPANNING group is the one place a reserve's position still matters, because there it advances a fixed slot.
- `deck_values`the deck's control-id ↔ parameter-set BINDING and its display units, split
from the editor shell on the same axis `deck_groups` was split from `knob_deck`: `deck_groups`
says which controls exist, this says what each one's value MEANS. Holds `deckParamNorm` /
`setDeckParam` (the normalized ↔ stored-seconds/fraction/position binding and its clamps, over
`param_taper`'s maps), `resetDeckParam` (the double-click reset — the defaults are READ off a
default-constructed `PlaySeconds`, so there is no second table of defaults to drift, and the
value is COPIED rather than round-tripped: that taper bypass is mandatory and must never be
"simplified" back into a norm round trip), `deckParamUnit`/`snapDeckParamNorm` (THE snap-unit
table, and where each control's full scale enters — a whole DISPLAYED percent is a different
norm step at 0..100 %, 0..200 % and ±100 %). Display FORMATTING is not here — `param/`'s
`param_format` owns the one formatter per unit category, because the host and the editor must
be its two callers and neither may hold a second implementation. Links the header-only
`play_seconds`, deliberately not
`sample_map`: `PlaySeconds` is the whole of what a deck edits, and linking the mapping would
drag the bank model and the WAV codec in behind it. The shell keeps only the controls the
parameter set does not carry (key-track, voice count, master gain, preview velocity) and the
labels for them.
- `master_meter` — the MASTER column's interior, split from `knob_deck` on the axis `sample_chrome` has to `sample_bands`: that says where the column is, this lays out inside it (22 px numeral gutter · 4 · 36 px bar field) and holds the per-instance UI state the bars draw from. `kMeterColumnW` is the SUM of those three, exported so `deck_groups`' MASTER descriptor reserves exactly what the interior consumes — the column is banked to grow, and a reserve that did not track it would underfill or overrun silently. **Bar count takes a RESOLVED `LaneSplit`, the same value `waveform_view`'s `resolveLaneSplit` answers** — a mono source under stereo mode is dual-mono, and two identical bars would be a lie. Also owns `meterTickNumeralled` (the spec-pinned 0/12/24/36/48/60 numeral set, beside the tick step it derives from), `meterNumeralRect` (bottom-clamped, so the floor tick's numeral cannot hang out of the gutter), and `meterSingleLaneState` — the one bar folds both channels PER FIELD, never picking a whole channel by level. Composes `engine/meter_ballistics` per channel and gives the gain-reduction lamp the peak tick's own hold-then-release, without which a catch smaller than 20 dB × the UI period is dark again before it has been drawn twice; the audio thread's clip flag is ORed in because it is the only latch that sees every block. `meterDrawEqual` is what lets the UI tick repaint on change alone. Also owns the editor's two paint-dispatch predicates, so neither lives as a bare comment in the shell: `meterFastPathEligible` (is a WM_PAINT dirty rect wholly inside the field?) and `meterBarsWithinField` (the self-containment invariant that fast path rests on), both asserted in `test_master_meter.cpp`.
- `deck_groups` — also home to `deckParamCommit` and `liveCommitFor`, the editor's whole commit-tier routing decision (see "Live parameter delivery" above), and to `OverlayEnv` + `overlayEnvForGroup`/`overlayEnvEnabled`/`overlayEnvInert`, the whole overlay-FOCUS state machine (which deck names which envelope, the none resting state, and which selections a disabled or DRAWN group makes inert); WHICH groups the Sample face's deck carries, split from `knob_deck`'s HOW they lay out: the `DeckParam` control-id space (the editor's `ParamControl` is an alias of it), the `DeckGroupId` list, `sampleDeckGroups` in signal-flow order (**pitch → filter → amp**, then velocity/voice/master), and the deck's bipolar-knob law. Reads `PlayMode` for the AMP group's Gate/Trigger face, which is why this and not `knob_deck` is the module that touches the engine's value layer. Also home to `CurveTarget` + `curveTargetFor` — the VELOCITY group's three cells are popup openers, not dials, and that predicate is the ONE place they are named, so paint, hit-test routing and the popup's title all agree. MASTER is reserved for post-voice-mixer concerns, which is why the curves sit in their own group immediately left of VOICE rather than there; it now discharges that reservation as the double-height bus deck — gain, the limiter enable, one reserved slot, the meter column and the GR lamp. FILTER's `Band|Notch` rides its caption slack rather than the knob row: that is the 92 px that makes the SOUND row fit its block, and putting it back breaks the fit. VOICE's `Retrig|Legato` deliberately stays in the knob row — VOICE's caption row is the binding side, so moving it there makes the group 226 rather than 164.
- `spline_edit` — THE point-editing grammar, and the one place it is written down: left-click grabs a node and adds one in empty space, right-click deletes, control-click toggles hard/smooth. Both spline consumers — the velocity-curve popup and the spline EG overlay — route their mouse-down through `resolveSplineEdit`, so the two cannot drift into two grammars. The endpoint and point-count rules are NOT restated here: `deletePoint` and `addPoint` own them, and the caller applies the resolved action to the curve. Also home to `splineOverlayBox`, the contour's mapping box inside the waveform overlay — the FULL area, no inset, so the drawn contour stays 1:1 with the sample's time axis. Spline points are excluded from `param_taper`'s Shift/Ctrl modifier law like waveform markers are: a point is a normalized position with no displayed unit, and control-click there is already claimed by the hard/smooth toggle above.
- `curve_popup` — pure curve-popup geometry + dismissal test (FB1): centered sheet over the Sample face — width/height clamps, title row, Close button rect, curve-box rect, outside-sheet dismissal test. Mirror of `overflow_menu`; no LICE or REAPER types.
- `envelope_overlay` — pure amp-envelope→polyline geometry for the Sample-view envelope overlay (read from `envelope_overlay.h`): maps Gate's AHDSR shape or Trigger's fade-in/unity/%-length/fade-out shape to a polyline inside a rect at the shared time base (Gate: a bounded param-domain schematic, sample-length-free; Trigger: PCM-aligned wall-clock), every vertex clamped in-canvas (`x`/`y` inside the rect). Shares the `EnvNode`/`AmpEnvelope`/`timeToX`/`levelToY` vocabulary with `envelope_edit` so the drawn handle and its grab region agree pixel-for-pixel. No VST3/REAPER/LICE types at the boundary.
- `envelope_edit` — pure node hit-test + pixel-delta→clamped-param inverse map for the draggable envelope nodes (read from `envelope_edit.h`): `nodeAtPoint` resolves a grab to the nearest node within a pick radius (Chebyshev distance, draw-order tie-break); `resolveNodeDrag` maps a pixel delta since grab to a new `AmpEnvelope`, enforcing monotonic-in-time ordering between neighbouring nodes and the same caller-supplied per-param clamp bounds the sliders use a drag can never produce a param a slider couldn't. Mirror of `card_drag`/`waveform_view`; the inverse of `envelope_overlay`'s params→polyline forward map, so node-drag and slider-edit read/write one shared model and can never diverge.
- `envelope_overlay` — pure staged-envelope→polyline geometry for the Sample-view overlay (read from `envelope_overlay.h`): maps a `StageEnvelope` to a polyline inside a rect under whichever of TWO layout policies its `EnvKind` selects — an AHDSR draws a bounded param-domain schematic with its release RIGHT-ANCHORED to the canvas edge, an AHD draws 1:1 over the waveform's own time axis — plus a round mid-segment knot on every sloped stage that has a duration. Every vertex clamped in-canvas. Shares the `EnvNode`/`StageEnvelope`/`timeToX`/`levelToY` vocabulary with `envelope_edit` so the drawn handle and its grab region agree pixel-for-pixel. No VST3/REAPER/LICE types at the boundary.
- `curve_tessellate` — the staged envelope's TRACE, split from `envelope_overlay` on the axis those two already have: that module decides where a node LANDS, this strokes the span BETWEEN two of them. Joins the non-knot vertices with the curve each stage's exponent defines, sampled one point per pixel column, at `start + (end - start) * curveMap(phi)` — the composition `envelopes.h`'s four evaluators use, so a drawn stage and the sound it makes cannot diverge. Node vertices keep their exact integer coordinates (the handles are drawn on them); only the interior samples are sub-pixel. A neutral exponent or a zero level span emits the two endpoints and nothing between, which is the straight stroke drawn before curves existed, vertex for vertex.
- `envelope_edit` — pure node hit-test + pixel-delta→clamped-param inverse map for the draggable envelope nodes and their curve knots (read from `envelope_edit.h`): `nodeAtPoint` resolves a grab to the nearest node within a pick radius (Chebyshev distance, draw-order tie-break, knots appended last so a coincident endpoint handle wins); `resolveNodeDrag` maps a pixel delta since grab to a new `StageEnvelope` under the same caller-supplied per-param clamp bounds the knobs use — a drag can never produce a param a knob couldn't. Mirror of `card_drag`/`waveform_view`; the inverse of `envelope_overlay`'s params→polyline forward map, so node-drag, knot-drag and knob-edit read/write one shared model and can never diverge.
## Gotchas
- **Gate's envelope-overlay x-axis is schematic, not PCM-aligned** (per `envelope_overlay.h`'s FA2 contract note) — it does NOT line up with the waveform under it; only Trigger's x-axis is wall-clock/PCM-aligned. Don't assume the Gate curve is time-accurate against the sample.
- **Trigger's fade fields require a non-trivial converter, not a field copy.** `TriggerParams` (engine) stores fades as source *frames*; `AmpEnvelope` (the overlay's view struct) stores them as *fractions* of the played span. A converter is owed on both the pack (draw) and unpack (commit) directions — `trigger_seam` owns this formula; do not copy the fields directly.
- **An AHDSR's overlay x-axis is schematic, not PCM-aligned, and it is not linear in seconds either** — it does NOT line up with the waveform under it, and each of its four equal stage slots is filled by `param_taper`'s own norm, so a node's position within its slot IS its knob's needle position. Two stages therefore cannot be compared by eye at a 10:1 ratio; the ms labels carry the number. Only a sustain-less AHD's x-axis is wall-clock/PCM-aligned and linear. Content-fit auto-scale and a minimum drawn stage width were both considered and REJECTED — the first moves the axis under the hand, the second decouples the drawn position from the value and breaks the drag inverse.
- **An AHD's Hold is a FRACTION of what attack and decay left, never a time.** That is the whole reason A+H+D ≤ span holds by construction; adding a clamp on the sum, or re-expressing Hold as a duration, reintroduces the overflow the fraction exists to prevent.
- **`param_slider`'s linear slider rows are retired on the parameter surface** — per root `CLAUDE.md`'s FB2 note, the `Knob` primitive (the knob-deck grammar) is now the only live consumer of that half of `param_slider`. Don't assume `param_slider`'s SLIDER row type is still drawn.
- **The engine's per-sample path is inline ON PURPOSE.** `Voice::advanceFrame` and the three evaluators in `envelopes.h` live in headers so `VoiceEngine::render`'s inner loop — in another TU, with no LTO configured — still inlines the whole stack. Moving either out of line, or giving the evaluators a virtual `tick()`, puts a call on the hottest loop in the program.
- **The band-stack allocator is the ONLY vertical-inventory owner.** A band's interior module (`sample_chrome`, `knob_deck`, the waveform painters) lays out inside the rect it is handed. A band owner that re-derives its own top/bottom has forked the stack.
@@ -243,6 +386,17 @@ slider couldn't. Two pure modules split the forward (draw) and inverse (edit) ma
Channel-mode (D-E) bus-renegotiation design and the earlier Preserve-onset-latency
framing in the S16 guardrails. Root `CLAUDE.md` is the current source of truth
for both — do not reintroduce either superseded design.
- **A filter envelope only advances while its depth is non-zero.** `tickFilterCutoff`'s exact
skip at `modAmount == 0` skips the envelope tick along with the solve, so dialling depth up
mid-note starts the envelope from the note's stage-0 position rather than from where it would
have been. Its step smoother is frozen with it — an absorbed step sits in the offset and
emits when depth is next dialled up (bounded, and scaled by a depth ramping from 0).
Continuous either way (the contribution starts at 0), and keeping the skip is what holds the
at-rest per-sample path byte-identical — but don't read a live depth move as "resuming" an
envelope that was never running.
- **A live edit leaves the snapshot's own `sample.play` stale, on purpose.** The block, not the
snapshot, is the audio thread's source; a new voice latches the stale copy and is corrected by
`snapLive` before its first frame.
- **`keyboard_strip`'s width-uniformity guarantee is client-pixel only.** Its test sweep
covers client-pixel widths (including multiples standing in for larger client areas);
nothing in the instrument implements `IPlugViewContentScaleSupport`, so host-side DPI
+10
View File
@@ -1,3 +1,13 @@
add_subdirectory(engine)
add_subdirectory(map)
add_subdirectory(note)
add_subdirectory(ui)
# After ui: the VST3 parameter identity reads the deck's commit predicate and its value binding.
add_subdirectory(param)
# Last: bake composes the three above it.
add_subdirectory(bake)
# The spline EG spans all three: the shared curve + its RT cursor (engine), the dual-state
# persistence (map), and the point-editing grammar (ui). Declared here because no one
# subdirectory owns the seam it covers.
reasampler_test(spline_egs LINK sampler_core sample_map component_state_io spline_edit deck_groups)
+107
View File
@@ -0,0 +1,107 @@
# src/core/instrument/bake — the resample bake's pure half
## Scope
The offline pass that turns the dialed instrument into a file, and the reset that hands the
instrument back neutral afterwards. A fifth peer of `engine/` / `map/` / `note/` / `ui/`
under `core/instrument/`, pure by the same rule — no REAPER types, no VST3 types, no host.
It is neither engine (it owns no voice), mapping (it resolves no capture), nor note (it
holds no program): it is the *composition* of the three into one render, plus the one
decision about what the render made obsolete.
## Invariants
- **The bake renders on its OWN engine, never the live one.** `renderBake` takes its
`SampleData` BY VALUE and detaches `SampleData::live` before constructing a `VoiceEngine`
for the render alone. Two consequences, both load-bearing: the audio thread's live block
can neither be observed nor disturbed by a bake, and a repeated bake of one dialed sound
is byte-identical because nothing outside the passed value can vary between runs.
- **The window bounds the render; the envelope does not.** Termination is structural — the
loop runs to `BakePlan::renderFrames()` and stops. That is why a Gate bake with a sustain
loop active terminates: the gate is released at `noteOffFrame` so the tail is real, but
even a pathological envelope cannot run past the window.
- **The whole chain is printed — voice, master gain, then the limiter, in the processor's
own order.** `bake_render.cpp`'s master stage carries the argument. The limiter is printed
only when it is ENGAGED; bypassed, `renderBake` never constructs one and the result is the
pre-limiter render frame for frame. The lookahead is compensated inside the render — the
buffers carry an extra flush window and the capture is read past it — so an engaged bake
under the ceiling is bit-identical to a bypassed one, not the same audio 2 ms late.
- **A printed capture replayed through an engaged limiter is limited TWICE — a NAMED
boundary, not a bug**, and the same shape as the automation-lane limitation below. The
reset is what normally prevents it (`limiterEnabled` is not on the survive list, so a bake
hands the enable back off), and at unity the second pass has nothing to take: every sample
of the printed file is already at or under the ceiling, and the limiter reduces only where
its detector reads ABOVE it — which after a bake means its inter-sample estimate alone. Dial
the enable back on over raised gain, though, and the capture is limited on top of limiting
that is already in its samples. Not detectable from inside the instrument and not corrected
there; the user's remedy is to leave the enable where the bake put it.
- **A degenerate or unholdable window is refused, not rendered.** `planBake` refuses a
collapsed window, a non-positive rate, a window that rounds to no frames, and one past
`kMaxBakeFrames` — an unbounded window is a `bad_alloc` inside a UI tick, and the
seconds→frames narrowing is undefined long before the allocation would fail. The refusal
carries a `BakeRefusal` naming WHICH: past-the-ceiling is a real sound that will not fit,
which reads to the user as a different sentence than an empty window.
- **The window derives itself, and Hold is the one exception.** Trigger derives from the play
span; Gate over an active sustain loop takes the user's Hold, because a loop sounds for as
long as it is held and no derivation can supply a duration; Gate WITHOUT one derives from
source exhaustion, since the read head frees the voice whether or not the gate is down.
`bakeWindowNeedsHold` is the predicate, and it reads the ENGINE's loop fold rather than the
loop fields, so the control that collects Hold cannot appear for a loop the voice refuses.
- **Trailing silence is free; truncation is not.** Every derivation errs outward — the
Varispeed bound takes the deepest reachable offset the voice can play, and every path is
padded by the voice's terminal declick ramp (`kDeclickFrames`, unconditionally — not branched
on the pitch engine that has the ramp today). Judge any change to this module against that
asymmetry. What it does NOT mean is quantizing: a derived length is an exact duration and a
finite ladder cannot express one (`note/CLAUDE.md`) — rounding up to a rung truncated any
source past the top rung, which is the failure this asymmetry exists to prevent.
- **The reset's survive list is written out; everything else defaults.** `resetAfterBake`
starts from a default-constructed parameter set and copies back only the mapping facts.
A parameter added later therefore resets by default — the safe direction, since
under-resetting applies the same processing twice while over-resetting costs a re-dial.
A new mapping fact must be added to the copy list explicitly.
- **Play mode resets to TRIGGER, not to the value struct's Gate default** — the one
classification this track made against the ratified rule rather than reading off it.
`bake_reset.cpp` carries the argument at the assignment.
- **`kStageTimeMaxSeconds` (the stage-time ceiling `param_taper` owns) is not a reset-list
candidate at all** — it bounds a knob's taper, is never itself a dialed value, and so has
no disposition to classify against the ratified reset rule.
- **A host automation lane outranks the reset, and the bake cannot clear it — a NAMED
limitation, not a bug.** Every reset-class value that is also an exposed VST3 parameter is
now notified to the host (the reset writes through `setInstrumentParams`, which is the one
notification funnel), so the host's DISPLAY follows the reset. A lane, however, lives in the
host's project data: if a reset-class parameter carries one, the host replays its curve onto
audio that already has that processing baked in — double processing, and the "sounds as the
dialled instrument sounded just before the click" claim does not hold in that case. There is
no detection available: `IAutomationState` reports the host's automation mode for the whole
plug-in, not per parameter, so both "refuse the bake" and "reset only the un-automated ones"
are unbuildable rather than merely unattractive. The user's remedy is to remove the lane.
## Modules
- `bake_plan``defaultBakeProgram` (the whole programmed note, DERIVED from the dialed
sound: its note length as well as its end offset), `bakeWindowNeedsHold`, `BakePlan` (the
render window, the captured slice of it, and the two event frames), `kMaxBakeFrames`, and
`planBake`, the one `ResolvedNote` + rate -> frames resolution, answering a `PlannedBake`.
- `bake_render``BakeAudio` and `renderBake`: the programmed note through the sample's
own voice path and then the master stage, summed into an interleaved buffer at the
source's own channel count.
- `bake_reset``BakeReset` and `resetAfterBake`: the ratified reset scope, answered for
both the parameter set and the post-mixer master gain.
## Gotchas
- **`BakePlan` speaks two frame domains** — the captured file's and the render's, which are
offset from each other whenever the note and the capture window do not start together.
`bake_plan.h` says which field is in which; do not read them as one clock.
- **`defaultBakeProgram`'s read-rate bound is an upper bound, not a model.** Anything that
slows the read makes the head take longer to cross its span, so the window is scaled by the
slowest read the voice can reach — a shallower excursion leaves trailing silence in the file.
Rate is a term of it under BOTH engines and the deepest downward pitch offset under Varispeed
alone (`playbackStretch` argues each); both the Trigger span and the Gate exhaustion length
take the product, and the Gate-with-loop branch takes neither.
- **The bake fires at the instance's PREVIEW velocity, not a constant.** Three velocity curves
are live, so the velocity is a property of the sound being printed and not a detail of the
render; it also feeds the Varispeed bound above (a velocity→pitch curve moves the window).
- The render's channel count is the loaded `SampleData`'s, which is already the instance's
channel-mode decision — a mono-mode instance bakes mono, and that is faithful, not a fold.
+24
View File
@@ -0,0 +1,24 @@
# The default program's window is derived from the DIALED sound, so the plan reads the
# engine's value layer, its loop fold and its declick length (all sampler_core), the one
# Trigger span formula (trigger_seam), and the note-length ladder (via note_program).
reasampler_pure_library(bake_plan
SOURCES bake_plan.cpp
LINK PUBLIC note_program sampler_core trigger_seam)
reasampler_test(bake_plan LINK bake_plan)
# limiter beside sampler_core, not through it: the render prints the whole master stage, and
# the limiter runs on the summed output rather than inside a voice.
reasampler_pure_library(bake_render
SOURCES bake_render.cpp
LINK PUBLIC bake_plan sampler_core limiter)
reasampler_test(bake_render LINK bake_render)
# No library of its own: the derived window is a PROPERTY of bake_plan + bake_render
# together, and this measures it end to end rather than either half in isolation.
reasampler_test(bake_window LINK bake_plan bake_render)
# sample_map carries InstrumentParams, which is the whole of what a reset rewrites.
reasampler_pure_library(bake_reset SOURCES bake_reset.cpp LINK PUBLIC sample_map)
# loop_marks is a TEST-only edge: it defines what a neutral loop looks like on the band, so
# the reset's loop assertions read it rather than restating it.
reasampler_test(bake_reset LINK bake_reset loop_marks)
+162
View File
@@ -0,0 +1,162 @@
// See bake_plan.h.
#include "core/instrument/bake/bake_plan.h"
#include <algorithm>
#include <cmath>
#include "core/instrument/engine/loop/loop_span.h" // resolveLoop (the one sustain-loop fold)
#include "core/instrument/engine/time_stretch.h" // clampStretchRate (THE rate bound)
#include "core/instrument/engine/voice.h" // kDeclickFrames (the terminal ramp length)
#include "core/instrument/map/trigger_seam.h" // triggerPlayLength (the one span formula)
namespace reasampler::instrument::bake {
using note::NoteProgram;
using note::ResolvedNote;
namespace {
// Seconds -> frames by round-half-away-from-zero, the one conversion every field here uses,
// so the window and its event frames cannot round against each other. Reports failure
// rather than clamping: the double->int64 narrowing below is undefined once the product
// leaves int64's range, which a legal offset magnitude reaches long before that.
bool toFrames(double seconds, int rate, std::int64_t& out) {
const double frames = seconds * static_cast<double>(rate);
const auto ceiling = static_cast<double>(kMaxBakeFrames);
if (!(frames >= -ceiling && frames <= ceiling)) return false; // also catches NaN
out = static_cast<std::int64_t>(std::llround(frames));
return true;
}
// OUTPUT frames per source frame for the dialed voice, at its slowest reachable read — the
// factor a source span is scaled by to bound how long it takes to play out. Two terms:
//
// Rate divides, under BOTH engines: Varispeed folds it into the read increment and Preserve
// feeds the stretcher at it, so either way the source is consumed at that many frames per
// output frame. Taken through the engine's clamp, because that is the value Voice::start
// actually plays.
//
// The deepest DOWNWARD pitch offset stretches, under Varispeed ONLY, where the read head
// advances at the pitch ratio. Preserve transposes inside the shifter and leaves the read
// rate alone, which is the only sense in which the two are decoupled there.
//
// A Gate release is ticked per output frame, so neither term touches it.
double playbackStretch(const PlayParams& play, int velocity) {
double down = 0.0;
if (play.pitchEngine == PitchEngine::Varispeed) {
down = (std::min)(0.0, kVelocityPitchRangeSemitones *
play.pitchVelocityCurve.eval(velocity));
// Taken as a bound rather than exactly, like the velocity term beside it: an upward
// offset only makes the read faster, and every term in this sum is a floor.
down += (std::min)(0.0, play.pitchOffsetSemitones);
if (play.pitchEnv.enabled) {
// A drawn contour is bipolar, so it reaches -|peak| whichever way the depth points;
// the staged AHD only ever travels between 0 and the peak.
down += play.pitchSpline.mode == EnvMode::Spline
? -std::fabs(play.pitchEnv.peakSemitones)
: (std::min)(0.0, play.pitchEnv.peakSemitones);
}
}
return std::pow(2.0, -down / 12.0) / engine::clampStretchRate(play.playRate);
}
// Voice::start's own clamp: a start at or past the end degrades to 0 (play from the top)
// rather than starting a voice already off the end.
std::int64_t effectiveStart(const SampleData& dialed) {
const auto frameCount = static_cast<std::int64_t>(dialed.frames.size());
const std::int64_t start = dialed.startFrame;
return (start < 0 || start >= frameCount) ? 0 : start;
}
} // namespace
bool bakeWindowNeedsHold(PlayMode mode, const SampleLoop& loop, std::int64_t crossfadeFrames,
std::int64_t frameCount) {
// resolveLoop already refuses a non-Gate voice, so this is exactly "Gate over a loop the
// read path will honour" — the engine's decision, not a second reading of the fields.
return engine::loop::resolveLoop(loop, crossfadeFrames, frameCount,
mode == PlayMode::Gate)
.active;
}
bool bakeWindowNeedsHold(const SampleData& dialed) {
return bakeWindowNeedsHold(dialed.play.playMode, dialed.loop, dialed.loopCrossfadeFrames,
static_cast<std::int64_t>(dialed.frames.size()));
}
NoteProgram defaultBakeProgram(const SampleData& dialed, int renderSampleRate,
note::Division hold, note::Velocity velocity) {
NoteProgram p; // a quarter note, capture opening at note-on
p.velocity = velocity;
if (renderSampleRate <= 0) return p;
const double rate = static_cast<double>(renderSampleRate);
const auto frameCount = static_cast<std::int64_t>(dialed.frames.size());
const std::int64_t start = effectiveStart(dialed);
const double stretch = playbackStretch(dialed.play, p.velocity.value());
const double releaseSeconds = static_cast<double>(dialed.play.adsr.releaseFrames) / rate;
double endOffsetSeconds = 0.0;
if (dialed.play.playMode == PlayMode::Trigger) {
// Trigger ignores note-off entirely: the sound ends when the read head reaches the
// play span's end. The note is that span, so the window closes on the sound rather
// than on a length the voice never consulted.
const std::int64_t span =
map::triggerPlayLength(effectiveLengthFraction(dialed.play), frameCount, start);
p.length = note::lengthOfSeconds(static_cast<double>(span) / rate * stretch);
} else if (bakeWindowNeedsHold(dialed)) {
// The loop cycles for as long as the note is held, so the hold IS the length, and the
// release is the one stage that runs after note-off.
p.length = note::lengthOfDivision(hold);
endOffsetSeconds = releaseSeconds;
} else {
// Gate with no loop: the read head runs off the source and frees the voice whether or
// not the gate is still down, so the maximal sound is the whole post-start span held.
// Exact, not a ladder rung: a source longer than the ladder's top rung would otherwise
// take that rung and release mid-sound, and rounding up to one costs trailing silence
// on every other source.
const std::int64_t postStart = (std::max)(std::int64_t{0}, frameCount - start);
p.length = note::lengthOfSeconds(static_cast<double>(postStart) / rate * stretch);
endOffsetSeconds = releaseSeconds;
}
// The voice rings its last output out over kDeclickFrames instead of hard-cutting it, and
// that ramp starts where the derivations above end. Added on every path, not just the
// Preserve one that has the ramp today: trailing silence is free, a hard cut is not.
endOffsetSeconds += static_cast<double>(kDeclickFrames) / rate;
p.end = note::EndOffset(note::offsetFromMs(endOffsetSeconds * 1000.0));
return p;
}
PlannedBake planBake(const ResolvedNote& resolved, int sampleRate, int rootNote) {
const PlannedBake empty{std::nullopt, BakeRefusal::EmptyWindow};
const PlannedBake tooLong{std::nullopt, BakeRefusal::PastFrameCeiling};
if (resolved.windowCollapsed) return empty;
if (sampleRate <= 0) return empty;
// The render starts at whichever comes first, note-on or the capture opening. A POSITIVE
// start offset is legal and means the capture opens after the note — so the head is
// rendered and discarded, never folded away by sliding note-on later inside the window.
const double renderStartSeconds = (std::min)(resolved.captureStartSeconds, 0.0);
BakePlan plan;
plan.sampleRate = sampleRate;
if (!toFrames(resolved.captureLengthSeconds(), sampleRate, plan.totalFrames))
return tooLong;
if (plan.totalFrames <= 0) return empty;
if (!toFrames(resolved.captureStartSeconds - renderStartSeconds, sampleRate,
plan.leadInFrames))
return tooLong;
if (!toFrames(-renderStartSeconds, sampleRate, plan.noteOnFrame)) return tooLong;
if (!toFrames(resolved.noteOffSeconds - renderStartSeconds, sampleRate,
plan.noteOffFrame))
return tooLong;
// Each field cleared the ceiling alone; the render holds their sum.
if (plan.renderFrames() > kMaxBakeFrames) return tooLong;
plan.noteOffFrame = (std::max)(plan.noteOffFrame, plan.noteOnFrame);
plan.note = std::clamp(rootNote, 0, 127);
plan.velocity = std::clamp(static_cast<int>(resolved.velocity), 1, 127);
return PlannedBake{plan, BakeRefusal::None};
}
} // namespace reasampler::instrument::bake
+94
View File
@@ -0,0 +1,94 @@
// bake_plan — the programmed note resolved against a concrete sample rate: the frames the
// offline pass renders, the slice of them the capture keeps, and the two event frames.
//
// Separate from bake_render because the plan is what a preview and a bake must agree on;
// the render is only one consumer of it.
#pragma once
#include <cstdint>
#include <optional>
#include "core/instrument/engine/play_params.h" // SampleData (the dialed sound)
#include "core/instrument/note/note_program.h"
namespace reasampler::instrument::bake {
// The render's frame ceiling, refused like any other degenerate window. A legal offset
// magnitude reaches ~11.6 days, and renderBake allocates two channel buffers plus an
// interleaved one from the window — an unbounded one is a bad_alloc inside a UI tick, not a
// long bake. ~5.5 minutes at 48 kHz, past any musical programmed note.
inline constexpr std::int64_t kMaxBakeFrames = 16'000'000;
// Whether the window needs a user-supplied hold. A Gate voice over an ACTIVE sustain loop
// sounds for as long as it is held, by definition — there is no intrinsic end to derive, and
// this is the ONLY case in which there isn't. Answered by the engine's own loop fold, so the
// control that collects the hold cannot appear for a loop the voice would refuse.
bool bakeWindowNeedsHold(PlayMode mode, const SampleLoop& loop, std::int64_t crossfadeFrames,
std::int64_t frameCount);
bool bakeWindowNeedsHold(const SampleData& dialed);
// The bake's programmed note, DERIVED from the dialed sound at `renderSampleRate` (the rate
// the bake renders at, which is what the engine's frame counts are consumed against):
//
// Trigger — the note IS the play span (note-off is ignored anyway), stretched by the
// slowest read the dialed voice can reach: Rate under BOTH engines, plus the
// deepest downward pitch offset under Varispeed.
// Gate, loop — `hold` is the note length; the end offset is the release.
// Gate, no loop— the read head runs off the source and frees the voice whatever the gate is
// doing, so the note is the whole post-start span, stretched the same way.
//
// Both derived lengths are EXACT durations, not ladder rungs: a source longer than the
// ladder's top rung has no rung that covers it, and quantizing up to one overshoots every
// other source (see note/CLAUDE.md). `hold` alone stays musical — it is a picker.
//
// Every case is padded by the voice's terminal declick ramp (kDeclickFrames): trailing
// silence is free, and closing the window on the frame the ramp starts is a hard cut.
// `hold` is read only in the Gate-with-loop case; `velocity` is the velocity the note fires
// at, and it feeds the Varispeed half of that stretch as well as the render.
//
// Takes no tempo: nothing derived here is beat-denominated. The one field that is — `hold` —
// meets the tempo in resolveNote, with the rest of the program's beat-denominated fields.
note::NoteProgram defaultBakeProgram(const SampleData& dialed, int renderSampleRate,
note::Division hold, note::Velocity velocity);
// The render window in frames. TWO domains meet here: `totalFrames` is the captured FILE's
// length, everything else counts RENDER frames from whichever comes first, note-on or the
// capture opening. A positive start offset (legal — it trims the attack) puts note-on at
// render frame 0 and the file's frame 0 `leadInFrames` later; a negative one does the
// reverse, and the file opens on silence before the note. Either event frame may sit past
// the render, which then closes before the note ever fires — a legal empty capture.
struct BakePlan {
std::int64_t totalFrames = 0; // frames in the captured file
std::int64_t leadInFrames = 0; // rendered ahead of the file's frame 0, then discarded
std::int64_t noteOnFrame = 0; // both in render frames
std::int64_t noteOffFrame = 0;
// The capture's root: rendering AT root is what makes the root survivable, which is
// why the root parameter is the one processing control a bake does not reset.
int note = 60;
int velocity = 100;
int sampleRate = 0;
std::int64_t renderFrames() const { return leadInFrames + totalFrames; }
};
// Why a window was refused. The two are different user problems and read as different
// sentences: an empty window is a programming mistake, a window past the ceiling is a legal
// dialed sound that simply cannot be held in one pass.
enum class BakeRefusal : std::uint8_t {
None,
EmptyWindow, // collapsed, a non-positive rate, or a window that rounds to no frames
PastFrameCeiling, // representable but longer than kMaxBakeFrames
};
// The one `ResolvedNote` + rate -> frames resolution. A degenerate or unholdable window is
// refused rather than rendered; `refusal` is None iff `plan` holds one. `rootNote` and the
// resolved velocity are clamped into MIDI range.
struct PlannedBake {
std::optional<BakePlan> plan;
BakeRefusal refusal = BakeRefusal::None;
};
PlannedBake planBake(const note::ResolvedNote& resolved, int sampleRate, int rootNote);
} // namespace reasampler::instrument::bake
+118
View File
@@ -0,0 +1,118 @@
// See bake_render.h.
#include "core/instrument/bake/bake_render.h"
#include <algorithm>
#include <cmath>
#include "core/instrument/engine/limiter.h"
#include "core/instrument/engine/voice_engine.h"
namespace reasampler::instrument::bake {
namespace {
// A fixed render block rather than the host's. A block boundary is where the engine
// re-observes live state, and the detach below leaves it nothing to observe — so this is
// defence in depth against a future block-boundary read, not the reason two bakes agree.
constexpr std::int64_t kBlockFrames = 512;
} // namespace
BakeAudio renderBake(SampleData sample, const BakePlan& plan, double masterGainLinear,
bool limiterEnabled) {
BakeAudio out;
if (!sample.playable() || plan.totalFrames <= 0 || plan.sampleRate <= 0) return out;
// Each field bounded BEFORE the sum: renderFrames() adds them, and a hand-built plan
// (planBake already bounds both — bake_plan.cpp) could otherwise carry leadInFrames
// near INT64_MAX and signed-overflow inside the guard meant to catch exactly that.
if (plan.leadInFrames < 0 || plan.leadInFrames > kMaxBakeFrames ||
plan.totalFrames > kMaxBakeFrames) {
return out;
}
if (plan.renderFrames() > kMaxBakeFrames) return out;
// The live block is the audio thread's moving target; a render that observed it would
// depend on what the user happened to be dragging. The dialed values are already in
// this SampleData's own play params, which is what the bake is meant to print.
sample.live = nullptr;
const int channels = sample.channelCount();
// The limiter delays its output by its lookahead, so the buffers carry that many extra
// frames and the window is read that far in — the file is the same frames it would be
// with the limiter bypassed, not the capture shifted late by 2 ms. The extra input is
// SILENCE rather than more rendered audio: the file ends at the window, so a peak past
// it is not in the capture and must not duck the frames that are.
const auto flushFrames = static_cast<std::size_t>(
limiterEnabled ? engine::limiterLookaheadSamples(plan.sampleRate) : 0);
const auto rendered = static_cast<std::size_t>(plan.renderFrames());
std::vector<AudioSample> left(rendered + flushFrames, 0.f);
std::vector<AudioSample> right(channels == 2 ? rendered + flushFrames : 0u, 0.f);
// Pre-size the Preserve shifters here, off any audio thread, exactly as the processor
// does for its live engine — a cold shifter would smear the onset.
std::int64_t preserveWindow = static_cast<std::int64_t>(
kPreserveWindowMs * static_cast<double>(plan.sampleRate) / 1000.0 + 0.5);
if (preserveWindow < 2) preserveWindow = 2;
VoiceEngine engine(/*maxVoices=*/1, sample, /*preserveVoiceCap=*/0, preserveWindow,
VoiceMode::Poly, MonoTrigger::Retrigger, /*takeoverDeclick=*/false);
for (std::int64_t pos = 0; pos < plan.renderFrames();) {
if (pos == plan.noteOnFrame) engine.noteOn(plan.note, plan.velocity);
// Trigger ignores note-off by design; in Gate this is the release the programmed
// note length bounds.
if (pos == plan.noteOffFrame) engine.noteOff(plan.note);
// Stop the block at the next event frame so both land sample-accurately. An event
// past the window (a capture that closes before the note) never bounds anything.
std::int64_t limit = plan.renderFrames();
if (pos < plan.noteOnFrame) limit = (std::min)(limit, plan.noteOnFrame);
else if (pos < plan.noteOffFrame) limit = (std::min)(limit, plan.noteOffFrame);
const std::int64_t chunk = (std::min)(limit - pos, kBlockFrames);
if (chunk <= 0) break; // unreachable while limit > pos; a guard, not a path
const auto at = static_cast<std::size_t>(pos);
const auto n = static_cast<std::size_t>(chunk);
if (channels == 2) engine.render(left.data() + at, right.data() + at, n);
else engine.render(left.data() + at, n);
pos += chunk;
}
// The whole master stage is printed here rather than left for the processor, in the
// processor's own order — gain, then the limiter — because resetAfterBake hands both
// controls back neutral: a render that only summed voices would return every iteration
// shifted by 1/gain and unlimited, and a gain dialed to silence would come back at full
// level. A flat gain multiply, not the processor's per-sample ramp: the gain is constant
// for the whole render, which is exactly what that ramp exists to converge to.
const auto gain = static_cast<AudioSample>(masterGainLinear);
for (AudioSample& s : left) s *= gain;
for (AudioSample& s : right) s *= gain;
if (limiterEnabled) {
engine::Limiter limiter;
// Enabled BEFORE prepare, whose reset snaps to the enable target: that starts the
// render already engaged. Enabling afterwards takes process()'s live-engage path,
// which mutes for the delay-line prime and then fades in — silencing the head of the
// capture. prepare()'s allocation and transcendentals are legal here: the bake runs
// on the UI thread, never in process().
limiter.setEnabled(true);
limiter.prepare(plan.sampleRate);
// One call: kMaxBakeFrames bounds the whole buffer well inside int, and a block
// split would change nothing (the limiter carries its state across calls).
limiter.process(left.data(), channels == 2 ? right.data() : nullptr,
static_cast<int>(left.size()));
}
out.channelCount = channels;
out.sampleRate = plan.sampleRate;
const auto lead = static_cast<std::size_t>(plan.leadInFrames) + flushFrames;
const auto total = static_cast<std::size_t>(plan.totalFrames);
out.interleaved.resize(total * static_cast<std::size_t>(channels));
for (std::size_t f = 0; f < total; ++f) {
out.interleaved[f * channels] = left[lead + f];
if (channels == 2) out.interleaved[f * channels + 1] = right[lead + f];
}
return out;
}
} // namespace reasampler::instrument::bake
+40
View File
@@ -0,0 +1,40 @@
// bake_render — the offline pass: one programmed note through a voice engine built for
// this render alone, summed into an interleaved buffer.
//
// Never touches a live engine and never runs on the audio thread. Takes its SampleData BY
// VALUE for the reason this directory's CLAUDE.md records.
#pragma once
#include <cstdint>
#include <vector>
#include "core/instrument/bake/bake_plan.h"
#include "core/instrument/engine/play_params.h"
namespace reasampler::instrument::bake {
using audio::AudioSample;
struct BakeAudio {
std::vector<AudioSample> interleaved; // [f0c0, f0c1, f1c0, …]
int channelCount = 0; // 0 = nothing rendered
int sampleRate = 0;
std::int64_t frameCount() const {
return channelCount > 0
? static_cast<std::int64_t>(interleaved.size()) / channelCount
: 0;
}
bool empty() const { return frameCount() == 0; }
};
// Renders `plan` through `sample`'s own voice path and then the master stage the processor
// runs after the engine: `masterGainLinear`, then the limiter when `limiterEnabled` — see
// bake_render.cpp for why both print here rather than in the processor. `limiterEnabled`
// false yields the pre-limiter render. The result is the plan's captured window: the
// lead-in frames are rendered and dropped. An unplayable sample yields an empty result.
BakeAudio renderBake(SampleData sample, const BakePlan& plan, double masterGainLinear,
bool limiterEnabled);
} // namespace reasampler::instrument::bake
+29
View File
@@ -0,0 +1,29 @@
// See bake_reset.h.
#include "core/instrument/bake/bake_reset.h"
namespace reasampler::instrument::bake {
BakeReset resetAfterBake(const map::InstrumentParams& dialed) {
BakeReset out;
// The root is what the note was rendered at, so it is exactly what the new capture
// plays back at unity — resetting it would detune every following iteration.
out.params.rootOverride = dialed.rootOverride;
// How far pitch tracks the keyboard is a fact about the mapping; a single rendered
// note carries no trace of it.
out.params.keyTrack = dialed.keyTrack;
// There is no key-range parameter to carry (core/instrument/CLAUDE.md: no key-range
// concept) — if one is ever added it belongs on this list, not in the defaults.
// Play mode is on neither ratified list, so it is classified here, and the acceptance
// criteria decide it: the bake's product is a finished one-shot carrying its own
// attack, span and release. Trigger plays that back verbatim — note-off ignored, the
// default AHD flat at unity over the whole span. Gate would re-gate it: the default
// release would cut the printed tail at note-off, and every further iteration would cut
// the previous one's again. "Neutral" for this control means "adds no processing",
// which is Trigger, not the value struct's own Gate default.
out.params.play.playMode = PlayMode::Trigger;
return out;
}
} // namespace reasampler::instrument::bake
+26
View File
@@ -0,0 +1,26 @@
// bake_reset — hand the instrument back neutral after a bake: the dialed processing now
// lives in the recaptured audio, so the controls that produced it return to their defaults.
//
// The rule, ratified by Daniel: a control resets iff its effect is in the printed audio; a
// MAPPING fact survives, because it describes how the file is played, not how it was made.
#pragma once
#include "core/instrument/map/sample_map.h" // InstrumentParams
namespace reasampler::instrument::bake {
// The two surfaces a bake resets. Master gain lives on the processor rather than in the
// parameter set; it is answered here because renderBake prints it into the file (see
// bake_render.cpp's master stage) rather than left to the shell. The limiter needs no field
// of its own: its enable rides the parameter set, and the render prints it too.
struct BakeReset {
map::InstrumentParams params;
double masterGainLinear = 1.0; // unity — renderBake printed the dialed gain
};
// Everything defaults; the survivors are copied back explicitly (this directory's CLAUDE.md
// owns why that direction, and which classifications are ratified).
BakeReset resetAfterBake(const map::InstrumentParams& dialed);
} // namespace reasampler::instrument::bake
+65 -1
View File
@@ -5,6 +5,12 @@ reasampler_pure_library(pitch_shift SOURCES pitch_shift.cpp LINK PUBLIC peaks)
# specifically the compile-time proof it does not drag in the WDL <windows.h> chain.
reasampler_test(pitch_shift LINK pitch_shift)
# Deliberately NOT linked by sampler_core, enforcing period_detect.h's off-audio-thread
# invariant at build time: sampler_core_tests links sampler_core and nothing else, so no TU
# on the render path can name detectPeriod without failing to link.
reasampler_pure_library(period_detect SOURCES period_detect.cpp LINK PUBLIC peaks)
reasampler_test(period_detect LINK period_detect)
reasampler_pure_library(velocity_curve SOURCES velocity_curve.cpp)
# Links only velocity_curve, deliberately not editor_geometry: the proof the engine can
# depend on the curve without inheriting the editor's layout types.
@@ -16,12 +22,24 @@ reasampler_test(master_gain LINK master_gain)
# Declared before sampler_core because the voice now runs one per sounding note.
add_subdirectory(filter)
# The sustain loop's validity + crossfade geometry, shared by the voice and the editor's
# marker layer. After filter: it links play_params' dependency set, which includes it.
add_subdirectory(loop)
# The live-parameter block: the value layer plus its publication, deliberately linking no
# engine the block is a plain value the voice observes, not a thing the engine owns.
reasampler_pure_library(live_params
SOURCES live_params.cpp
LINK PUBLIC peaks velocity_curve filter curve_law)
reasampler_test(live_params LINK live_params)
# Two TUs on the engine's own responsibility seam (per-note setup vs. note routing and
# block render). The per-sample render half stays inline in voice.h precisely so this TU
# boundary costs the hot path nothing.
reasampler_pure_library(sampler_core
SOURCES voice.cpp voice_engine.cpp
LINK PUBLIC peaks pitch_shift velocity_curve filter)
LINK PUBLIC peaks pitch_shift velocity_curve filter live_params curve_law loop_span
time_stretch)
# Links only sampler_core: linking more would break the plain-data-boundary proof a VST3
# or REAPER type reaching the core would fail to compile or link here.
reasampler_test(sampler_core LINK sampler_core)
@@ -29,3 +47,49 @@ reasampler_test(sampler_core LINK sampler_core)
# The filter's own seams are covered by the four targets in filter/; this one covers the
# integration: pipeline order, per-voice independence, and the off-by-default bit-identity.
reasampler_test(sampler_filter LINK sampler_core)
# Live delivery is the third integration seam over the same engine: what a published block
# does to a voice that is already sounding, and what it must leave alone.
reasampler_test(live_delivery LINK sampler_core)
# The staged-envelope system across the same engine: per-segment curves, the sustain-less AHD
# both mode shapes share, and the Trigger tail's terminal behaviour.
reasampler_test(staged_envelopes LINK sampler_core)
# Measurement harness for Preserve on low-frequency material: how the splice search's
# reachable relocation interval interacts with a long source period. Written longhand and
# deliberately NOT add_test()'d it sweeps frequencies, windows and spectra and takes ~2m40s
# in Debug, which does not belong in a gate whose other targets run in seconds. It still
# builds with everything else, so it cannot rot into non-compilation. Run it by hand, in
# Release, when the question is what Preserve does to a given frequency.
add_executable(preserve_low_frequency_tests
${REASAMPLER_TESTS_DIR}/test_preserve_low_frequency.cpp)
# period_detect beside sampler_core, not through it: the harness plays the role the loader
# does, which is exactly the seam under measurement.
target_link_libraries(preserve_low_frequency_tests PRIVATE sampler_core period_detect)
# Bridges the two structural proofs above (sample_map never links the voice engine;
# sampler_core never links period_detect) for the one case that needs both: a REAL detected
# period reaching a real Preserve render. Its own target rather than extending either.
reasampler_test(period_render_integration LINK sample_map sampler_core)
# The Preserve read's source-feed schedule the TIME half beside pitch_shift's PITCH half.
# Header-only (it sits on the per-sample feed), hence INTERFACE.
add_library(time_stretch INTERFACE)
target_include_directories(time_stretch INTERFACE ${REASAMPLER_SRC_DIR})
target_link_libraries(time_stretch INTERFACE loop_span)
reasampler_test(time_stretch LINK time_stretch)
# The master bus's two pure halves. Neither links the engine: the limiter runs on the summed
# output, and the ballistics run on what the audio thread published about it.
reasampler_pure_library(limiter SOURCES limiter.cpp)
reasampler_test(limiter LINK limiter)
reasampler_pure_library(meter_ballistics SOURCES meter_ballistics.cpp)
reasampler_test(meter_ballistics LINK meter_ballistics)
# The meter's ACCUMULATE half, beside the ballistics that consume it. Header-only (the folds
# sit on the audio thread's per-block path), hence INTERFACE.
add_library(meter_accumulate INTERFACE)
target_include_directories(meter_accumulate INTERFACE ${REASAMPLER_SRC_DIR})
reasampler_test(meter_accumulate LINK meter_accumulate)
+353 -127
View File
@@ -1,6 +1,6 @@
#pragma once
// envelopes.h — the three per-frame envelope evaluators (AHDSR amplitude, Trigger fade
// shape, AD pitch offset). Concrete classes, every body defined in-class: these are called
// envelopes.h — the three per-frame envelope evaluators (AHDSR amplitude, sustain-less AHD,
// AHD pitch offset). Concrete classes, every body defined in-class: these are called
// per-voice-per-sample from Voice::advanceFrame, so they must inline into the render loop.
// NEVER give them a common base or a virtual tick() — that vtable lands on the hottest
// inner loop in the program (root CLAUDE.md, structural heuristic 3).
@@ -9,9 +9,97 @@
#include <cstdint>
#include "core/instrument/engine/play_params.h"
#include "core/util/curve_law.h"
namespace reasampler {
using util::curveMap;
// The A/H/D split of a bounded span, in frames.
struct AhdSpan {
std::int64_t attack = 0;
std::int64_t hold = 0;
std::int64_t decay = 0;
std::int64_t total = 0; // attack + hold + decay; <= span by construction
};
// THE span split, shared by every sustain-less envelope so they cannot disagree about where a
// stage boundary is. Attack takes at most the whole span and Decay at most what Attack left,
// so `remaining` is non-negative without a clamp; Hold then takes its FRACTION of that
// remainder, which is why total <= span holds for every (attack, decay, fraction) triple and
// there is no sum to clamp. The two per-stage mins reproduce the retired Trigger fade clamp
// exactly (head first, tail into what is left), so a migrated instance keeps its stage lengths.
inline AhdSpan fitAhd(std::int64_t spanFrames, const AhdParams& p) {
AhdSpan out;
const std::int64_t span = spanFrames > 0 ? spanFrames : 0;
std::int64_t a = p.attackFrames > 0 ? p.attackFrames : 0;
if (a > span) a = span;
std::int64_t d = p.decayFrames > 0 ? p.decayFrames : 0;
if (d > span - a) d = span - a;
const std::int64_t remaining = span - a - d;
double frac = p.holdFraction;
if (!(frac > 0.0)) frac = 0.0; // also catches NaN
if (frac > 1.0) frac = 1.0;
out.attack = a;
out.decay = d;
out.hold = static_cast<std::int64_t>(static_cast<double>(remaining) * frac + 0.5);
out.total = out.attack + out.hold + out.decay;
return out;
}
// The AHD's normalized level at `offset` frames into the span: 0 -> 1 over attack, flat 1
// across hold, 1 -> 0 over decay, 0 outside. Pure over the offset so both the ticking pitch
// envelope and the positional amplitude one read one shape.
inline double ahdLevelAt(double offset, const AhdSpan& s, double attackCurve,
double decayCurve) {
if (offset < 0.0 || offset >= static_cast<double>(s.total)) return 0.0;
if (s.attack > 0 && offset < static_cast<double>(s.attack)) {
return curveMap(offset / static_cast<double>(s.attack), attackCurve);
}
const double decayStart = static_cast<double>(s.total - s.decay);
if (s.decay > 0 && offset >= decayStart) {
double t = (offset - decayStart) / static_cast<double>(s.decay);
if (t > 1.0) t = 1.0;
return 1.0 - curveMap(t, decayCurve);
}
return 1.0;
}
// Absorbs a step a live parameter move would otherwise put straight into an evaluator's
// output, as an offset that decays to EXACTLY zero — so the at-rest path carries no residue
// and the smoother's own branch stays predictably false. Per-frame decay rather than a
// wall-clock one, matching the voice's takeover declick; the floor is far below both domains
// this is used in (amplitude, and semitones of pitch offset).
class StepSmoother {
public:
// `step` is (level before the change - level after it): adding it back reproduces the
// pre-change output exactly on the first frame.
void absorb(double step) {
offset_ += step;
active_ = (offset_ > kFloor || offset_ < -kFloor);
if (!active_) offset_ = 0.0;
}
void clear() { offset_ = 0.0; active_ = false; }
bool active() const { return active_; }
// This frame's offset; decays afterwards, latching inactive at the floor.
double advance() {
const double out = offset_;
offset_ *= kDecay;
if (offset_ < kFloor && offset_ > -kFloor) {
offset_ = 0.0;
active_ = false;
}
return out;
}
private:
static constexpr double kDecay = 0.95;
static constexpr double kFloor = 1e-5;
double offset_ = 0.0;
bool active_ = false;
};
// AHDSR amplitude envelope, sample-based (times in frames), linear segments. A gate:
// noteOn() enters Attack; noteOff() enters Release from wherever it is.
//
@@ -24,6 +112,11 @@ namespace reasampler {
// A zero-length attack jumps straight to 1 on the first frame; holdFrames == 0 skips Hold
// entirely (the pre-hold-stage ADSR, back-compat); zero decay jumps to sustain; a noteOff
// during attack/hold/decay releases from the current partial level, not from sustainLevel.
//
// stagePos_ is the elapsed position within the current stage. It is a double rather than a
// frame count only so applyLive can hold a fractional normalized position; every value it
// takes on the un-edited path is integral, so the segment math is bit-identical to the
// integer-counter engine.
class AdsrEnvelope {
public:
enum class Stage { Idle, Attack, Hold, Decay, Sustain, Release, Finished };
@@ -34,25 +127,124 @@ public:
void noteOn() {
stage_ = Stage::Attack;
level_ = 0.0;
framesInStage_ = 0;
stagePos_ = 0.0;
smooth_.clear();
}
// Gate off: enter Release from the CURRENT level — release-before-sustain releases from
// the partial attack/decay level, not from sustainLevel.
// the partial attack/decay level, not from sustainLevel. A running smoother deliberately
// survives: it is mid-glide, and cutting it here would reintroduce the step it absorbed.
void noteOff() {
if (stage_ == Stage::Idle || stage_ == Stage::Finished || stage_ == Stage::Release) {
return; // already released / not sounding.
}
releaseFrom_ = level_;
stage_ = Stage::Release;
framesInStage_ = 0;
stagePos_ = 0.0;
}
// Live parameter delivery to a fresh voice — one that has NOT yet rendered a frame, whose
// latched copy may predate the newest edit. It takes the params outright: there is no
// phase to hold and nothing to be continuous with. applyLive cannot serve here in either
// direction — with a stale duration of 0 its phi rule reads stagePos_ == 0 as a COMPLETED
// stage and discards the newly-dialled time, and with a stale duration > 0 against a new 0
// it absorbs a full-scale step into a voice that has emitted nothing, fading the onset in.
void snapLive(const AdsrParams& params) {
params_ = params;
smooth_.clear();
}
// Live parameter delivery to a SOUNDING voice. The mid-stage rule is HOLD NORMALIZED
// STAGE POSITION: phi = elapsed/duration is kept fixed across the change, so this frame's
// level is unchanged by construction and the remainder of the stage takes its share of the
// newly-dialled duration. The rule is expressed over normalized position, never over
// output level, so a per-segment curve exponent composes with it as a pure map of phi.
//
// Two cases phi cannot cover, both absorbed by the smoother rather than allowed to step:
// a sustain level moved while the voice holds it (sustain is a level, not a timed stage),
// and a stage duration dialled to exactly zero mid-stage (the stage ceases to exist and
// completes at its terminal level).
void applyLive(const AdsrParams& params) {
const double before = stageLevel(params_);
const double oldDuration = stageDuration(params_);
const double newDuration = stageDuration(params);
if (newDuration > 0.0) {
stagePos_ = (oldDuration > 0.0) ? stagePos_ * (newDuration / oldDuration)
: newDuration; // a collapsed stage was complete
}
params_ = params;
const double after = stageLevel(params_);
if (after != before) smooth_.absorb(before - after);
}
// Advances one frame and returns the amplitude for THIS frame (before advancing).
// Once Release completes the envelope latches Finished and returns 0.0 forever (until
// the next noteOn). A single, monotonic per-frame step — the caller pulls one value per
// output frame.
//
// While the smoother runs the return may sit OUTSIDE [0,1] by the offset it is decaying
// (bounded by the step it absorbed). finished() ignores that residue, so a Release that
// completes with an offset still decaying is hard-cut when the voice frees — the audible
// remainder of a step the smoother had already taken most of.
double tick() {
const double out = tickStage();
return smooth_.active() ? out + smooth_.advance() : out;
}
Stage stage() const { return stage_; }
bool finished() const { return stage_ == Stage::Finished; }
double level() const { return level_; }
private:
// The level tick() would emit right now under `params` without advancing anything. THE one
// home for every segment's shape: tickStage owns only the advance and the stage
// transitions and reads its output from here, so a per-segment curve added later lands in
// one place and the smoother can never size a step against a different curve than the
// output takes.
double stageLevel(const AdsrParams& params) const {
switch (stage_) {
case Stage::Attack: {
if (params.attackFrames <= 0) return 1.0;
double l = stagePos_ / static_cast<double>(params.attackFrames);
if (l > 1.0) l = 1.0;
return curveMap(l, params.attackCurve);
}
case Stage::Hold:
// A zero-length hold falls straight through to Decay on the next tick, whose
// level at position 0 is 1.0 — unless decay is zero too, which lands on sustain.
if (params.holdFrames > 0) return 1.0;
return (params.decayFrames <= 0) ? params.sustainLevel : 1.0;
case Stage::Decay: {
if (params.decayFrames <= 0) return params.sustainLevel;
double t = stagePos_ / static_cast<double>(params.decayFrames);
if (t > 1.0) t = 1.0; // never bites on the un-edited path (transitions at >=)
return 1.0 + (params.sustainLevel - 1.0) * curveMap(t, params.decayCurve);
}
case Stage::Sustain:
return params.sustainLevel;
case Stage::Release: {
if (params.releaseFrames <= 0) return 0.0;
double t = stagePos_ / static_cast<double>(params.releaseFrames);
if (t > 1.0) t = 1.0;
return releaseFrom_ * (1.0 - curveMap(t, params.releaseCurve));
}
default:
return 0.0;
}
}
// The current stage's dialled duration under `params`; 0 for the untimed stages.
double stageDuration(const AdsrParams& params) const {
switch (stage_) {
case Stage::Attack: return static_cast<double>(params.attackFrames);
case Stage::Hold: return static_cast<double>(params.holdFrames);
case Stage::Decay: return static_cast<double>(params.decayFrames);
case Stage::Release: return static_cast<double>(params.releaseFrames);
default: return 0.0;
}
}
double tickStage() {
switch (stage_) {
case Stage::Idle:
case Stage::Finished:
@@ -60,19 +252,13 @@ public:
return 0.0;
case Stage::Attack: {
if (params_.attackFrames <= 0) {
level_ = 1.0;
} else {
level_ = static_cast<double>(framesInStage_) /
static_cast<double>(params_.attackFrames);
if (level_ > 1.0) level_ = 1.0;
}
level_ = stageLevel(params_);
const double out = level_;
++framesInStage_;
if (framesInStage_ >= params_.attackFrames) {
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.attackFrames)) {
// holdFrames == 0 falls straight through Hold on the next tick to Decay.
stage_ = Stage::Hold;
framesInStage_ = 0;
stagePos_ = 0.0;
level_ = 1.0;
}
return out;
@@ -84,43 +270,38 @@ public:
// extra sample.
if (params_.holdFrames <= 0) {
stage_ = Stage::Decay;
framesInStage_ = 0;
stagePos_ = 0.0;
level_ = 1.0;
// Single re-dispatch into Decay (bounded: Hold->Decay only, not general
// recursion).
return tick();
// recursion). Re-enters the STAGE evaluator, never tick(), so a running
// smoother is applied exactly once per frame.
return tickStage();
}
level_ = 1.0;
level_ = stageLevel(params_);
const double out = level_;
++framesInStage_;
if (framesInStage_ >= params_.holdFrames) {
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.holdFrames)) {
stage_ = Stage::Decay;
framesInStage_ = 0;
stagePos_ = 0.0;
level_ = 1.0;
}
return out;
}
case Stage::Decay: {
if (params_.decayFrames <= 0) {
level_ = params_.sustainLevel;
} else {
const double t = static_cast<double>(framesInStage_) /
static_cast<double>(params_.decayFrames);
level_ = 1.0 + (params_.sustainLevel - 1.0) * t;
}
level_ = stageLevel(params_);
const double out = level_;
++framesInStage_;
if (framesInStage_ >= params_.decayFrames) {
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.decayFrames)) {
stage_ = Stage::Sustain;
framesInStage_ = 0;
stagePos_ = 0.0;
level_ = params_.sustainLevel;
}
return out;
}
case Stage::Sustain:
level_ = params_.sustainLevel;
level_ = stageLevel(params_);
return level_;
case Stage::Release: {
@@ -129,13 +310,10 @@ public:
stage_ = Stage::Finished;
return 0.0;
}
const double t = static_cast<double>(framesInStage_) /
static_cast<double>(params_.releaseFrames);
level_ = releaseFrom_ * (1.0 - t);
if (level_ < 0.0) level_ = 0.0;
level_ = stageLevel(params_);
const double out = level_;
++framesInStage_;
if (framesInStage_ >= params_.releaseFrames) {
stagePos_ += 1.0;
if (stagePos_ >= static_cast<double>(params_.releaseFrames)) {
stage_ = Stage::Finished;
level_ = 0.0;
}
@@ -145,122 +323,170 @@ public:
return 0.0; // unreachable; silences a warning.
}
Stage stage() const { return stage_; }
bool finished() const { return stage_ == Stage::Finished; }
double level() const { return level_; }
private:
AdsrParams params_;
Stage stage_ = Stage::Idle;
double level_ = 0.0;
std::int64_t framesInStage_ = 0;
double stagePos_ = 0.0;
double releaseFrom_ = 0.0; // level at the moment noteOff() was called
StepSmoother smooth_;
};
// A stateless-shape amplitude function over the play span, evaluated at a source-frame
// offset into the span (not output frames): under Varispeed a transposed voice consumes
// source faster than output, so driving the fades off the read position keeps fade-in/out
// anchored to the same source frames regardless of engine. Distinct from AHDSR —
// time-boxed by the play length and note-off-immune.
class TriggerEnvelope {
public:
// `playLengthFrames` is (playEnd - startFrame). Fades are clamped so
// fadeIn + fadeOut <= playLength (fadeOut anchored to the end). A zero/negative play
// length finishes immediately.
void configure(std::int64_t playLengthFrames, std::int64_t fadeInFrames,
std::int64_t fadeOutFrames, FadeCurve curve = kDefaultFadeCurve) {
playLength_ = playLengthFrames > 0 ? playLengthFrames : 0;
curve_ = curve;
finished_ = (playLength_ <= 0);
// Clamp the fades so fadeIn + fadeOut <= playLength (fade-out anchored to the end).
// A negative fade is treated as 0. When both fades together exceed the play length,
// shrink the fade-out first (the head fade-in is the more perceptually load-bearing
// onset ramp), then the fade-in — never letting either go negative or the sum exceed
// the span.
std::int64_t fi = fadeInFrames > 0 ? fadeInFrames : 0;
std::int64_t fo = fadeOutFrames > 0 ? fadeOutFrames : 0;
if (fi > playLength_) fi = playLength_;
if (fi + fo > playLength_) fo = playLength_ - fi; // fo >= 0 since fi <= playLength_
fadeIn_ = fi;
fadeOut_ = fo;
// The sustain-less AHD amplitude shape, evaluated at a source-frame offset into the span
// rather than by ticking output frames: under Varispeed a transposed voice consumes source
// faster than output, so driving the shape off the read position keeps every stage boundary on
// the same source frames regardless of engine. Note-off-immune and time-boxed by the span.
//
// Positional means there is no phase counter to hold across a live edit, so the phi rule
// AdsrEnvelope applies has nothing to act on here; a live reshape is a level step, absorbed by
// the same bounded smoother.
class AhdEnvelope {
public:
// `spanFrames` is the bound the stages are fitted into — (playEnd - startFrame) for the
// Trigger amp and filter envelopes. A zero/negative span finishes immediately.
void configure(std::int64_t spanFrames, const AhdParams& params) {
span_ = spanFrames > 0 ? spanFrames : 0;
fit(params, /*latchFinished=*/false); // a fresh note starts from a clean read
smooth_.clear();
}
// Amplitude in [0,1] at `sourceOffset` = (readPos - startFrame). Latches finished() at
// or past playLength. Pure over the offset so it composes with either pitch engine's
// read rate.
// Peer of AdsrEnvelope::snapLive: a voice that has rendered nothing takes the new shape
// outright, with no step to absorb.
void snapLive(const AhdParams& params) {
fit(params, /*latchFinished=*/false);
smooth_.clear();
}
// Live delivery to a sounding voice at its current `sourceOffset`. See the class note for
// why this smooths rather than holding a normalized position.
void applyLive(double sourceOffset, const AhdParams& params) {
const double before = ahdLevelAt(sourceOffset, fit_, attackCurve_, decayCurve_);
// LATCHED: a voice already read past its fitted total must never resurge because a
// later live move reopened the total. Reachable on any active() voice, including one
// ringing out past its own end (voice.h) where tickAmplitude() still runs.
fit(params, /*latchFinished=*/true);
const double after = ahdLevelAt(sourceOffset, fit_, attackCurve_, decayCurve_);
if (after != before) smooth_.absorb(before - after);
}
// Amplitude at `sourceOffset` = (readPos - startFrame). Latches finished() at or past the
// fitted total, which is what frees the voice.
double amplitudeAt(double sourceOffset) {
if (finished_ || sourceOffset < 0.0 ||
sourceOffset >= static_cast<double>(playLength_)) {
// At/past the play length the one-shot is done; the voice also frees on
// readPos >= playEnd.
if (sourceOffset >= static_cast<double>(playLength_)) finished_ = true;
if (finished_ || sourceOffset >= static_cast<double>(fit_.total)) {
if (sourceOffset >= static_cast<double>(fit_.total)) finished_ = true;
return 0.0;
}
// Fade-in: 0->1 over [0, fadeIn_). Fade-out: 1->0 over
// [playLength_-fadeOut_, playLength_). Unity between. The two ramps never overlap
// (configure clamps fadeIn_ + fadeOut_ <= length). The offset is fractional (the read
// head is fractional under repitch), so the ramps are smooth rather than stepped.
double amp = 1.0;
const double foStart = static_cast<double>(playLength_ - fadeOut_);
if (fadeIn_ > 0 && sourceOffset < static_cast<double>(fadeIn_)) {
const double phase = sourceOffset / static_cast<double>(fadeIn_); // 0..1
amp = (curve_ == FadeCurve::EqualPower)
? std::sin(phase * 1.5707963267948966) // sin(phase*pi/2): constant power
: phase;
} else if (fadeOut_ > 0 && sourceOffset >= foStart) {
const double phase = (sourceOffset - foStart) / static_cast<double>(fadeOut_);
amp = (curve_ == FadeCurve::EqualPower)
? std::cos(phase * 1.5707963267948966) // cos(phase*pi/2): constant power
: (1.0 - phase);
}
return amp;
const double out = ahdLevelAt(sourceOffset, fit_, attackCurve_, decayCurve_);
return smooth_.active() ? out + smooth_.advance() : out;
}
bool finished() const { return finished_; }
const AhdSpan& stages() const { return fit_; }
private:
std::int64_t playLength_ = 0;
std::int64_t fadeIn_ = 0;
std::int64_t fadeOut_ = 0;
FadeCurve curve_ = kDefaultFadeCurve;
bool finished_ = false;
// `latchFinished`: once true, a re-fit can only ever KEEP finished_ true, never clear it —
// see applyLive above for why. configure()/snapLive() pass false: those are a fresh read
// (new note or a not-yet-rendered voice), which must compute finished_ from scratch.
void fit(const AhdParams& p, bool latchFinished) {
fit_ = fitAhd(span_, p);
attackCurve_ = p.attackCurve;
decayCurve_ = p.decayCurve;
const bool empty = (fit_.total <= 0);
finished_ = latchFinished ? (finished_ || empty) : empty;
}
std::int64_t span_ = 0;
AhdSpan fit_;
double attackCurve_ = util::kCurveNeutral;
double decayCurve_ = util::kCurveNeutral;
bool finished_ = true;
StepSmoother smooth_;
};
// tick() returns the current pitch offset in semitones (0 when disabled or past
// attack+decay), advancing one frame. The voice converts it to a ratio multiply
// (Varispeed) or a shift-amount add (Preserve).
// tick() returns the current pitch offset in semitones (0 when disabled or past the AHD),
// advancing one frame. The voice converts it to a ratio multiply (Varispeed) or a shift-amount
// add (Preserve). Unlike the amplitude AHD this owns its own position counter — pitch-envelope
// time is wall-clock output frames — so the mid-stage rule applies in full.
class PitchEnvelope {
public:
void configure(const PitchEnvParams& params) { params_ = params; pos_ = 0; }
void noteOn() { pos_ = 0; }
// `spanFrames` is the playable span the Hold fraction is taken against.
void configure(std::int64_t spanFrames, const PitchEnvParams& params) {
span_ = spanFrames > 0 ? spanFrames : 0;
params_ = params;
fit_ = fitAhd(span_, params.shape);
pos_ = 0.0;
}
void noteOn() { pos_ = 0.0; smooth_.clear(); }
// Peer of AdsrEnvelope::snapLive (see it for why the two paths cannot share code): a voice
// that has rendered nothing takes the new shape and depth outright. `enabled` is a discrete
// toggle travelling by reload, so the caller's copy of it is deliberately ignored.
//
// Both live entry points re-take `spanFrames` rather than keeping configure()'s: the span is
// an OUTPUT-frame duration the caller converts from the read rate, and that rate carries a
// live control (voice.h's pitchEnvSpanFrames). Passing the span back unchanged is exact.
void snapLive(std::int64_t spanFrames, const PitchEnvParams& params) {
span_ = spanFrames > 0 ? spanFrames : 0;
params_.peakSemitones = params.peakSemitones;
params_.shape = params.shape;
fit_ = fitAhd(span_, params_.shape);
smooth_.clear();
}
// Live parameter delivery, same rule as AdsrEnvelope::applyLive: hold the normalized
// position within whichever leg the envelope is in, and absorb the depth step (peak is a
// level, not a duration). A moved span re-fits under the same rule, so a live Pitch move
// reshapes this envelope continuously instead of leaving it on the note-on read rate.
void applyLive(std::int64_t spanFrames, const PitchEnvParams& params) {
const double before = offsetAt();
span_ = spanFrames > 0 ? spanFrames : 0;
const AhdSpan next = fitAhd(span_, params.shape);
pos_ = holdPhase(fit_, next);
params_.peakSemitones = params.peakSemitones;
params_.shape = params.shape;
fit_ = next;
const double after = offsetAt();
if (after != before) smooth_.absorb(before - after);
}
double tick() {
if (!params_.enabled) return 0.0;
const std::int64_t a = params_.attackFrames > 0 ? params_.attackFrames : 0;
const std::int64_t d = params_.decayFrames > 0 ? params_.decayFrames : 0;
const double peak = params_.peakSemitones;
double offset;
if (pos_ < a) {
// Attack: 0 -> peak over attackFrames (rise into the peak).
offset = peak * (static_cast<double>(pos_) / static_cast<double>(a));
} else if (pos_ < a + d) {
// Decay: peak -> 0 over decayFrames (settle to base pitch).
const double t = static_cast<double>(pos_ - a) / static_cast<double>(d);
offset = peak * (1.0 - t);
} else {
offset = 0.0; // past attack+decay: at base pitch forever.
}
++pos_;
return offset;
const double offset = offsetAt();
pos_ += 1.0;
return smooth_.active() ? offset + smooth_.advance() : offset;
}
private:
// The semitone offset at the current position — the shared evaluator for both tick() and
// applyLive's before/after comparison.
double offsetAt() const {
if (!params_.enabled) return 0.0;
return params_.peakSemitones *
ahdLevelAt(pos_, fit_, params_.shape.attackCurve, params_.shape.decayCurve);
}
// The position under `next` holding the normalized position within whichever leg pos_ is
// in. A leg dialled to zero completes: the position lands on that leg's new end.
double holdPhase(const AhdSpan& old, const AhdSpan& next) const {
const double oa = static_cast<double>(old.attack);
const double oh = static_cast<double>(old.hold);
const double od = static_cast<double>(old.decay);
const double na = static_cast<double>(next.attack);
const double nh = static_cast<double>(next.hold);
const double nd = static_cast<double>(next.decay);
if (pos_ < oa) return (na > 0.0) ? pos_ * (na / oa) : na;
if (pos_ < oa + oh) return (nh > 0.0) ? na + (pos_ - oa) * (nh / oh) : na + nh;
if (pos_ < oa + oh + od) {
return (nd > 0.0) ? na + nh + (pos_ - oa - oh) * (nd / od) : na + nh + nd;
}
return na + nh + nd; // already past the envelope: stay past it under the new shape
}
PitchEnvParams params_;
std::int64_t pos_ = 0;
std::int64_t span_ = 0;
AhdSpan fit_;
double pos_ = 0.0;
StepSmoother smooth_;
};
} // namespace reasampler
@@ -234,6 +234,13 @@ topology.
genuinely ~0.02% low at 48 kHz, widening to ~0.03% low at 192 kHz — real coefficient
narrowing, not measurement-window noise, and comfortably inside the test's 0.4% tolerance
either way. Do not reintroduce a direct-form kernel.
- **A coefficient jump here produces no isolated output spike, measured.** Preserving state
across `prepare()` is strong enough that even an instantaneous cutoff/Q/morph jump leaves the
boundary frame inside the signal's own frame-to-frame range — a single-frame-spike metric
cannot detect one. What the caller's per-frame glide prevents is therefore the *parameter*
arriving as a step (and the zipper of repeated steps at control rate), not a click at the
jump itself. A test claiming to prove the glide must measure how fast the output diverges,
not how far one frame moves; `live_delivery_tests` does.
- **`prepare()` deliberately does not clear state** — a live parameter move must glide, not
click. Call `reset()` at note-on. **Exception: the non-positive-rate bypass path.** There,
`a1=1, a2=a3=0` makes both state updates the exact identity and `bypassMix()` never reads
@@ -1,10 +1,16 @@
# Control mapping, SVF coefficients, morph weights, and the filter type each get their own
# TU; VoiceFilter::process stays header-inline so the kernel still inlines at the call site.
# The frozen control-position laws are their own target: they are the filter's PARAMETER
# surface, and the VST3 parameter layer reports Hz/Q/drive through them. Kept separable so
# that consumer does not take a link edge onto the per-voice kernel the extension's link
# graph must never be able to reach the voice DSP (root CLAUDE.md, the bake invariant).
reasampler_pure_library(filter_params SOURCES filter_params.cpp)
reasampler_pure_library(filter SOURCES
filter_params.cpp
filter_coeffs.cpp
filter_morph.cpp
voice_filter.cpp)
voice_filter.cpp
LINK PUBLIC filter_params)
# Four test targets along the module's own seams so each asserts one domain. filter_tests
# alone owns the analytic reference and the steady-state gain measurement a forked copy of
@@ -52,6 +52,13 @@ float filterDriveDepthFromNorm(float norm) {
return static_cast<float>(kFilterDriveDepthMax * n * n);
}
float filterNormFromDriveDepth(float depth) {
if (!(depth > 0.0f)) return 0.0f; // also catches NaN
if (depth >= kFilterDriveDepthMax) return 1.0f;
return static_cast<float>(
std::sqrt(static_cast<double>(depth) / static_cast<double>(kFilterDriveDepthMax)));
}
float filterNormFromQ(float q) {
if (!(q > kFilterQMin)) return 0.0f;
if (q >= kFilterQMax) return 1.0f;
@@ -49,4 +49,9 @@ float filterNormFromQ(float q);
// linear rather than merely close.
float filterDriveDepthFromNorm(float norm);
// Exact inverse of filterDriveDepthFromNorm; out-of-range depth clamps to 0 or 1. The analytic
// inverse of a frozen law is not a change to it — it has the standing the two inverses above
// already have.
float filterNormFromDriveDepth(float depth);
} // namespace reasampler::instrument::engine::filter
+227
View File
@@ -0,0 +1,227 @@
// limiter.cpp — see limiter.h.
#include "core/instrument/engine/limiter.h"
#include <algorithm>
#include <cmath>
namespace reasampler::instrument::engine {
namespace {
constexpr int kProtoLen = kLimiterOversample * kLimiterOsTaps + 1; // 33: odd, so phase 0 is exact
double sincPi(double x) {
if (x == 0.0) return 1.0;
const double a = 3.14159265358979323846 * x;
return std::sin(a) / a;
}
} // namespace
double limiterCeilingLinear() { return std::pow(10.0, kLimiterCeilingDbTp / 20.0); }
int limiterLookaheadSamples(double sampleRate) {
if (!(sampleRate > 0.0)) return 0;
const int n = static_cast<int>(kLimiterLookaheadSeconds * sampleRate + 0.5);
// One sample above the detector's group delay is the floor: the smoothing window must have
// at least one entry of its own for the no-overshoot bound to say anything.
return n > kLimiterOsDelay ? n : kLimiterOsDelay + 1;
}
void Limiter::prepare(double sampleRate) {
latency_ = limiterLookaheadSamples(sampleRate);
if (latency_ <= 0) latency_ = kLimiterOsDelay + 1;
window_ = latency_ - kLimiterOsDelay + 1;
ceiling_ = static_cast<float>(limiterCeilingLinear());
const double rate = sampleRate > 0.0 ? sampleRate : 48000.0;
releaseCoeff_ = static_cast<float>(1.0 - std::exp(-1.0 / (kLimiterReleaseSeconds * rate)));
switchStep_ = static_cast<float>(1.0 / (kLimiterMuteSeconds * rate));
// Windowed-sinc polyphase interpolator, built here because it costs transcendentals.
// Phase 0's taps all land on sinc zeros except the centre, so it is an exact delay and is
// read straight out of the history instead of being convolved.
for (int p = 0; p < kLimiterOversample; ++p) {
for (int k = 0; k < kLimiterOsTaps; ++k) {
const int i = kLimiterOversample * k + p;
const double centred = static_cast<double>(i) - (kProtoLen - 1) / 2.0;
const double hann =
0.5 - 0.5 * std::cos(2.0 * 3.14159265358979323846 * i / (kProtoLen - 1));
osTaps_[p][k] = static_cast<float>(sincPi(centred / kLimiterOversample) * hann);
}
}
delayL_.assign(static_cast<std::size_t>(latency_), 0.f);
delayR_.assign(static_cast<std::size_t>(latency_), 0.f);
wedgeVal_.assign(static_cast<std::size_t>(window_), 1.f);
wedgeIdx_.assign(static_cast<std::size_t>(window_), 0);
avgRing_.assign(static_cast<std::size_t>(window_), 1.f);
reset();
}
void Limiter::clearState() {
std::fill(delayL_.begin(), delayL_.end(), 0.f);
std::fill(delayR_.begin(), delayR_.end(), 0.f);
delayPos_ = 0;
for (int i = 0; i < kLimiterOsTaps; ++i) { histL_[i] = 0.f; histR_[i] = 0.f; }
histPos_ = 0;
wedgeHead_ = 0;
wedgeCount_ = 0;
pushIndex_ = 0;
std::fill(avgRing_.begin(), avgRing_.end(), 1.f);
avgSum_ = static_cast<double>(window_);
avgPos_ = 0;
releaseGain_ = 1.f;
}
void Limiter::reset() {
clearState();
active_ = target_.load(std::memory_order_relaxed);
switchGain_ = active_ ? 1.f : 0.f;
primeRemaining_ = 0;
}
void Limiter::setEnabled(bool on) { target_.store(on, std::memory_order_relaxed); }
float Limiter::detectTruePeak(float xl, float xr, bool stereo) {
histPos_ = (histPos_ + 1) & (kLimiterOsTaps - 1);
histL_[histPos_] = xl;
if (stereo) histR_[histPos_] = xr;
// Phase 0 is the exact delay, so the sample under test is read, not convolved.
const int base = (histPos_ - kLimiterOsDelay + kLimiterOsTaps) & (kLimiterOsTaps - 1);
float peak = std::fabs(histL_[base]);
if (stereo) {
const float r0 = std::fabs(histR_[base]);
if (r0 > peak) peak = r0;
}
for (int p = 1; p < kLimiterOversample; ++p) {
float accL = 0.f, accR = 0.f;
for (int k = 0; k < kLimiterOsTaps; ++k) {
const int idx = (histPos_ - k + kLimiterOsTaps) & (kLimiterOsTaps - 1);
accL += osTaps_[p][k] * histL_[idx];
if (stereo) accR += osTaps_[p][k] * histR_[idx];
}
const float al = std::fabs(accL);
if (al > peak) peak = al;
if (stereo) {
const float ar = std::fabs(accR);
if (ar > peak) peak = ar;
}
}
return peak;
}
float Limiter::smoothGain(float target) {
// Sliding minimum over `window_` via a monotonic wedge. Expiring the front BEFORE the push
// is what bounds the wedge to `window_` entries — pushing first can lap the ring. Wraps by
// compare-and-subtract, matching delayPos_/avgPos_: window_ is not a power of two, so `%`
// would not strength-reduce on this per-sample path.
while (wedgeCount_ > 0 &&
wedgeIdx_[static_cast<std::size_t>(wedgeHead_)] <= pushIndex_ - window_) {
wedgeHead_ = (wedgeHead_ + 1 == window_) ? 0 : wedgeHead_ + 1;
--wedgeCount_;
}
while (wedgeCount_ > 0) {
const int backSum = wedgeHead_ + wedgeCount_ - 1;
const int back = (backSum >= window_) ? backSum - window_ : backSum;
if (wedgeVal_[static_cast<std::size_t>(back)] < target) break;
--wedgeCount_;
}
const int slotSum = wedgeHead_ + wedgeCount_;
const int slot = (slotSum >= window_) ? slotSum - window_ : slotSum;
wedgeVal_[static_cast<std::size_t>(slot)] = target;
wedgeIdx_[static_cast<std::size_t>(slot)] = pushIndex_;
++wedgeCount_;
++pushIndex_;
const float windowMin = wedgeVal_[static_cast<std::size_t>(wedgeHead_)];
// Moving average of the same width over those minima.
avgSum_ += static_cast<double>(windowMin) - static_cast<double>(avgRing_[static_cast<std::size_t>(avgPos_)]);
avgRing_[static_cast<std::size_t>(avgPos_)] = windowMin;
avgPos_ = (avgPos_ + 1 == window_) ? 0 : avgPos_ + 1;
float smoothed = static_cast<float>(avgSum_ / window_);
// Never above unity — the structural form of "no makeup gain, ever", and what makes the
// at-rest gain land on EXACTLY 1.0f after the running sum has been added to and subtracted
// from for hours.
if (!(smoothed < 1.f)) smoothed = 1.f;
// Release: falls with the smoother, rises no faster than the one-pole. Staying at or below
// `smoothed` is what preserves the no-overshoot bound.
if (smoothed < releaseGain_) releaseGain_ = smoothed;
else releaseGain_ += (smoothed - releaseGain_) * releaseCoeff_;
return releaseGain_;
}
float Limiter::process(float* left, float* right, int frames) {
if (!left || frames <= 0 || latency_ <= 0) return 1.f;
const bool want = target_.load(std::memory_order_relaxed);
if (!want && !active_) return 1.f; // settled bypass: not one sample read or written
if (want && !active_) {
// A live engage. The dry path leaves circuit AT THIS SAMPLE rather than fading out:
// fading it would emit unlimited signal at a partial weight, which is a peak over the
// ceiling. Silence covers the delay line's prime, then the fade-in rides the limited
// path, every sample of which is already under the ceiling.
clearState();
active_ = true;
switchGain_ = 0.f;
primeRemaining_ = latency_;
}
const bool stereo = (right != nullptr);
float blockMin = 1.f;
for (int i = 0; i < frames; ++i) {
const float dryL = left[i];
const float dryR = stereo ? right[i] : 0.f;
const float peak = detectTruePeak(dryL, dryR, stereo);
const float targetGain = peak > ceiling_ ? ceiling_ / peak : 1.f;
const float gain = smoothGain(targetGain);
const std::size_t slot = static_cast<std::size_t>(delayPos_);
const float wetL = delayL_[slot] * gain;
const float wetR = stereo ? delayR_[slot] * gain : 0.f;
delayL_[slot] = dryL;
if (stereo) delayR_[slot] = dryR;
delayPos_ = (delayPos_ + 1 == latency_) ? 0 : delayPos_ + 1;
// Settled engaged is a branch rather than `wet * 1.0f` so it is bit-exact.
const float s = switchGain_;
if (s >= 1.f) {
left[i] = wetL;
if (stereo) right[i] = wetR;
} else if (s > 0.f) {
left[i] = wetL * s;
if (stereo) right[i] = wetR * s;
} else {
left[i] = 0.f;
if (stereo) right[i] = 0.f;
}
// `gain` is the limiter's own reduction, computed from the real input this sample
// whether or not the mute is currently scaling it toward silence — publishing it
// unscaled is what lets the meter show "really limiting" and not "just muting".
if (gain < blockMin) blockMin = gain;
// A disengage is tested FIRST so a toggle-off arriving mid-engage abandons the prime
// instead of waiting it out in silence.
if (!want) {
switchGain_ = s - switchStep_;
if (switchGain_ <= 0.f) {
// The disengage completes HERE, sample-accurately: the delay leaves circuit and
// the rest of the block is the dry buffer, untouched. Resuming from silence is
// the accepted discontinuity; fading the dry path back in instead would put
// unlimited signal at a partial weight, which is the leak the ceiling forbids.
switchGain_ = 0.f;
active_ = false;
break;
}
} else if (primeRemaining_ > 0) {
--primeRemaining_;
} else if (s < 1.f) {
switchGain_ = (s + switchStep_ >= 1.f) ? 1.f : s + switchStep_;
}
}
return blockMin;
}
} // namespace reasampler::instrument::engine
+129
View File
@@ -0,0 +1,129 @@
// limiter.h — the master bus's lookahead brickwall limiter: true-peak sidechain detection,
// stereo-linked gain, and NO makeup gain of any kind. RT: process() allocates nothing, takes
// no lock and evaluates no transcendental; prepare() owns every allocation and every exp/pow.
// Bypassed and settled, process() returns without touching a sample — that untouched buffer
// is what makes the master bus byte-identical to the bare ramped multiply with the limiter off.
#pragma once
#include <atomic>
#include <cstdint>
#include <vector>
namespace reasampler::instrument::engine {
// The BAKED ceiling. A safety device with no configurable controls, so this is not a
// parameter. dBTP is a TRUE-peak target, which is why the detector oversamples and the
// signal path never does — though the bound is on the detector's 4x-oversampled ESTIMATE,
// not infinite-resolution true peak (normal for any practical TP limiter, and part of why
// this ceiling sits at -0.3 rather than 0).
inline constexpr double kLimiterCeilingDbTp = -0.3;
// The total delay the limiter imposes while engaged, and therefore the plugin's whole reported
// PDC latency. The detector's own group delay is inside this budget, not on top of it.
inline constexpr double kLimiterLookaheadSeconds = 0.002;
// Gain recovery. The min-then-average smoother releases in one lookahead window on its own,
// which distorts low frequencies; this one-pole only ever slows the RISE, so the smoother's
// no-overshoot bound survives it unchanged.
inline constexpr double kLimiterReleaseSeconds = 0.100;
// The transition mute. Long enough that the fade is not itself an edge and that it dwarfs the
// 2 ms delay-line prime it covers; short enough that the whole muted window (prime + fade) is
// ~12 ms rather than a gap. Linear in amplitude, not equal-power: this fades ONE leg to
// silence, it does not cross two.
inline constexpr double kLimiterMuteSeconds = 0.010;
// 4x true-peak oversampling (ITU-R BS.1770's floor at 48 kHz) over an 8-tap-per-phase
// polyphase interpolator. The 33-tap prototype's centre tap makes phase 0 an exact 4-sample
// delay, and that delay is the detector's group delay.
inline constexpr int kLimiterOversample = 4;
inline constexpr int kLimiterOsTaps = 8;
inline constexpr int kLimiterOsDelay = 4;
// kLimiterCeilingDbTp as a linear magnitude.
double limiterCeilingLinear();
// The delay the limiter imposes while engaged, in samples at `sampleRate` — what the plugin
// reports to the host's PDC. 0 at a non-positive rate; never below the detector's own delay.
int limiterLookaheadSamples(double sampleRate);
// The master-bus limiter. One instance per plugin instance; prepare() before the first block.
//
// The gain law is a sliding MINIMUM of the per-sample target gain over the lookahead window,
// then a MOVING AVERAGE of the same width. Every term of that average is a minimum whose own
// window contains the sample being gained, so the smoothed gain is <= the target gain at every
// sample by construction — the ceiling is held structurally rather than by a tuned attack.
//
// SWITCHING IS A MUTE, NOT A BLEND. Unlimited signal is emitted at weight 1 (settled bypass,
// which is the untouched buffer) or at weight 0, never in between — a fraction of an unlimited
// signal is a peak above the ceiling, which is exactly the leak this design forbids. So the
// FADE always rides the limited path (any weight of it is already under the ceiling, since the
// mute only scales down) and the HARD EDGE always lands on the bypassed side, against silence:
// engaging mutes at once, holds while the delay line primes, then fades the limited path in;
// disengaging fades the limited path out and resumes the dry buffer from silence. That
// discontinuity is accepted; a spike is not.
class Limiter {
public:
// Sizes the delay line, the detector and the smoothers, and snaps to the current enable
// state. Allocates and evaluates transcendentals: main/UI thread only, never in process().
void prepare(double sampleRate);
// Clears the delay line and the detector and snaps to the current enable state, skipping
// the transition mute — an activation has nothing sounding to be continuous with.
// Main/UI thread only (the host guarantees process() is stopped at both call sites).
void reset();
// The enable target. Set on the UI thread, observed by process() at block start.
void setEnabled(bool on);
bool enabled() const { return target_.load(std::memory_order_relaxed); }
// Applies the limiter in place over `frames` of `left` (and `right`, which may be null for
// a mono buffer). Returns the SMALLEST gain the LIMITER ITSELF computed this block —
// smoothGain's output against the real input, at every sample including a muted one — NOT
// scaled by the transition mute. The mute is a switch, not limiting: scaling by it would
// report 0.0 (full reduction) on every toggle regardless of program content, which is a
// meter defect, not a fact about the bus. 1.0 means no detected peak exceeded the ceiling,
// whether settled bypassed or mid-mute over quiet material.
float process(float* left, float* right, int frames);
private:
void clearState();
// The detector's true-peak estimate for the sample kLimiterOsDelay back, given the newest
// input frame. Advances the FIR history.
float detectTruePeak(float xl, float xr, bool stereo);
// Pushes one target gain through the sliding minimum and the moving average.
float smoothGain(float target);
std::atomic<bool> target_{false};
// --- prepared geometry ---
int latency_ = 0; // total delay; also the delay ring's length
int window_ = 0; // the minimum/average width, latency_ - kLimiterOsDelay + 1
float ceiling_ = 1.f;
float releaseCoeff_ = 1.f;
float switchStep_ = 1.f;
float osTaps_[kLimiterOversample][kLimiterOsTaps] = {}; // phase 0 is unused (exact delay)
// --- audio-thread state ---
std::vector<float> delayL_, delayR_;
int delayPos_ = 0;
float histL_[kLimiterOsTaps] = {};
float histR_[kLimiterOsTaps] = {};
int histPos_ = 0;
// Monotonic wedge over the target gain: values ascending from the front, so the front is
// the window minimum. Amortized O(1) per sample, bounded by 2 ops per push over a block.
std::vector<float> wedgeVal_;
std::vector<std::int64_t> wedgeIdx_;
int wedgeHead_ = 0, wedgeCount_ = 0;
std::int64_t pushIndex_ = 0;
std::vector<float> avgRing_;
double avgSum_ = 0.0; // double: the running sum is added to and subtracted from forever
int avgPos_ = 0;
float releaseGain_ = 1.f;
bool active_ = false; // the limited path is in circuit (engaged, or still fading out)
float switchGain_ = 0.f; // the transition mute; only ever scales the LIMITED path
int primeRemaining_ = 0; // samples held at silence while the delay line fills
};
} // namespace reasampler::instrument::engine
@@ -0,0 +1,80 @@
// live_params.cpp — the fold from the parameter set to the live block, and the ramp-step law.
// See live_params.h for the publication contract.
#include "core/instrument/engine/live_params.h"
namespace reasampler::instrument::engine {
LiveValues foldLive(const PlayParams& params, double keyTrack) {
// Value-initialized, so the padding is determinate too. Nothing reads it — the block's
// equality is field-wise for exactly that reason — but this is the one construction site
// every publisher goes through, and an object with indeterminate bytes travelling under a
// seqlock is a hazard worth not having. Off the audio thread; the memset costs nothing here.
LiveValues v{};
v.keyTrack = keyTrack;
// Folded here, not at the voice: Voice::start reads the block's value directly, so the
// spline rule has to be applied on the way in or the two would answer differently.
v.splineActive = splineActive(params);
v.lengthFraction = effectiveLengthFraction(params);
v.filterSettings = params.filter.settings;
v.filterModAmount = params.filter.modAmount;
v.filterVelAmount = params.filter.velAmount;
v.filterKeyTrack = params.filter.keyTrack;
v.filterEnv = params.filter.env;
v.filterAhd = params.filter.trigEnv;
v.adsr = params.adsr;
v.ampAhd = params.trigAhd;
v.pitchEnv = params.pitchEnv;
v.playRate = params.playRate;
v.pitchOffsetSemitones = params.pitchOffsetSemitones;
return v;
}
namespace {
bool sameAdsr(const AdsrParams& a, const AdsrParams& b) {
return a.attackFrames == b.attackFrames && a.holdFrames == b.holdFrames &&
a.decayFrames == b.decayFrames && a.sustainLevel == b.sustainLevel &&
a.releaseFrames == b.releaseFrames && a.attackCurve == b.attackCurve &&
a.decayCurve == b.decayCurve && a.releaseCurve == b.releaseCurve;
}
bool sameAhd(const AhdParams& a, const AhdParams& b) {
return a.attackFrames == b.attackFrames && a.decayFrames == b.decayFrames &&
a.holdFraction == b.holdFraction && a.attackCurve == b.attackCurve &&
a.decayCurve == b.decayCurve;
}
bool sameFilterSettings(const filter::FilterSettings& a, const filter::FilterSettings& b) {
return a.cutoffNorm == b.cutoffNorm && a.resonanceNorm == b.resonanceNorm &&
a.morphNorm == b.morphNorm && a.driveNorm == b.driveNorm &&
a.morphLaw == b.morphLaw;
}
} // namespace
bool operator==(const LiveValues& a, const LiveValues& b) {
return sameFilterSettings(a.filterSettings, b.filterSettings) &&
a.filterModAmount == b.filterModAmount &&
a.filterVelAmount == b.filterVelAmount &&
a.filterKeyTrack == b.filterKeyTrack &&
sameAdsr(a.filterEnv, b.filterEnv) &&
sameAhd(a.filterAhd, b.filterAhd) &&
sameAdsr(a.adsr, b.adsr) &&
sameAhd(a.ampAhd, b.ampAhd) &&
a.pitchEnv.enabled == b.pitchEnv.enabled &&
a.pitchEnv.peakSemitones == b.pitchEnv.peakSemitones &&
sameAhd(a.pitchEnv.shape, b.pitchEnv.shape) &&
a.playRate == b.playRate &&
a.pitchOffsetSemitones == b.pitchOffsetSemitones &&
a.keyTrack == b.keyTrack &&
a.lengthFraction == b.lengthFraction &&
a.splineActive == b.splineActive;
}
double liveRampStep(double sampleRate) {
if (!(sampleRate > 0.0)) return 0.0; // also catches NaN
return 1.0 / (kLiveRampSeconds * sampleRate);
}
} // namespace reasampler::instrument::engine
+185
View File
@@ -0,0 +1,185 @@
#pragma once
// live_params.h — the live playback-parameter block: the plain value bundle the audio thread
// observes once per BLOCK, the single-writer seqlock that publishes it without a lock or a
// torn read, the ONE fold from PlayParams that keeps the two representations in step, and the
// per-frame ramp that keeps a block-rate step inaudible. Ownership belongs above every
// instrument snapshot (see SampleData::live).
#include <atomic>
#include <cstdint>
#include <type_traits>
#include "core/instrument/engine/play_params.h"
namespace reasampler::instrument::engine {
// Full-scale glide time for a live control move (wall-clock seconds), so every smoothed
// control in the program settles on the one time base the post-mixer gain ramp already uses.
inline constexpr double kLiveRampSeconds = 0.020;
// Every continuously-valued playback control, in the SAME domains the engine latches at
// note-on (normalized control positions, envelope times already resolved to frames). What is
// deliberately absent is as load-bearing as what is present: velocity and everything derived
// from it, the note number and its pitch ratio, and the decoded PCM are facts about the note
// event, not controls, and stay latched at note-on. The discrete toggles (play mode, pitch
// engine, filter enable/law, pitch-envelope enable, channel mode) travel by reload instead.
//
// morphLaw rides inside filterSettings only because it is cheaper to carry the whole struct to
// the filter's prepare() than to splice it back; it changes only across a reload, which
// republishes this block, so the two can never disagree.
// Each envelope carries BOTH mode shapes: which one a voice applies is fixed at note-on by
// its play mode, so publishing both keeps the block one shape regardless of mode. The pitch
// envelope's `enabled` rides along inside its params only because the struct is carried whole;
// PitchEnvelope ignores it, since a toggle travels by reload.
struct LiveValues {
filter::FilterSettings filterSettings{};
double filterModAmount = 0.0;
// The DEPTH scaling the velocity curve, not the curve's value: the note's velocity is
// latched, its depth is a control, exactly as filterKeyTrack is a control over a latched
// note number.
double filterVelAmount = 0.0;
double filterKeyTrack = 0.0;
AdsrParams filterEnv{};
AhdParams filterAhd{};
AdsrParams adsr{};
AhdParams ampAhd{};
PitchEnvParams pitchEnv{};
// The block's THIRD commit class, and the reason this comment is here rather than at the
// predicate: playRate is published like any live control but read ONLY at note-on, by
// Voice::start via VoiceEngine::startVoice — never by applyLive on a sounding voice. A live
// rate would mean re-folding an already-resolved sustain loop and re-mapping a contour
// mid-note, both of which are note-on folds. pitchOffsetSemitones has no such tie and is
// ordinarily live.
double playRate = 1.0;
double pitchOffsetSemitones = 0.0;
// Two more members of playRate's note-on-latched class, here for the same reason it is:
// both resolve a fact the voice fixes at note-on (the pitch ratio, and playEnd_), so live
// delivery would retune or re-span a note already struck. Voice::start receives them as
// arguments; applyLive never touches either.
double keyTrack = kKeyTrackDefault;
// ALREADY spline-folded (effectiveLengthFraction) — a drawn contour is a pure time function
// over the whole sample, so the stored knob is inert while one is active and the block must
// carry what the voice will actually play, not the stored value.
double lengthFraction = 1.0;
// The drawn-EG state the fold above reads. A mode flip travels by reload like the contours
// themselves, so this is not a control; it rides here only so a block-boundary write of
// Trigger length (a host automation point) can apply the SAME fold rather than un-doing it.
bool splineActive = false;
};
// The seqlock copies the block as raw bytes, which is only defensible for a plain value type.
static_assert(std::is_trivially_copyable_v<LiveValues>,
"the live block is copied under a seqlock — it must stay a plain value");
// A SIZE-CHANGING edit only: padding can absorb a member added beside an existing one (a bool
// beside splineActive, a fifth FilterSettings float) without moving this literal at all, so this
// assert is NOT the guard against a forgotten operator== field —
// testEveryFieldOfLiveValuesIsCompared (test_live_params.cpp) is that guard, poisoning one leaf
// at a time. This assert only catches an edit that changes sizeof(LiveValues) itself. Confirmed
// 352 bytes, MSVC 19.44 x64, Release (`SizeProbe<sizeof(LiveValues)>`, an incomplete-template
// size probe whose error message reports the value). Bump the literal AND operator== together.
static_assert(sizeof(LiveValues) == 352,
"a member was added or removed — extend operator== in live_params.cpp to match");
// FIELD-wise equality, and it must never be "simplified" into a memcmp. LiveValues carries
// padding, and nothing gives that padding a determinate value across a copy: NRVO is optional
// and the implicit copy/move is specified member-wise, so two blocks folded from the same
// parameter set are NOT reliably byte-equal. A byte compare therefore reports differences that
// do not exist — which is exactly what it did before this existed. Listed member by member, so a
// member added to the block above must be added here as well; this sits directly beneath the
// struct for that reason.
bool operator==(const LiveValues& a, const LiveValues& b);
inline bool operator!=(const LiveValues& a, const LiveValues& b) { return !(a == b); }
// The ONE derivation of the live block from the parameter set. Every publisher goes through
// here so there is a single site to keep in step with PlayParams. `keyTrack` is passed in
// because it belongs to the capture/instrument scalar beside the play bundle, not to
// PlayParams — SampleData::keyTrack at the reload, InstrumentParams::keyTrack at a live commit.
LiveValues foldLive(const PlayParams& params, double keyTrack);
// Single-writer / single-reader seqlock. The writer publishes a whole block between an odd
// and an even generation; the reader copies the block and re-checks the generation, retrying
// a bounded number of times, so it can never act on a half-applied edit. Wait-free for the
// reader: after the retry budget it reports "nothing new" and the caller keeps its last good
// snapshot rather than spinning on the audio thread.
//
// SINGLE-WRITER IS THE CALLER'S JOB and is load-bearing: two concurrent writers can leave the
// generation EVEN mid-write (A stores gen+1, B reads odd and stores gen+2) while both copy the
// block, and a reader then accepts a torn block as coherent. Every publisher must serialize.
//
// The plain (non-atomic) block copied across the fences is the standard pragmatic seqlock:
// the fences give correct ordering, but the concurrent read of a non-atomic object is a data
// race under the C++ object model, so TSan/UBSan will report it. That report is expected, not
// a defect — there is no clean lock-free standard-C++ alternative that keeps the block a plain
// value the audio thread can copy in one shot.
//
// The writer interface deliberately assumes NO particular thread beyond single-writer, so a
// host's own parameter-change queue (delivered on the audio thread with sample offsets) can
// drive it later without a redesign.
class LiveParams {
public:
// A generation of 0 means "never published"; the first publish lands on 2.
void publish(const LiveValues& values) {
const std::uint32_t gen = seq_.load(std::memory_order_relaxed);
seq_.store(gen + 1, std::memory_order_relaxed); // odd: a write is in progress
std::atomic_thread_fence(std::memory_order_release);
values_ = values;
std::atomic_thread_fence(std::memory_order_release);
// Skip 0 on wrap (~2^31 publishes): landing there would read as "never published" and
// stall every reader until the NEXT publish — a silent mode, unlike a loud one.
const std::uint32_t next = (gen + 2 == 0u) ? 2u : gen + 2;
seq_.store(next, std::memory_order_release); // even: complete and coherent
}
// The last generation published, without copying the block — one relaxed load, so a reader
// that only needs "has anything moved" pays nothing for asking on a block where nothing has.
std::uint32_t generation() const { return seq_.load(std::memory_order_relaxed); }
// Copies the block into `out` and returns the generation actually observed, or 0 when
// nothing has been published yet or the retry budget ran out (in which case `out` may hold
// a torn copy and MUST be discarded — compare the return against 0 before using it).
std::uint32_t read(LiveValues& out, int maxAttempts = 4) const {
for (int attempt = 0; attempt < maxAttempts; ++attempt) {
const std::uint32_t before = seq_.load(std::memory_order_acquire);
if (before == 0) return 0; // never published
if ((before & 1u) != 0u) continue; // writer mid-update
std::atomic_thread_fence(std::memory_order_acquire);
out = values_;
std::atomic_thread_fence(std::memory_order_acquire);
if (seq_.load(std::memory_order_relaxed) == before) return before;
}
return 0;
}
private:
std::atomic<std::uint32_t> seq_{0};
LiveValues values_{};
};
// Linear per-frame glide with EXACT termination: once the target is within one step the value
// becomes the target itself. An asymptotic smoother would leave the value forever a hair off,
// pinning the filter's exact-equality cutoff skip on the always-re-solve path; this returns to
// the skip path the moment the move completes. A non-positive step snaps (no rate known yet).
struct ValueRamp {
double value = 0.0;
double target = 0.0;
double step = 0.0;
bool moving() const { return value != target; }
void set(double v) { value = v; target = v; }
void aim(double t) { target = t; }
// Advances one frame; returns whether the value actually moved.
bool tick() {
if (value == target) return false;
const double delta = target - value;
if (step <= 0.0 || (delta <= step && delta >= -step)) value = target;
else value += (delta > 0.0) ? step : -step;
return true;
}
};
// Per-frame ramp step for a control whose full travel is 1.0, at `sampleRate`. A non-positive
// rate yields 0 — the ramp then snaps rather than inventing a rate.
double liveRampStep(double sampleRate);
} // namespace reasampler::instrument::engine
+69
View File
@@ -0,0 +1,69 @@
# src/core/instrument/engine/loop — the sustain loop's span rule
## Scope
One pure module, `loop_span`: the ONE fold that turns a stored `SampleLoop` + crossfade
length into the `ResolvedLoop` the voice's read path wraps on, plus the editor's default
handle placement for a capture with no loop. No REAPER, no VST3, no allocation, no I/O.
Everything lives in `reasampler::instrument::engine::loop`.
`resolveLoop` is cold — called once per note-on and by the editor. `crossfadeWeight` is
header-inline because it is evaluated per voice per sample.
## Invariants
### The crossfade is PRE-SEAM, and that is what makes it one tap
The fade runs over the last `crossfade` frames before `end`, blending the material running
into `end` toward the material running into `start`. The incoming material is the same read
head one loop length earlier, so the second tap is `pos - length` — no second position to
advance, no second wrap rule, no state. At `end` the incoming tap has arrived at `start`,
which is exactly where the wrap puts the head, so the seam is continuous by construction
rather than by a fade that merely hides it.
The consequence is a hard clamp: **`crossfade <= start`**. A loop starting at frame 0 has no
material ahead of it and therefore gets no crossfade, whatever the user dialled — honest
rather than silently reading before the buffer.
### The weight is normalized over `crossfade - 1`, so the last rendered frame lands AT 1
`crossfadeWeight` normalizes by `1/(crossfade-1)`, not `1/crossfade`: `d` at the last rendered
frame (`end - 1`) is always exactly `crossfade - 1` — the ceiling's own threshold — for every
REAL crossfade length (`crossfade >= 2`), so that frame is the incoming tap outright rather than
a blend approaching it. The seam across the wrap is therefore the material's OWN one-frame step
(`sampler_core_tests`, `testSeamStepMatchesTheNaturalStepForAnyCrossfade`), not a residual that
merely shrinks with a longer fade — the earlier `1/crossfade` normalization left `(xf-1)/xf` at
that frame, which is what the `crossfade - 1` fix closes. `crossfade == 1` degenerates to the
hard seam instead: its one frame sits at `d == 0`, caught by the `d <= 0` floor before the
multiply/ceiling ever runs, so `fadeInv` is guarded to 0 rather than dividing by zero.
### Linear, not equal-power
The two taps are one loop length apart in the same material and are usually well correlated,
where an equal-power pair bulges. Linear also costs a subtract and a multiply on a path that
forbids a transcendental. The filter's morph crossfade is equal-power for a reason specific
to quadrature taps (`engine/filter/CLAUDE.md`) — that reasoning does not transfer here.
**Known exception:** a full-mix or stem bounce (in this tool's own stated material scope) is
not quasi-periodic, so its two taps are effectively decorrelated — a linear pair then dips
~3 dB at the fade midpoint the way it wouldn't on a correlated tonal/one-shot loop. Accepted
rather than fixed: an equal-power pair would cost the transcendental this path forbids, and the
dip is a fade-region loudness wobble, not the seam click the crossfade exists to kill.
### An invalid span is refused, never repaired
An inverted span, a span reaching past the PCM, a negative start, a Trigger voice: all yield
`active == false`, so the note plays straight through. Repairing a corrupt span into a
plausible one would make a wrong loop audible and a bug invisible; the crossfade length is
the one field that IS clamped rather than refused, because its bound is a property of the
loop it sits in rather than of the user's intent.
## Gotchas
- **`crossfadeWeight` assumes its argument is already wrapped** into `[start, end)`. The
ceiling at 1.0 is a belt against an unwrapped caller, not permission to skip the wrap —
an unwrapped position would otherwise extrapolate past the incoming tap.
- **`defaultLoopBounds` is a UI default living in an engine module** on purpose: the span the
user is offered and the span `resolveLoop` will accept have to be one definition, and the
previous frame-0 default put the loop-start handle underneath the start marker where no
grab could reach it.
@@ -0,0 +1,7 @@
# The loop's validity rule and crossfade geometry. Links peaks/filter/velocity_curve/curve_law
# (play_params' own dependency set) deliberately not the voice engine: the resolve is a fold
# over plain values, which is what lets the editor share it without pulling the engine in.
reasampler_pure_library(loop_span
SOURCES loop_span.cpp
LINK PUBLIC peaks filter velocity_curve curve_law)
reasampler_test(loop_span LINK loop_span)
@@ -0,0 +1,39 @@
// loop_span.cpp — see loop_span.h. Pure math; no host types.
#include "core/instrument/engine/loop/loop_span.h"
namespace reasampler::instrument::engine::loop {
ResolvedLoop resolveLoop(const SampleLoop& loop, std::int64_t crossfadeFrames,
std::int64_t frameCount, bool gateMode) {
ResolvedLoop out;
// Trigger is a one-shot by definition, so the loop is not merely unused there — it is
// absent, and the read path branches on this one flag.
if (!gateMode || !loop.hasLoop) return out;
if (loop.start < 0 || loop.end <= loop.start || loop.end > frameCount) return out;
out.active = true;
out.start = loop.start;
out.end = loop.end;
out.length = loop.end - loop.start;
// The incoming tap reads at `pos - length`, i.e. over [start - crossfade, start) — so the
// fade cannot outrun the material ahead of the loop, nor the loop itself.
std::int64_t xf = crossfadeFrames;
if (xf < 0) xf = 0;
const std::int64_t bound = maxCrossfade(out.start, out.length);
if (xf > bound) xf = bound;
out.crossfade = xf;
out.fadeBegin = static_cast<double>(out.end - xf);
// xf == 1 has no fractional region to normalize (crossfadeWeight's d <= 0 check already
// catches its only frame) — guard rather than divide by zero.
out.fadeInv = xf > 1 ? 1.0 / static_cast<double>(xf - 1) : 0.0;
return out;
}
LoopBounds defaultLoopBounds(std::int64_t frameCount) {
if (frameCount <= 0) return LoopBounds{};
return LoopBounds{frameCount - frameCount / 4, frameCount};
}
} // namespace reasampler::instrument::engine::loop
@@ -0,0 +1,98 @@
#pragma once
// loop_span.h — the sustain loop's ONE validity/clamp rule plus its pre-seam crossfade
// geometry. The resolve is cold (note-on, editor); crossfadeWeight is header-inline because
// it sits on the per-voice-per-sample read.
#include <cstdint>
#include <vector>
#include "core/audio/peaks.h" // AudioSample
#include "core/instrument/engine/play_params.h" // SampleLoop
namespace reasampler::instrument::engine::loop {
using audio::AudioSample;
// The crossfade's own bound: it cannot outrun the material ahead of the loop (`start` source
// frames precede it) nor the loop's own length (the incoming tap is one loop length behind the
// head). Shared by resolveLoop's clamp and the editor's drag clamp so the two cannot diverge.
inline std::int64_t maxCrossfade(std::int64_t start, std::int64_t length) {
return start < length ? start : length;
}
// A sustain loop folded against one capture: validity, geometry, and the clamped crossfade.
// `active == false` leaves every other field zero, so a caller can wrap on the flag alone.
//
// The fade is PRE-SEAM and its incoming tap is the same read head one loop length earlier —
// `pos - length`, no second position to advance. See CLAUDE.md for why that shape, and for
// the `crossfade <= start` bound it forces.
struct ResolvedLoop {
bool active = false;
std::int64_t start = 0;
std::int64_t end = 0; // half-open
std::int64_t length = 0; // end - start
std::int64_t crossfade = 0; // source frames; 0 = hard seam
double fadeBegin = 0.0; // end - crossfade
double fadeInv = 0.0; // 1 / (crossfade - 1); 0 when crossfade <= 1
};
// Folds a stored loop + crossfade against the decoded sample. Refuses anything the read path
// could not honour — a non-Gate mode, an unset loop, an inverted or empty span, a span
// reaching outside the PCM — by returning an inactive result rather than a repaired one, so a
// corrupt span silently plays through instead of reading out of bounds.
ResolvedLoop resolveLoop(const SampleLoop& loop, std::int64_t crossfadeFrames,
std::int64_t frameCount, bool gateMode);
// Weight of the INCOMING (pre-loop-start) tap at source position `pos`: 0 before the fade
// region, reaching exactly 1 at the LAST rendered frame (`end - 1`), not merely approaching it —
// normalizing over `crossfade - 1` rather than `crossfade` is what buys that: d at `end - 1` is
// always exactly `crossfade - 1`, the ceiling's own threshold, for any REAL crossfade
// (`crossfade >= 2`). That last frame is therefore the incoming tap outright, which is exactly
// the value the wrap hands over, so the step across the seam is the material's own natural step
// — not a residual that merely shrinks with a longer fade. `crossfade == 1` degenerates to the
// hard seam instead: its one frame sits at `d == 0`, caught by the `d <= 0` floor below before
// the ceiling ever runs. `pos` must already be wrapped into [start, end) — the ceiling is a belt
// for a caller that has not wrapped yet, not a licence to skip it.
inline double crossfadeWeight(const ResolvedLoop& lp, double pos) {
if (lp.crossfade <= 0) return 0.0;
const double d = pos - lp.fadeBegin;
if (d <= 0.0) return 0.0;
return d < static_cast<double>(lp.crossfade - 1) ? d * lp.fadeInv : 1.0;
}
// Linear-interpolated read at a plain (non-wrapping) fractional source position. The crossfade
// tap sits one loop length behind the head, i.e. BEFORE the loop start, so it never needs the
// wrap partner the main read uses.
inline double lerpSource(const std::vector<AudioSample>& pcm, std::int64_t frameCount,
double pos) {
const std::int64_t i0 = static_cast<std::int64_t>(pos);
const std::int64_t i1 = i0 + 1;
const double frac = pos - static_cast<double>(i0);
const double a = (i0 >= 0 && i0 < frameCount) ? static_cast<double>(pcm[i0]) : 0.0;
const double b = (i1 >= 0 && i1 < frameCount) ? static_cast<double>(pcm[i1]) : 0.0;
return a + (b - a) * frac;
}
// One integer source frame with the loop crossfade already blended in — the Preserve path's
// read, and the start()-time ring prime's. `pos` must be a valid index; `xw` is crossfadeWeight
// at that position (0 blends nothing).
inline AudioSample crossfadedSource(const std::vector<AudioSample>& pcm, const ResolvedLoop& lp,
std::int64_t pos, double xw) {
const double v = static_cast<double>(pcm[static_cast<std::size_t>(pos)]);
if (xw <= 0.0) return static_cast<AudioSample>(v);
const std::int64_t tap = pos - lp.length;
if (tap < 0) return static_cast<AudioSample>(v);
const double in = static_cast<double>(pcm[static_cast<std::size_t>(tap)]);
return static_cast<AudioSample>(v + xw * (in - v));
}
// Where the editor parks the loop handles for a capture that has none — the last quarter,
// where a sustain loop actually goes. Lives here, next to the validity rule, so the span a
// user is offered and the span the engine will accept are one definition.
struct LoopBounds {
std::int64_t start = 0;
std::int64_t end = 0;
};
LoopBounds defaultLoopBounds(std::int64_t frameCount);
} // namespace reasampler::instrument::engine::loop
+7 -12
View File
@@ -6,7 +6,6 @@
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <limits>
namespace reasampler::instrument::engine {
@@ -18,6 +17,13 @@ double masterGainMaxLinear() { return std::pow(10.0, kMasterGainMaxDb / 20.0); }
double masterGainDbFromNorm(double norm) {
norm = clamp01(norm);
if (norm <= 0.0) return -std::numeric_limits<double>::infinity();
// UNITY IS EXACT, and the argument is arithmetic rather than structural — a host's
// reset-to-default arrives here as toPlain(defaultNormalized) and must land on 0.0 dB, not a
// hair off it. fl(60/84) differs from 60/84 by δ ≈ 1.6e-17; 84·δ ≈ 1.33e-15 sits under the
// half-ulp of 60 (3.55e-15), so -60 + fl(60/84)·84 rounds to exactly 60 and the sum to 0.
// PRECONDITION: no FP contraction. Fused into a single FMA the residue survives as 1.33e-15.
// Safe on the shipped MSVC/x64 default (no FMA without /arch:AVX2); a build that enables
// contraction here breaks the exactness test in test_param_units, which is where it surfaces.
return kMasterGainMinDb + norm * (kMasterGainMaxDb - kMasterGainMinDb);
}
@@ -37,15 +43,4 @@ double masterGainNormFromLinear(double linear) {
return masterGainNormFromDb(20.0 * std::log10(linear));
}
void formatMasterGainLabel(double norm, char* buf, std::size_t len) {
if (!buf || len == 0) return;
norm = clamp01(norm);
if (norm <= 0.0) {
std::snprintf(buf, len, "-inf");
return;
}
const double db = masterGainDbFromNorm(norm);
std::snprintf(buf, len, "%+.1fdB", db);
}
} // namespace reasampler::instrument::engine
-6
View File
@@ -7,8 +7,6 @@
#pragma once
#include <cstddef>
namespace reasampler::instrument::engine {
// norm 0 is -inf (true zero); norm just above 0 starts at the finite floor kMasterGainMinDb
@@ -31,8 +29,4 @@ double masterGainLinearFromNorm(double norm);
// true-zero and the floor aren't representable on the knob. Out-of-range/non-finite clamps.
double masterGainNormFromLinear(double linear);
// "-inf" at the bottom, else a signed one-decimal dB string ("-12.0dB", "+2.4dB").
// Writes at most `len` bytes including the terminator.
void formatMasterGainLabel(double norm, char* buf, std::size_t len);
} // namespace reasampler::instrument::engine
@@ -0,0 +1,69 @@
// meter_accumulate.h — the master meter's ACCUMULATE half: the audio thread's block-rate fold
// into the two windows the UI drains, and the drain that starts the next window. The ballistics
// that run on what comes out are meter_ballistics'. Header-only — the folds sit on the audio
// thread's per-block path. The folds are templated on the accumulator ONLY so the
// drain-inside-the-fold interleave below can be pinned deterministically instead of raced for.
#pragma once
#include <atomic>
namespace reasampler::instrument::engine {
// A lock-backed std::atomic<float> would put a mutex on the audio thread; assert the freedom
// rather than assume it.
static_assert(std::atomic<float>::is_always_lock_free,
"the meter folds run on the audio thread and must be lock-free");
// The two windows' identity elements: a peak window that has seen nothing reports silence, a
// gain window that has seen nothing reports no reduction. They are what a consume reinstalls,
// so they live beside the folds rather than at the reader.
inline constexpr float kMeterPeakIdentity = 0.f;
inline constexpr float kMeterGainIdentity = 1.f;
// Folds one block's reading into its accumulator — a running max for a peak, a running min for
// the limiter's gain — so the ~47 blocks that elapse between two 500 ms UI frames at 48 kHz/512
// all reach the meter instead of the one it happened to sample.
//
// An UNCONDITIONAL read-modify-write, and that is the whole point. The UI's consume is an
// exchange that can land between a plain load and its store, and a load-compare-store fold
// would then drop the block outright: it decided against storing by comparing with a window the
// UI has since taken, so that block's reading enters neither the old window nor the new one.
// The CAS retries against whatever the consume left, which makes `acc >= blockPeak` hold on
// exit however the two interleave. STRONG, so the loop is bounded by the interference it is
// written against: the audio thread is the only writer besides the UI's single consume, and
// weak's permitted spurious failure would make an unbounded retry count reachable with no
// interference at all. Three calls per block, so the strong form costs nothing measurable.
// Relaxed throughout: the accumulators are advisory and order no other state. `Accumulator` is
// templated only so a test can pin the interleave; it must behave as std::atomic<float>.
template <class Accumulator>
inline void foldPeak(Accumulator& acc, float blockPeak) {
float seen = acc.load(std::memory_order_relaxed);
while (!acc.compare_exchange_strong(seen, seen > blockPeak ? seen : blockPeak,
std::memory_order_relaxed,
std::memory_order_relaxed)) {
}
}
template <class Accumulator>
inline void foldMinGain(Accumulator& acc, float blockMinGain) {
float seen = acc.load(std::memory_order_relaxed);
while (!acc.compare_exchange_strong(seen, seen < blockMinGain ? seen : blockMinGain,
std::memory_order_relaxed,
std::memory_order_relaxed)) {
}
}
// Takes what the window accumulated and reinstalls the identity element, which IS what starts
// the next window — so exactly one reader may consume (the shell's MasterBusMeter states who).
// Concrete: only the folds have the interleave a test seam buys, and a template over one
// instantiation models nothing.
inline float consumePeak(std::atomic<float>& acc) {
return acc.exchange(kMeterPeakIdentity, std::memory_order_relaxed);
}
inline float consumeMinGain(std::atomic<float>& acc) {
return acc.exchange(kMeterGainIdentity, std::memory_order_relaxed);
}
} // namespace reasampler::instrument::engine
@@ -0,0 +1,57 @@
// meter_ballistics.cpp — see meter_ballistics.h.
#include "core/instrument/engine/meter_ballistics.h"
#include <cmath>
namespace reasampler::instrument::engine {
double meterDbFromLinear(double linear) {
if (!(linear > 0.0)) return kMeterFloorDb; // also catches NaN
const double db = 20.0 * std::log10(linear);
return db < kMeterFloorDb ? kMeterFloorDb : db;
}
double meterNormFromDb(double db) {
if (!(db > kMeterFloorDb)) return 0.0; // also catches NaN
if (db >= kMeterTopDb) return 1.0;
return (db - kMeterFloorDb) / (kMeterTopDb - kMeterFloorDb);
}
MeterState advanceMeter(MeterState prev, double blockPeakLinear, double elapsedSeconds) {
const double dt = (elapsedSeconds > 0.0) ? elapsedSeconds : 0.0;
const double fall = kMeterFallDbPerSecond * dt;
const double peakDb = meterDbFromLinear(blockPeakLinear);
MeterState next = prev;
// Instantaneous rise, timed fall — one expression, because a fall can never take the bar
// below the peak this very block carried.
const double fallen = prev.levelDb - fall;
next.levelDb = fallen > peakDb ? fallen : peakDb;
if (next.levelDb >= next.holdDb) {
next.holdDb = next.levelDb;
next.holdRemainingSeconds = kMeterPeakHoldSeconds;
} else {
next.holdRemainingSeconds = prev.holdRemainingSeconds - dt;
if (next.holdRemainingSeconds < 0.0) {
// Spend the overshoot as fall time so the tick's release does not quantize to the
// UI frame it happened to expire on.
const double held = kMeterFallDbPerSecond * -next.holdRemainingSeconds;
const double dropped = next.holdDb - held;
next.holdDb = dropped > next.levelDb ? dropped : next.levelDb;
next.holdRemainingSeconds = 0.0;
}
}
if (blockPeakLinear >= 1.0) next.clip = true;
return next;
}
MeterState clearMeterClip(MeterState prev) {
MeterState next = prev;
next.clip = false;
return next;
}
} // namespace reasampler::instrument::engine
@@ -0,0 +1,40 @@
// meter_ballistics.h — the output meter's ballistics and its dB scale: peak fall, peak hold,
// clip latch, and the dB -> normalized map the bar draws against. UI-thread math ONLY: the
// audio thread publishes raw block peaks per block and converts, holds and decays nothing.
#pragma once
namespace reasampler::instrument::engine {
// The scale is LINEAR IN dB across this span. Above 0 dBFS is shown because that is exactly
// what the limiter-off case has to make visible.
inline constexpr double kMeterFloorDb = -60.0;
inline constexpr double kMeterTopDb = 6.0;
// A peak meter must not smooth its attack or it under-reports, so the rise is instantaneous
// and only the fall is timed. 20 dB/s is close to the IEC 60268-18 PPM fallback.
inline constexpr double kMeterFallDbPerSecond = 20.0;
inline constexpr double kMeterPeakHoldSeconds = 1.5;
// Linear magnitude -> dBFS, floored at kMeterFloorDb — a silent block reads the floor rather
// than -inf, so the state stays a finite number the ballistics can subtract from.
double meterDbFromLinear(double linear);
// dBFS -> [0,1] up the meter, clamped at both ends.
double meterNormFromDb(double db);
struct MeterState {
double levelDb = kMeterFloorDb;
double holdDb = kMeterFloorDb;
double holdRemainingSeconds = 0.0;
bool clip = false; // latched; only clearMeterClip lowers it
};
// One UI frame of ballistics against the block peak the audio thread published and the time
// since the previous frame. Clip latches at a block peak >= 0 dBFS and is never cleared here.
MeterState advanceMeter(MeterState prev, double blockPeakLinear, double elapsedSeconds);
// The click-to-clear on the meter's clip cap.
MeterState clearMeterClip(MeterState prev);
} // namespace reasampler::instrument::engine
@@ -0,0 +1,254 @@
// period_detect — pure implementation. See period_detect.h for the contract.
//
// YIN (de Cheveigne & Kawahara 2002), two-pass: a cumulative-mean-normalized difference
// function on a 4x box-decimated copy picks the period, then the raw difference function at
// full rate refines it to a fraction of a frame. The decimated pass is what makes the cost
// bounded; the full-rate pass is what makes the estimate precise enough to multiply — the
// splice jump is n periods, so an error of e frames lands as n*e frames of misalignment.
//
// Hand-rolled rather than autocorrelation-with-an-FFT: no third-party dependency, and the
// difference function's absolute threshold is what lets "no period here" be a real answer.
#include "core/instrument/engine/period_detect.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
namespace reasampler::instrument::engine {
namespace {
constexpr int kDecimate = 4;
// Below this RMS a block carries no signal to find a period in; its difference function is
// numerically degenerate rather than merely inconclusive.
constexpr double kSilenceRms = 1e-5;
// Box-decimate `src[from, from+count)` by kDecimate. The averaging is the anti-alias filter:
// a plain stride would fold high partials onto the low lags the coarse pass searches.
std::vector<double> decimate(const std::vector<AudioSample>& src, std::size_t from,
std::size_t count) {
std::vector<double> out(count / kDecimate);
for (std::size_t i = 0; i < out.size(); ++i) {
double s = 0.0;
for (int k = 0; k < kDecimate; ++k) {
s += static_cast<double>(src[from + i * kDecimate + static_cast<std::size_t>(k)]);
}
out[i] = s / kDecimate;
}
return out;
}
// The cumulative-mean-normalized difference d'(tau) over lags [1, lagHi], analysis window W:
// d(tau) = sum_{j<W} (x[j] - x[j+tau])^2
// d'(tau) = d(tau) / ((1/tau) * sum_{t=1..tau} d(t))
// Index 0 is unused (set to 1.0, YIN's convention). The normalization is what makes the
// threshold below an absolute one rather than a signal-dependent one.
std::vector<double> cmndf(const std::vector<double>& x, std::size_t W, std::size_t lagHi) {
std::vector<double> dp(lagHi + 1, 1.0);
double running = 0.0;
for (std::size_t tau = 1; tau <= lagHi; ++tau) {
double d = 0.0;
for (std::size_t j = 0; j < W; ++j) {
const double diff = x[j] - x[j + tau];
d += diff * diff;
}
running += d;
dp[tau] = running > 0.0 ? d * static_cast<double>(tau) / running : 1.0;
}
return dp;
}
// Parabolic vertex through (i-1, i, i+1) as an offset in [-0.5, 0.5] from i. Zero at an end
// point or a non-minimum, which leaves the integer lag — benign, and the full-rate pass
// refines it again anyway.
double parabolicOffset(const std::vector<double>& y, std::size_t i) {
if (i == 0 || i + 1 >= y.size()) return 0.0;
const double den = y[i - 1] - 2.0 * y[i] + y[i + 1];
if (!(den > 0.0)) return 0.0; // a minimum has positive curvature
double f = 0.5 * (y[i - 1] - y[i + 1]) / den;
if (f > 0.5) f = 0.5;
if (f < -0.5) f = -0.5;
return f;
}
// YIN's absolute-threshold rule: take the FIRST dip below the threshold, walked down to its
// local bottom — not the global minimum. A periodic signal dips at every multiple of its
// period, so the global minimum is as likely to be 2P or 3P; taking the first dip is what
// makes the answer the fundamental period rather than some harmonic of it.
bool pickPeriod(const std::vector<double>& dp, std::size_t lagLo, double& tauOut,
double& dissimilarity) {
for (std::size_t tau = lagLo; tau + 1 < dp.size(); ++tau) {
if (dp[tau] >= kPeriodDetectThreshold) continue;
std::size_t t = tau;
while (t + 1 < dp.size() && dp[t + 1] < dp[t]) ++t;
tauOut = static_cast<double>(t) + parabolicOffset(dp, t);
dissimilarity = dp[t];
return true;
}
return false;
}
// The raw difference function over [lo, hi] at FULL rate, minimized parabolically. The coarse
// pass already chose which dip; this only says exactly where its bottom is. Amplitude drift
// over the few frames spanned here is negligible, so the unnormalized d() suffices.
double refineFullRate(const std::vector<AudioSample>& pcm, std::size_t from, std::size_t W,
std::size_t lo, std::size_t hi) {
std::vector<double> d(hi - lo + 1, 0.0);
for (std::size_t tau = lo; tau <= hi; ++tau) {
double s = 0.0;
for (std::size_t j = 0; j < W; ++j) {
const double diff = static_cast<double>(pcm[from + j]) -
static_cast<double>(pcm[from + j + tau]);
s += diff * diff;
}
d[tau - lo] = s;
}
const std::size_t best =
static_cast<std::size_t>(std::min_element(d.begin(), d.end()) - d.begin());
return static_cast<double>(lo + best) + parabolicOffset(d, best);
}
double blockRms(const std::vector<AudioSample>& pcm, std::size_t from, std::size_t count) {
double e = 0.0;
for (std::size_t i = 0; i < count; ++i) {
const double x = static_cast<double>(pcm[from + i]);
e += x * x;
}
return std::sqrt(e / static_cast<double>(count));
}
} // namespace
PeriodEstimate detectPeriod(const std::vector<AudioSample>& pcm, int sampleRate,
std::size_t spanFrom, std::size_t spanCount) {
if (sampleRate <= 0 || spanCount == 0) return {};
if (spanFrom > pcm.size() || spanCount > pcm.size() - spanFrom) return {};
const double rate = static_cast<double>(sampleRate);
std::size_t lagHi = longestLagFrames(sampleRate);
const std::size_t lagLo = static_cast<std::size_t>(rate / kPeriodDetectMaxHz);
if (lagLo < 2) return {}; // a rate so low the whole search band collapses
// One probe block is W + lagHi frames with W == lagHi (YIN's usual sizing: the analysis
// window must cover the longest lag being tested). A short span shortens the search
// rather than refusing outright — a 200 ms one-shot still has a period worth finding.
if (spanCount < 2 * lagHi) lagHi = spanCount / 2;
if (lagHi <= lagLo + 2) return {};
const std::size_t block = 2 * lagHi;
// Probe POSITIONS, not disjoint blocks — see kPeriodDetectProbes in the header for why
// lagHi is the separation that makes two overlapping probes independent evidence.
const std::size_t room = spanCount - block;
const std::size_t probes = std::min<std::size_t>(kPeriodDetectProbes, 1 + room / lagHi);
// Room to spare after the last probe's block is spread between them, so the probes sample
// the whole span rather than only its opening.
const std::size_t stride = probes > 1 ? room / (probes - 1) : 0;
std::vector<double> periods;
std::vector<double> confidences;
// Probes that carried signal AND ran the real dip search — the agreement denominator. A
// silent block is no evidence either way; a block whose decimated search band or full-rate
// refine bracket collapsed to nothing (the two geometry continues below) never ran that
// search either, so it is excluded on the same footing as silence, not counted as if it had.
std::size_t evidence = 0;
for (std::size_t p = 0; p < probes; ++p) {
// (probes - 1) * stride <= room by construction, so the last block always fits.
const std::size_t from = spanFrom + p * stride;
if (blockRms(pcm, from, block) < kSilenceRms) continue;
const std::vector<double> small = decimate(pcm, from, block);
const std::size_t smallHi = lagHi / kDecimate;
const std::size_t smallW = small.size() - smallHi;
if (smallHi <= lagLo / kDecimate + 2 || smallW == 0) continue; // degenerate geometry
const std::vector<double> dp = cmndf(small, smallW, smallHi);
double coarseTau = 0.0, dissimilarity = 1.0;
if (!pickPeriod(dp, std::max<std::size_t>(2, lagLo / kDecimate), coarseTau,
dissimilarity)) {
++evidence; // the search ran and found no dip: real evidence against a period
continue;
}
// Bracket the full-rate refinement at +/- 2 decimated samples around the coarse pick:
// the decimated parabola is already sub-decimated-sample accurate, so this is margin,
// not a second search.
const double centre = coarseTau * kDecimate;
const std::size_t lo = static_cast<std::size_t>(
std::max(static_cast<double>(lagLo), centre - 2.0 * kDecimate));
const std::size_t hi = static_cast<std::size_t>(
std::min(static_cast<double>(lagHi), centre + 2.0 * kDecimate));
if (hi <= lo) continue; // degenerate refine bracket
++evidence; // the search ran and found a period: real evidence for one
periods.push_back(refineFullRate(pcm, from, block - hi, lo, hi));
confidences.push_back(1.0 - dissimilarity);
}
if (periods.empty()) return {};
// ONE piece of evidence in the whole span — either it hosted a single probe position, or
// every other probe was silent. Nothing can rule against this estimate, so the accept rests
// on pickPeriod's absolute threshold, which is a real test and not an absence of one: the
// block genuinely repeats at this lag across its whole analysis window. Refusing instead
// would deny every short one-shot a period, and a period that turns out wrong costs a
// mis-centred correlation search at the splice, not an unrefined one (pitch_shift.cpp's
// splice searches +/- maxLag around whichever jump it is handed). Do not "unify" this back
// into the majority test — at one piece of evidence that test accepts unconditionally, which
// is the same behaviour with none of the reasoning. Nor key it on how many probes SURVIVED:
// one survivor out of four that all carried signal is not this case at all.
if (evidence == 1) {
PeriodEstimate lone;
lone.frames = periods[0];
lone.confidence = confidences[0];
return lone;
}
std::vector<double> sorted = periods;
std::sort(sorted.begin(), sorted.end());
const double median = sorted[sorted.size() / 2];
// Average the probes that agree with the median rather than taking the median outright:
// averaging cancels each probe's own estimation jitter, and the jump multiplies whatever
// error survives by n.
double sum = 0.0, confSum = 0.0;
std::size_t agree = 0;
for (std::size_t i = 0; i < periods.size(); ++i) {
if (std::fabs(periods[i] - median) > kPeriodDetectAgreeTolerance * median) continue;
sum += periods[i];
confSum += confidences[i];
++agree;
}
// A STRICT MAJORITY of the probes that carried signal must agree, not merely two of them: a
// source whose first half is one period and second half another gives two probes each way,
// and taking either as "the" period would misalign every splice in the other half. Refusing
// is the right answer there — the fixed-window fallback is what a source with no ONE period
// gets. The denominator is `evidence` and not `periods.size()` because once probes overlap
// a straddling block finds no period at all rather than a third one, and counting only the
// survivors turned that two-and-two split into a two-of-three accept.
// Reached only with two or more pieces of evidence; the lone case returned above.
if (agree * 2 <= evidence) return {};
PeriodEstimate est;
est.frames = sum / static_cast<double>(agree);
est.confidence = confSum / static_cast<double>(agree);
return est;
}
PeriodEstimate detectPeriod(const std::vector<AudioSample>& pcm, int sampleRate) {
return detectPeriod(pcm, sampleRate, 0, pcm.size());
}
AnalysisSpan periodAnalysisSpan(std::size_t frameCount, std::int64_t loopStart,
std::int64_t loopEnd, bool hasLoop, int sampleRate) {
const AnalysisSpan whole{0, frameCount};
if (!hasLoop || sampleRate <= 0) return whole;
if (loopStart < 0 || loopEnd <= loopStart) return whole;
if (static_cast<std::uint64_t>(loopEnd) > frameCount) return whole;
const std::size_t length = static_cast<std::size_t>(loopEnd - loopStart);
// One full probe block. Below it detectPeriod shortens lagHi to fit, which raises the
// lowest findable fundamental — the one thing the narrower span may never cost.
const std::size_t minimum = 2 * longestLagFrames(sampleRate);
if (length < minimum) return whole;
return AnalysisSpan{static_cast<std::size_t>(loopStart), length};
}
} // namespace reasampler::instrument::engine
+122
View File
@@ -0,0 +1,122 @@
#pragma once
// period_detect — the source's own fundamental period, estimated ONCE per load from decoded
// PCM, for the Preserve splice's pitch-synchronous jump (pitch_shift.h's periodAlignedJump).
//
// Runs off the audio thread BY LINK GRAPH: sampler_core does not link this module, so no
// translation unit on the render path can name detectPeriod. A sampler's source is fixed and
// fully known at load, which is the whole reason a detector is affordable here at all.
#include <cstddef>
#include <cstdint>
#include <vector>
#include "core/audio/peaks.h" // AudioSample (float)
namespace reasampler::instrument::engine {
using audio::AudioSample;
// The period the source repeats at, in SOURCE frames, or none. Derived from the audio, never
// authored and never persisted — this is a cache, not state.
struct PeriodEstimate {
double frames = 0.0; // 0 = no single period (inharmonic, polyphonic, percussive, noise)
// 1 - the accepted dissimilarity, [0,1]; 0 when frames == 0. Diagnostic: the accept decision
// is `valid()` alone and the loader takes `.frames` without reading this — its only reader is
// tests/test_period_detect.cpp. It is deliberately NOT a second accept gate: every
// accepted probe already cleared kPeriodDetectThreshold, so confidence > 0.88 holds by
// construction and any gate below that is a no-op while any gate above it is a tuned number
// with nothing to derive it from.
double confidence = 0.0;
bool valid() const { return frames > 0.0; }
};
// Fundamental bounds the search runs over. The LOW bound is the load-bearing one: a period
// only buys anything while it fits the splice's reachable jump (~1.25 windows, i.e. ~16 Hz at
// the product's 50 ms window), so searching below it would return periods the shifter must
// reject anyway. The high bound is generous — a period that short already has dozens of
// aligned landing points inside the search interval, so alignment was never in question there.
inline constexpr double kPeriodDetectMinHz = 15.0;
inline constexpr double kPeriodDetectMaxHz = 2000.0;
// YIN's absolute threshold: the first dissimilarity dip below this IS the period. A source
// that never dips below it has no single period, and detection returns none rather than the
// global minimum — the difference between "quiet but real" and "the least bad of nothing".
inline constexpr double kPeriodDetectThreshold = 0.12;
// The longest lag searched, in frames — THE one derivation of it. A probe block is twice this,
// and `periodAnalysisSpan`'s minimum is one block; both read this rather than re-deriving the
// same expression, so "choosing the loop never narrows the search band" is a fact and not a
// coincidence between two literals.
inline std::size_t longestLagFrames(int sampleRate) {
return static_cast<std::size_t>(static_cast<double>(sampleRate) / kPeriodDetectMinHz);
}
// How many blocks across the sample are estimated independently, and how far apart two of them
// may land and still be called the same period. Agreement is what separates a genuinely
// periodic source from one whose opening happens to look periodic.
//
// Probes are placed by POSITION and may overlap: what the rule needs is estimates from
// different places in the source, and two blocks a full longest-lag apart already differ by a
// whole cycle of the lowest frequency in the band, so neither can be a trivially shifted copy
// of the other at any period searched. Requiring DISJOINT blocks instead left every source
// under ~4x the longest lag with a single probe and so with no agreement to check at all.
inline constexpr int kPeriodDetectProbes = 4;
inline constexpr double kPeriodDetectAgreeTolerance = 0.02; // 2% of the median
// Estimates the fundamental period of `pcm[from, from+count)` at `sampleRate`. Cost is bounded
// by the constants above, not by the span length: at most kPeriodDetectProbes blocks of ~2 x
// the longest searched lag are analysed however long the span is. Allocates; never call from
// process(). An out-of-range span estimates nothing and returns none.
//
// Returns an invalid estimate (frames == 0) for silence, noise, and anything whose probes
// disagree — the caller's documented fallback is the fixed-window splice geometry.
//
// A STRICT MAJORITY of the probes that CARRIED SIGNAL must agree. Silence is excluded from that
// denominator and a failure to find a period is not: a silent block is no evidence either way,
// whereas a block that carries signal and repeats at no lag is evidence against a single period.
// A capture with a silent head or tail therefore still detects, while a mostly-noise source with
// one pitched burst is refused rather than accepted on that burst alone. A LONE piece of
// evidence — the whole span too short for a second probe position, or every other probe silent —
// is accepted on the absolute threshold alone, because there is nothing to rule against it and
// refusing would deny every short one-shot a period.
//
// The answer is NOT monotone in span length, and cannot be made so: no rule that refuses a
// two-and-two split at four probes can also accept a lone probe unconditionally, and the probe
// count steps at 3x, 4x, 5x and 6x the longest lag before saturating. What IS pinned, by a
// length sweep in the tests, is that a STATIONARY source detects at every length — a source
// whose period varies by more than kPeriodDetectAgreeTolerance is the only class that moves
// with the count, and refusing it is this contract's own answer.
PeriodEstimate detectPeriod(const std::vector<AudioSample>& pcm, int sampleRate,
std::size_t from, std::size_t count);
// The whole source.
PeriodEstimate detectPeriod(const std::vector<AudioSample>& pcm, int sampleRate);
// The frames detection should analyse for a capture that carries a sustain loop, and the reason
// the answer is not simply "all of them": under Gate the loop region is asymptotically ALL the
// splicer plays, so a phrase whose head is pitched differently from its sustain would otherwise
// disagree its way to none over the whole source. `[loopStart, loopEnd)` is used only when it is
// at least one full probe block — `2 * longestLagFrames(sampleRate)`, the span below which
// detectPeriod starts shortening its own search band — so choosing the narrower span never costs
// search-band WIDTH. It can still change the ANSWER: the agreement rule rules on content, so a
// source periodic over most of its length whose loop region is noisy detects whole and refuses
// over the loop. That is the intent — the loop is what a Gate voice plays.
// Anything else (no loop, an out-of-range span, a short one) yields the whole source.
//
// It takes NO play mode, deliberately, even though loop_span's resolveLoop does and refuses the
// loop outright under Trigger. A loop edit is structurally reload-bound — it moves the PCM span
// this cache was derived from — whereas play mode's exclusion from live delivery is a listed,
// reversible decision (deck_groups' deckParamCommit). Keying a load-time cache on it would work
// today and silently serve a stale period the day that decision is revisited.
//
// The read path's loop-validity authority is loop_span's resolveLoop; the bounds check here is
// on a cache input, not a second validity rule, and it refuses rather than repairs the same way.
struct AnalysisSpan {
std::size_t from = 0;
std::size_t count = 0;
};
AnalysisSpan periodAnalysisSpan(std::size_t frameCount, std::int64_t loopStart,
std::int64_t loopEnd, bool hasLoop, int sampleRate);
} // namespace reasampler::instrument::engine
+84 -28
View File
@@ -1,10 +1,12 @@
// pitch_shift — pure implementation. See pitch_shift.h for the contract and regression history.
//
// Algorithm: a delay ring of 2*window frames. The write head advances one frame per input
// sample (source rate, duration preserved). One active read tap advances by the shift
// `ratio_` per frame, so its delay behind the writer drifts at (1 - ratio) per frame. When
// that delay leaves the safe band [dLow, dHigh], the tap is relocated by a nominal jump of
// one window — clamped to the filled span so it never lands in unwritten silence — refined
// Algorithm: a delay ring of 2*window frames. The write head advances one frame per source
// frame the caller feeds; the active read tap advances by the shift `ratio_` per OUTPUT frame,
// so its delay behind the writer drifts at (feedRate - ratio) per frame — one frame in, one
// frame out (`feedRate == 1`) preserves duration, and any other feed cadence stretches it. When
// that delay leaves the safe band [dLow, dHigh], the tap is relocated by a nominal jump (one
// window, or the nearest whole number of source periods to it once setSourcePeriod names one)
// — clamped to the filled span so it never lands in unwritten silence — refined
// by a cross-correlation search over +/- maxLag plus a parabolic peak interpolation for a
// sub-sample lag (an integer-only lag left +/-0.5-sample errors: a sideband comb at the
// splice cadence on a repitched pure sine). Old and new taps then crossfade over fadeFrames
@@ -25,6 +27,23 @@ constexpr double kPi = 3.14159265358979323846;
} // namespace
std::int64_t periodAlignedJump(std::int64_t windowFrames, std::int64_t maxJumpFrames,
double periodFrames) {
if (windowFrames <= 1 || maxJumpFrames < 1) return windowFrames;
if (!(periodFrames > 0.0)) return windowFrames;
if (periodFrames > static_cast<double>(maxJumpFrames)) return windowFrames;
std::int64_t n = static_cast<std::int64_t>(
static_cast<double>(windowFrames) / periodFrames + 0.5);
if (n < 1) n = 1;
std::int64_t jump = static_cast<std::int64_t>(periodFrames * static_cast<double>(n) + 0.5);
while (jump > maxJumpFrames && n > 1) {
--n;
jump = static_cast<std::int64_t>(periodFrames * static_cast<double>(n) + 0.5);
}
if (jump < 1 || jump > maxJumpFrames) return windowFrames;
return jump;
}
void PitchShifter::configure(std::int64_t windowFrames) {
window_ = windowFrames;
if (window_ <= 1) {
@@ -36,8 +55,11 @@ void PitchShifter::configure(std::int64_t windowFrames) {
fading_ = false;
fadePos_ = 0;
fadeFrames_ = fadeLen_ = maxLag_ = corrFrames_ = dLow_ = dHigh_ = 0;
period_ = 0.0;
jump_ = jumpMax_ = 0;
filled_ = 0;
ratio_ = 1.0;
feedRate_ = 1.0;
tailFrozen_ = false;
lastSplice_ = SpliceEvent{};
return;
@@ -60,6 +82,9 @@ void PitchShifter::configure(std::int64_t windowFrames) {
dLow_ = window_ / 4;
dHigh_ = ringLen_ - window_ / 4;
corrFrames_ = std::max<std::int64_t>(1, std::min<std::int64_t>(dLow_ - 1, 512));
// The delay band is (dHigh_ - dLow_) wide and the search can add up to maxLag_ on either
// side; one frame more than that and a jump could land exactly ON a trigger boundary.
jumpMax_ = std::max<std::int64_t>(1, dHigh_ - dLow_ - maxLag_ - 1);
fadeLen_ = 0;
reset();
}
@@ -85,15 +110,23 @@ void PitchShifter::reset() {
}
filled_ = 0;
ratio_ = 1.0;
feedRate_ = 1.0;
period_ = 0.0;
jump_ = window_ > 1 ? window_ : 0;
tailFrozen_ = false;
lastSplice_ = SpliceEvent{};
}
void PitchShifter::setSourcePeriod(double periodFrames) {
period_ = periodFrames > 0.0 ? periodFrames : 0.0;
jump_ = window_ > 1 ? periodAlignedJump(window_, jumpMax_, period_) : 0;
}
void PitchShifter::freezeTail() {
if (window_ <= 1 || tailFrozen_) return;
tailFrozen_ = true;
// An in-flight crossfade was sized for a retreating writer (outgoing tap drains at
// ratio-1 per frame); frozen, it closes at the full ratio instead. Cap the live fade so
// ratio-feedRate per frame); frozen, it closes at the full ratio instead. Cap the live fade so
// it completes before tap B reaches the parked writer and reads lapped content mid-fade.
if (fading_) {
// Preserve t = fadePos_/fadeLen_ across the shortening so gNew is continuous at the
@@ -158,6 +191,10 @@ void PitchShifter::setShiftRatio(double ratio) {
if (ratio > 0.0) ratio_ = ratio; // ignore non-positive (never run the tap backward/stall)
}
void PitchShifter::setFeedRate(double rate) {
if (rate > 0.0) feedRate_ = rate;
}
double PitchShifter::readTap(double pos) const {
// Fractional linear interpolation with ring wrap.
double p = pos;
@@ -192,7 +229,10 @@ void PitchShifter::splice(std::int64_t nominalJump, double delay) {
std::int64_t jump = nominalJump;
if (jump > 0) {
const std::int64_t maxJump = filled_ - d - maxLag_ - 1;
if (jump > maxJump) jump = maxJump;
// Shortening a period-aligned jump to fit must land on a SHORTER MULTIPLE, not on the
// raw bound — a clamped jump is an unaligned one, which is the whole failure this
// module now avoids. With no period known (or none fitting) this is the bare clamp.
if (jump > maxJump) jump = periodAlignedJump(maxJump, maxJump, period_);
if (jump < 1) jump = 1;
}
// The correlation reference reads FORWARD from the tap; keep it strictly behind the
@@ -266,18 +306,19 @@ void PitchShifter::splice(std::int64_t nominalJump, double delay) {
while (p >= len) p -= len;
posA_ = p;
// Ratio-scaled fade length. At an up-splice the outgoing tap keeps draining toward the
// writer at (ratio - 1) per frame; the nominal window/4 fade only keeps it behind the
// writer for ratios up to 2 — beyond that (e.g. +24 st = ratio 4) it would cross mid-fade
// and play stale read-ahead data. Cap the live fade at the drain headroom actually
// available, minus 2 (trigger undershoot + interpolator read-ahead margin). Down-shifts
// drain at (1 - ratio) < 1 per frame and can't reach the ring end within window/4 frames,
// so they always keep the full fade.
// writer at (ratio - feedRate) per frame; the nominal window/4 fade only keeps it behind
// the writer while that rate stays under ~1 — beyond that (e.g. +24 st = ratio 4, or a
// half-speed feed under any up-shift) it would cross mid-fade and play stale read-ahead
// data. Cap the live fade at the drain headroom actually available, minus 2 (trigger
// undershoot + interpolator read-ahead margin). A drain rate at or below zero (down-shifts,
// and up-shifts the feed outruns) can't reach the ring end within window/4 frames, so those
// always keep the full fade.
//
// Tail-frozen: with the writer parked, the outgoing tap closes on it at the full ratio in
// either shift direction, so the drain rate is ratio_ instead of (ratio_ - 1) and the cap
// applies at every ratio (including unity, since delay now drains at unity too).
// either shift direction, so the drain rate is ratio_ regardless of feed and the cap applies
// at every ratio (including unity, since delay now drains at unity too).
fadeLen_ = fadeFrames_;
const double drainRate = tailFrozen_ ? ratio_ : (ratio_ - 1.0);
const double drainRate = tailFrozen_ ? ratio_ : (ratio_ - feedRate_);
if (drainRate > 0.0) {
const double headroom = static_cast<double>(dLow_) - drainRate - 2.0;
// Clamp in double before the int64 cast to avoid UB at pathological near-unity ratios
@@ -310,14 +351,27 @@ void PitchShifter::applySplice(const SpliceEvent& ev) {
lastSplice_ = ev; // observable mirror (tests assert follower == master per frame)
}
AudioSample PitchShifter::process(AudioSample in) { return processImpl(in, nullptr); }
AudioSample PitchShifter::process(AudioSample in) { return processImpl(in, nullptr, true); }
AudioSample PitchShifter::processLinked(AudioSample in, const SpliceEvent& master) {
return processImpl(in, &master);
return processImpl(in, &master, true);
}
AudioSample PitchShifter::processImpl(AudioSample in, const SpliceEvent* linked) {
if (window_ <= 1) return in; // pass-through (unconfigured / degenerate)
AudioSample PitchShifter::processNoInput() { return processImpl(0.0f, nullptr, false); }
AudioSample PitchShifter::processNoInputLinked(const SpliceEvent& master) {
return processImpl(0.0f, &master, false);
}
void PitchShifter::writeFrame(AudioSample in) {
if (window_ <= 1 || tailFrozen_) return;
ring_[static_cast<std::size_t>(writePos_)] = in;
if (filled_ < ringLen_) ++filled_;
if (++writePos_ >= ringLen_) writePos_ = 0;
}
AudioSample PitchShifter::processImpl(AudioSample in, const SpliceEvent* linked, bool write) {
if (window_ <= 1) return write ? in : 0.0f; // pass-through (unconfigured / degenerate)
// Copy the linked decision before clearing lastSplice_ (guards a self-aliased pointer).
const SpliceEvent linkedEv = linked != nullptr ? *linked : SpliceEvent{};
@@ -325,8 +379,9 @@ AudioSample PitchShifter::processImpl(AudioSample in, const SpliceEvent* linked)
// Tail-frozen: the source is exhausted, `in` is padding, not stream — write nothing (the
// ring keeps its all-real final two windows) and hold the write head; read/splice/fade
// below run unchanged over the frozen content.
if (!tailFrozen_) {
// below run unchanged over the frozen content. A starved stretch frame (`write` false) takes
// the identical shape: no input was due this output frame, so there is nothing to write.
if (write && !tailFrozen_) {
ring_[static_cast<std::size_t>(writePos_)] = in;
if (filled_ < ringLen_) ++filled_;
}
@@ -357,9 +412,9 @@ AudioSample PitchShifter::processImpl(AudioSample in, const SpliceEvent* linked)
while (d < 0.0) d += len;
while (d >= len) d -= len;
if (d <= static_cast<double>(dLow_)) {
splice(+window_, d);
splice(+jump_, d);
} else if (d >= static_cast<double>(dHigh_)) {
splice(-window_, d);
splice(-jump_, d);
}
}
} else {
@@ -372,14 +427,15 @@ AudioSample PitchShifter::processImpl(AudioSample in, const SpliceEvent* linked)
while (d < 0.0) d += len;
while (d >= len) d -= len;
if (d <= static_cast<double>(dLow_)) {
splice(+window_, d);
splice(+jump_, d);
} else if (d >= static_cast<double>(dHigh_)) {
splice(-window_, d);
splice(-jump_, d);
}
}
// Advance heads: write head one frame (parked while tail-frozen), tap(s) by the shift ratio.
if (!tailFrozen_) {
// Advance heads: write head one frame (parked while tail-frozen or starved), tap(s) by the
// shift ratio.
if (write && !tailFrozen_) {
++writePos_;
if (writePos_ >= ringLen_) writePos_ = 0;
}
+77 -6
View File
@@ -1,11 +1,18 @@
#pragma once
// pitch_shift — per-voice, duration-preserving pitch shifter (the Preserve engine's DSP core).
// pitch_shift — per-voice pitch shifter and time-stretcher (the Preserve engine's DSP core).
// Time-domain delay-line with correlation-aligned splices (SOLA-style): one active read tap
// chases the write head at the shift ratio; when it drifts out of its safe delay band it is
// relocated by a nominal window jump, refined by a cross-correlation search so the new read
// point is waveform-aligned, then old/new taps crossfade (raised-cosine). Source and output are
// both consumed/produced 1:1 — only pitch changes, duration is held (unlike the Varispeed
// `readPos_ += ratio_` resample path).
// relocated by a nominal jump, refined by a cross-correlation search so the new read point is
// waveform-aligned, then old/new taps crossfade (raised-cosine). The nominal jump is a whole
// number of the SOURCE's own periods when setSourcePeriod names one (pitch-synchronous OLA),
// and the fixed window otherwise.
//
// The WRITE rate (how fast source is consumed = duration) and the TAP rate (setShiftRatio =
// pitch) are INDEPENDENT, and only their difference drives the splice cadence. Feeding 1:1 via
// process() holds duration and moves pitch; feeding faster/slower via writeFrame() /
// processNoInput() moves duration at whatever pitch the tap is set to. Nothing here resamples
// to preserve duration — the splice/overlap-add IS the pitch-preserving mechanism, which is
// what the "WDL_Resampler is not a Preserve engine" invariant asks for.
//
// Regression history — do not revert any of these:
// - Correlated splices, vs. the original two-tap OLA (taps hard-locked w/2 apart, Hann
@@ -56,6 +63,21 @@ struct SpliceEvent {
std::int64_t fadeLen = 0; // live (ratio-scaled) crossfade length chosen
};
// The nominal splice jump for a source whose period is known: the multiple of `periodFrames`
// nearest `windowFrames` that still fits `maxJumpFrames`. Falls back to `windowFrames` — the
// pre-PSOLA geometry, exactly — whenever the period is unknown (<= 0) or too long for even one
// whole period to fit, which is the documented degradation for inharmonic, polyphonic,
// percussive and noise sources.
//
// Why this is the whole fix: a splice can only phase-align on a landing point that is a whole
// number of source periods away, and the correlation search only reaches [0.75, 1.25] windows.
// Periods with no multiple in that one interval — f < ~16 Hz, and 26.7-32 Hz at a 50 ms
// window — could never align, however good the search was. Making the NOMINAL a multiple puts
// an aligned point at the centre of the search rather than hoping one falls inside it. The
// jump is rounded to whole frames; the search's own sub-sample refinement absorbs the residue.
std::int64_t periodAlignedJump(std::int64_t windowFrames, std::int64_t maxJumpFrames,
double periodFrames);
// A per-channel time-domain splice-aligned pitch shifter. A stereo voice owns two, linked:
// channel 0 is the master, channel 1 follows its splice decisions via processLinked() so the
// two rings stay sample-aligned.
@@ -89,6 +111,25 @@ public:
// ratio) so a bad input never runs the tap backward or stalls it.
void setShiftRatio(double ratio);
// Source frames written per output frame — 1.0 unless the caller is stretching. Used ONLY
// to size a splice crossfade safely: the outgoing tap closes on the write head at
// (ratio - feedRate) per frame, so a fade sized against an assumed 1.0 overruns when the
// source is fed slower than the output runs and the tail of the fade reads lapped content.
// Values <= 0 are ignored. Exactly 1.0 reproduces the 1:1 geometry bit for bit.
void setFeedRate(double rate);
// The period of the source being fed, in SOURCE frames, making every splice jump a whole
// number of it — <= 0 means "unknown" (see periodAlignedJump for the exact fallback); the
// default, so a caller that never calls this sees no change.
// Detection itself is off-thread and elsewhere (period_detect, which the engine deliberately
// does not link); this is a couple of divisions and is safe to call at note-on.
// Cleared by configure()/reset(); NOT by prime()/warm(), which do not change the source.
void setSourcePeriod(double periodFrames);
// The nominal jump splices currently use — window() unless a source period retuned it to
// the nearest whole-period multiple, which can land either narrower or wider than window().
std::int64_t spliceJump() const { return jump_; }
// Transforms one input frame into one output frame (1 in, 1 out). RT-safe: reads/writes the
// pre-sized ring only, no allocation, no lock. Unconfigured returns `in` unchanged. Otherwise
// writes `in` at the write head, reads the active tap (crossfading against the outgoing tap
@@ -103,6 +144,20 @@ public:
// their ring state advances in lockstep. RT-safe: same guarantees as process().
AudioSample processLinked(AudioSample in, const SpliceEvent& master);
// Writes one source frame WITHOUT producing an output frame — the stretch path's surplus
// input when the source is consumed faster than the output runs. No splice can fire here:
// splices are decided on the read side. No-op while unconfigured or tail-frozen, and it
// deliberately leaves lastSplice_ alone so a linked follower's schedule is unaffected.
// RT-safe.
void writeFrame(AudioSample in);
// Produces one output frame WITHOUT consuming a source frame — the stretch path's starved
// output frame when the source is consumed slower than the output runs. Identical to
// process()/processLinked() in every other respect. Returns 0 while unconfigured (there is
// no input to pass through). RT-safe.
AudioSample processNoInput();
AudioSample processNoInputLinked(const SpliceEvent& master);
const SpliceEvent& lastSplice() const { return lastSplice_; }
// Call once the source stream is exhausted — no real frame remains to feed process().
@@ -137,7 +192,9 @@ private:
void applySplice(const SpliceEvent& ev);
// Shared body of process()/processLinked(); `linked` null = master mode (own trigger +
// search), non-null = follower mode (splice iff linked->fired, with linked's decision).
AudioSample processImpl(AudioSample in, const SpliceEvent* linked);
// `write` false is the starved stretch frame: read/splice/advance the taps, but consume no
// input and hold the write head (the same shape tail-freezing already takes).
AudioSample processImpl(AudioSample in, const SpliceEvent* linked, bool write);
std::vector<AudioSample> ring_; // delay line, length `ringLen_` == 2 * window_
std::int64_t window_ = 0; // nominal splice jump in frames; <= 1 = pass-through
@@ -152,6 +209,19 @@ private:
// ratio-scaled at splice time so an up-shift's outgoing
// tap can never drain into the writer mid-fade
std::int64_t maxLag_ = 0; // correlation search half-range (window_/4)
double period_ = 0.0; // source period in frames, 0 = unknown (fixed-window)
std::int64_t jump_ = 0; // nominal splice jump; window_ unless period_ retunes it
std::int64_t jumpMax_ = 0; // largest jump whose post-splice delay stays STRICTLY
// inside [dLow_, dHigh_] at the worst search lag, so a
// period-sized jump can never land back on a trigger and
// thrash (dHigh_-dLow_-maxLag_-1, i.e. 1.25*window_). At
// jump_==jumpMax_ a DOWN-splice's correlation read comes
// within ~41 frames of the write head (measured: the
// exact ring/lag/corrFrames_ geometry at the product
// window, worst case over every lag the search reaches) —
// real margin, not zero, but tight enough that widening
// maxLag_, corrFrames_ or jumpMax_ without re-deriving
// this bound risks reading unwritten ring content.
std::int64_t corrFrames_ = 0; // correlation segment length (dLow_-1, capped at 512, so
// the reference read forward from the tap stays behind
// the writer by construction at an up-splice)
@@ -161,6 +231,7 @@ private:
// clamps its up-jump to this so it never lands in
// unwritten silence
double ratio_ = 1.0; // current shift ratio (>0)
double feedRate_ = 1.0; // source frames written per output frame; splice-fade only
SpliceEvent lastSplice_{}; // decision of the most recent process*() frame; cleared
// at the top of every frame, set on a splice
bool tailFrozen_ = false; // writer frozen (source exhausted); tap recycles the
+165 -35
View File
@@ -11,9 +11,12 @@
#include "core/audio/peaks.h"
#include "core/instrument/engine/filter/voice_filter.h"
#include "core/instrument/engine/velocity_curve.h"
#include "core/util/curve_law.h" // the per-segment curve exponent domain + its neutral
namespace reasampler {
namespace instrument::engine { class LiveParams; } // live_params.h; SampleData holds a pointer
using audio::AudioSample;
using instrument::engine::VelocityCurve;
@@ -37,34 +40,58 @@ inline constexpr int kMaxVoiceCount = 32;
inline constexpr int kDefaultVoiceCount = 16;
// AHDSR amplitude envelope. holdFrames == 0 is exactly the pre-hold-stage ADSR (back-compat).
// The three curve exponents shape the SLOPED stages only — Hold and Sustain are flat by
// definition and carry none. `curve_law.h` owns what an exponent means.
struct AdsrParams {
std::int64_t attackFrames = 0;
std::int64_t holdFrames = 0;
std::int64_t decayFrames = 0;
double sustainLevel = 1.0; // 0..1
std::int64_t releaseFrames = 0;
double attackCurve = util::kCurveNeutral;
double decayCurve = util::kCurveNeutral;
double releaseCurve = util::kCurveNeutral;
};
// Attack -> Hold -> Decay over a bounded span: the shape every SUSTAIN-LESS envelope takes
// (the Trigger amp, the Trigger filter envelope, the pitch envelope). Hold is a FRACTION of
// the span left after attack and decay, never a time of its own — fitAhd (envelopes.h) owns
// why a fraction, not a time.
struct AhdParams {
std::int64_t attackFrames = 0;
std::int64_t decayFrames = 0;
double holdFraction = 1.0; // 0..1 of the span remaining after attack + decay
double attackCurve = util::kCurveNeutral;
double decayCurve = util::kCurveNeutral;
};
// Which shape an envelope takes: the STAGED knobs, or a free-drawn SPLINE contour. Both states
// are stored side by side and neither converts into the other, so a mode flip is reversible and
// lossless — the inactive one is saved but inert, edited only by switching back to it.
enum class EnvMode { Staged, Spline };
// The free-drawn alternative to a staged envelope: a contour over NORMALIZED sample time,
// covering the full sample length. Normalized is what makes it length-independent — a
// different-length capture replays the same shape proportionally, with no stored seconds to
// rescale. The default is the smooth y = 1 - x downward slope.
struct SplineEnv {
EnvMode mode = EnvMode::Staged;
VelocityCurve contour = VelocityCurve::rampDown();
};
// GATE = classic held note (AHDSR + sustain loop + note-off release). TRIGGER = one-shot:
// note-off-immune, no sustain loop, plays a % of sample length shaped by fade-in/out. Both
// honor the start point. Default Gate so an instrument with no params set plays as before.
// note-off-immune, no sustain loop, plays a % of sample length shaped by the AHD. Both honor
// the start point. Default Gate so an instrument with no params set plays as before.
enum class PlayMode { Gate, Trigger };
// Playback covers [startFrame, playEnd), playEnd = startFrame +
// round(lengthFraction*(frames - startFrame)). Amplitude ramps 0->1 over fadeInFrames at the
// head and 1->0 over fadeOutFrames anchored to playEnd; unity between. Fades clamp so
// fadeIn + fadeOut <= play length. The voice frees when the head reaches playEnd.
// Trigger's play SPAN: [startFrame, playEnd), playEnd = startFrame +
// round(lengthFraction*(frames - startFrame)). The voice frees when the head reaches playEnd.
// The amplitude SHAPE over that span is PlayParams::trigAhd — the fade-in/fade-out pair that
// used to live here is retired; do not reintroduce a second amplitude mechanism.
struct TriggerParams {
double lengthFraction = 1.0; // (0,1] of the post-start span to play
std::int64_t fadeInFrames = 0;
std::int64_t fadeOutFrames = 0;
double lengthFraction = 1.0; // (0,1] of the post-start span to play
};
// EQUAL_POWER (constant-power sin/cos) is the click-free default for Trigger's ramps; LINEAR is
// the build-time residual.
enum class FadeCurve { EqualPower, Linear };
inline constexpr FadeCurve kDefaultFadeCurve = FadeCurve::EqualPower;
// VARISPEED: readPos_ += ratio_, pitch and duration coupled (an octave up plays half as long).
// PRESERVE: the read advances at the source rate while a PitchShifter transposes the output
// (an octave up keeps its length).
@@ -81,14 +108,15 @@ inline constexpr PitchEngine kDefaultPitchEngine = PitchEngine::Preserve;
// of real source, so output frame 0 is source frame 0 regardless of window size.
inline constexpr double kPreserveWindowMs = 50.0;
// AD pitch-modulation envelope, off by default (enabled=false -> offset always 0 -> bit-identical
// to the un-modulated engine). At note-on the offset rises to peakSemitones over attackFrames,
// then falls to 0 over decayFrames; a zero attack gives a pure percussive pitch drop.
// AHD pitch-modulation envelope, off by default (enabled=false -> offset always 0 ->
// bit-identical to the un-modulated engine). At note-on the offset rises to peakSemitones over
// attack, holds there, then falls to 0 over decay; a zero attack gives a pure percussive pitch
// drop. The hold fraction defaults to 0 so an instance predating the stage plays exactly as its
// attack-decay predecessor did.
struct PitchEnvParams {
bool enabled = false;
std::int64_t attackFrames = 0;
std::int64_t decayFrames = 0;
double peakSemitones = 0.0; // signed depth at the peak
bool enabled = false;
double peakSemitones = 0.0; // signed depth at the peak
AhdParams shape{0, 0, /*holdFraction=*/0.0, util::kCurveNeutral, util::kCurveNeutral};
};
// Per-voice resonant filter, off by default (enabled=false -> the render path skips it
@@ -102,30 +130,110 @@ struct FilterParams {
bool enabled = false;
instrument::engine::filter::FilterSettings settings;
double modAmount = 0.0; // bipolar [-1,+1], envelope -> cutoff
double velAmount = 0.0; // bipolar [-1,+1], velocity -> cutoff
double velAmount = 0.0; // bipolar [-1,+1], scales velocityCurve's output
double keyTrack = 0.0; // octaves of cutoff per octave of (note - root)
AdsrParams env; // the same staged AHDSR the amp runs; frames
// Shapes velocity before velAmount scales it. Linear rather than the amp's flat() default
// because a flat curve under a depth control would make every velocity the same offset;
// the no-op at rest is velAmount == 0, not the curve. NOTE: this default only governs a
// FRESH FilterParams — the shared codec's corrupt/truncated-point-list repair
// (VelocityCurve::fromPoints, used for both this curve and the amp's) still degrades to
// flat() regardless, since that repair has no curve-specific fallback.
VelocityCurve velocityCurve = VelocityCurve::linear();
// The filter envelope takes the same shape the amp does under the active play mode:
// AHDSR in Gate, AHD in Trigger. Both are stored, so a mode flip cannot lose either
// mode's dialled values (see core/instrument/CLAUDE.md).
AdsrParams env; // Gate: the same staged AHDSR the amp runs; frames
AhdParams trigEnv; // Trigger: the same staged AHD the amp runs; frames
// Velocity -> cutoff, in the normalized cutoff domain. The contribution is
// velAmount * velocityCurve.eval(velocity): the BIPOLAR curve carries the shape (and its
// own sign), the depth knob scales it, and BOTH apply. The curve is flat at 0 by default,
// so no depth setting produces velocity modulation until a curve is drawn.
VelocityCurve velocityCurve = VelocityCurve::zero();
};
// Full-scale of the velocity->pitch curve: y = +/-1 transposes by this many semitones. Shared
// with the pitch envelope's own depth throw so the two pitch modulators speak one range.
inline constexpr double kVelocityPitchRangeSemitones = 24.0;
// Standard 12-tone-ET tracking, and the ONE home for that number: the capture's own scalar, the
// instrument's stored scalar and the live block all default from here, so a blob predating the
// field and a block published before the first note can never disagree about it.
inline constexpr double kKeyTrackDefault = 1.0;
// Bundle a voice reads at start(). Defaults reproduce the bare engine (Gate, hold-0 AHDSR,
// Varispeed, pitch envelope off, filter off) — core regression tests rely on this; the
// Preserve product default is layered on at (de)serialization, see kDefaultPitchEngine.
// Varispeed, pitch envelope off, filter off, no velocity->pitch) — core regression tests rely
// on this; the Preserve product default is layered on at (de)serialization, see
// kDefaultPitchEngine.
struct PlayParams {
PlayMode playMode = PlayMode::Gate;
AdsrParams adsr;
TriggerParams trigger;
AdsrParams adsr; // Gate amp
TriggerParams trigger; // Trigger play span
AhdParams trigAhd; // Trigger amp
PitchEngine pitchEngine = PitchEngine::Varispeed;
// Playback RATE, as source frames consumed per output frame. Under Varispeed it is one more
// factor of the read increment, so it moves pitch and duration together; under Preserve it
// drives duration alone and the shifter holds the pitch. Latched at note-on either way (the
// loop fold and the contour scale it composes with are both note-on folds), and clamped by
// the stretcher's own clampStretchRate — never here. 1.0 is the bare engine, bit for bit.
double playRate = 1.0;
// A baseline pitch offset in semitones, folded into the note's ratio beside key-tracking and
// the velocity->pitch transpose. Live on a sounding voice under both engines.
double pitchOffsetSemitones = 0.0;
PitchEnvParams pitchEnv;
// Velocity -> pitch offset, scaled by kVelocityPitchRangeSemitones. Bipolar and flat at 0
// by default, so it transposes nothing until a curve is drawn. Folded into the voice's
// baseRatio_ at note-on — it is fixed for the note's lifetime, so it costs no per-frame work.
VelocityCurve pitchVelocityCurve = VelocityCurve::zero();
FilterParams filter;
// The three drawn contours: the alternative to adsr/trigAhd, to pitchEnv.shape, and to
// filter.env/trigEnv respectively. They sit HERE rather than inside the three envelope
// structs because those are copied whole into the live block, which must stay trivially
// copyable (live_params.h) — and a contour is not a live control anyway: like the velocity
// curves it travels by reload.
SplineEnv ampSpline;
SplineEnv pitchSpline;
SplineEnv filterSpline;
};
// Whether ANY of the three envelopes is drawn rather than staged. Templated over the two
// parameter representations (frames and the editor's seconds mirror) because both spell the
// three fields identically and the rule must not be written twice — compile-time dispatch,
// no runtime cost, off every hot path.
//
// THE consequence, and its one home: a spline contour is a pure time function over the full
// sample length, which IS the Trigger/one-shot playback model — so Gate is not available while
// any spline EG is active. resolvePlay enforces it on the way to the engine; the editor's
// play-mode toggle refuses the Gate segment so the two agree.
//
// The pitch/filter terms are gated on their own `enabled` flag to match Voice::start's binder
// (voice.cpp only binds pitchSplineCur_/filterSplineCur_ when that flag is set): without this,
// a Spline mode flip on a disabled pitch/filter envelope would cost Gate for zero modulation,
// since the binder would never actually engage. Amp has no such flag, so it counts unconditionally.
template <class Play>
bool splineActive(const Play& p) {
return p.ampSpline.mode == EnvMode::Spline ||
(p.pitchEnv.enabled && p.pitchSpline.mode == EnvMode::Spline) ||
(p.filter.enabled && p.filterSpline.mode == EnvMode::Spline);
}
// The mode the engine will actually run, and the one home of splineActive's rule (see its doc
// above). Header-inline and allocation-free: play_params.h sits on the per-voice-per-sample
// include path. Every caller — resolvePlay (sample_map.cpp), the editor's applyControl, and
// the editor's read-only predicates — routes through one of these two, so none of them can
// drift into a second reading of the fields.
template <class Play>
PlayMode effectivePlayMode(const Play& p) {
return splineActive(p) ? PlayMode::Trigger : p.playMode;
}
template <class Play>
void enforceGateUnavailableWhileDrawn(Play& p) {
p.playMode = effectivePlayMode(p);
}
// The %-length the voice ACTUALLY plays. Same rule family, same reason it is templated: a drawn
// contour is a pure time function over the full sample length, so any active spline EG folds
// the fraction to 1.0 while the stored knob goes inert — but the stored value survives, so a
// pre-spline setting is still there to be read. Every consumer of the Trigger span must fold it
// here or it silently plays/draws/bakes a fraction of the take.
template <class Play>
double effectiveLengthFraction(const Play& p) {
return splineActive(p) ? 1.0 : p.trigger.lengthFraction;
}
// [start, end) frames, half-open. A zero-length loop (start == end) is the "no sustain loop"
// marker — a held note past the sample end goes silent rather than looping a zero span.
struct SampleLoop {
@@ -151,6 +259,12 @@ struct SampleData {
int rootNote = 60;
SampleLoop loop;
// Pre-seam crossfade at the loop reset, in SOURCE frames — a source-timeline quantity
// like the loop points it belongs to, so no rate resolves it. 0 (the default) is the
// hard seam every instance predating the field plays. engine/loop/loop_span.h owns what
// the fade actually does and how it clamps.
std::int64_t loopCrossfadeFrames = 0;
// Frame offset a voice starts playback at; frame 0 default is the pre-existing behavior.
// Clamped into [0, frames) at note-on — a start >= sample length is a no-op (starts at 0).
std::int64_t startFrame = 0;
@@ -158,14 +272,30 @@ struct SampleData {
// How far keyboard pitch tracks the root: 1.0 = standard 12-tone-ET (default); 0.0 = no
// tracking (every key plays root pitch); 2.0 = double-rate. Scales the (note-root) semitone
// offset in keyTrackedRatio; rides both repitch engines via the voice's baseRatio_.
double keyTrack = 1.0;
double keyTrack = kKeyTrackDefault;
// Maps note-on velocity (0..127) to the voice's amp gain, eval'd once in Voice::start
// (never per frame). Default flat y=1 — every velocity plays at unity.
VelocityCurve velocityCurve = VelocityCurve::flat();
// The source's own fundamental period in SOURCE frames, which makes Preserve's splices
// pitch-synchronous (pitch_shift.h). DERIVED from the PCM at load, not authored and never
// persisted — a cache, not state, so it takes no rung of the payload ladder. 0 means
// unknown (nothing detected it, or the source has no single period) and restores the
// fixed-window splice geometry byte for byte, which is why a hand-built SampleData is
// still exactly the bare engine.
double sourcePeriodFrames = 0.0;
PlayParams play;
// The live-parameter block a sounding voice tracks, or null for the bare latched engine
// (the default — with no block attached the core is byte-identical to the pre-live one).
// NON-OWNING and deliberately not per-snapshot: the shell owns ONE block that outlives
// every instrument snapshot, so a voice still ringing out of the drain slot follows the
// same knob as a live one. That is the desired behaviour — it is the note the user is
// hearing. Do not "fix" it by moving ownership into the snapshot.
const instrument::engine::LiveParams* live = nullptr;
// A framesR of a different length than frames is treated as absent — a malformed pair
// never half-plays.
int channelCount() const {
+132
View File
@@ -0,0 +1,132 @@
#pragma once
// time_stretch — the Preserve engine's TIME half: how fast the source is consumed, given a
// playback rate. It pairs with pitch_shift's PITCH half (how fast the ring's read tap runs);
// the two rates are independent over one delay ring, and only their difference reaches the
// splice machinery. Header-inline: every member sits on the per-voice-per-sample feed.
#include <cstdint>
#include "core/instrument/engine/loop/loop_span.h"
namespace reasampler::instrument::engine {
// The playback rates the Preserve DSP is measured over, and therefore the only ones it
// accepts. The ceiling also bounds a voice's per-output-frame feed loop (kMaxFeedPerFrame
// source frames) — the RT-safety argument for feeding a variable count at all.
//
// This range NARROWS the splice-cadence failure onto the source fundamental; it does not
// eliminate it. A splice recurs every `pitch_shift.h`'s spliceJump() / |rate - shift| output
// frames (the tap's delay drifts across one nominal jump at that per-frame rate); the shifted
// tone's own period is `sourcePeriod / shift` output frames. Whenever the recurrence interval
// is shorter than that period, a splice lands inside a single perceived cycle and the
// correlation search has less than one period to align against. Measured at rate 4.0, shift
// 0.25 (-24 st), fixed-window jump (2205): interval 2205/3.75 ~= 588 vs period ~4*P ~= 785
// frames (P ~= 196) — matches the originally observed 539-vs-785 failure. This range's ceiling
// (2.0, not 4.0) raises the safe floor, it does not remove it: at rate 2.0, shift 0.25, interval
// = 2205/1.75 = 1260 still produces measurable splice debris for any source period P > 315
// frames (~140 Hz at 44.1k) — inside bass/low-vocal material, and -24 st is reachable from the
// Pitch knob alone. pitch_shift_tests (testStretchCadenceCornerArtifactEnergyAtRate2ShiftQuarter)
// asserts this corner directly at P=500/600/700: energy outside the fundamental runs 7-21% there
// against ~0% on an aligned control at the same rate/shift — zero-crossing period is NOT what it
// checks, since splice debris fools that estimator into reading the wrong period on a render
// whose fundamental is provably correct. (The pre-stretch rate-1.0 engine's floor by the same
// inequality is P > 735, ~60 Hz — what this range raises the floor from, not what it removes.)
//
// The above derives the floor with jump == window(), which is only the FIXED-WINDOW half of
// the story. Once a source period is known, spliceJump() is periodAlignedJump's answer instead
// (pitch_shift.h), and that answer can land NARROWER than window() — as low as ~0.63*window for
// some periods — which SHRINKS the interval and moves the failure threshold EARLIER, not later.
// There is no single closed-form floor for this case (the jump is itself a function of P), so
// read it at the concrete corner instead: at P=1470 (30 Hz at 44.1k) the same rate 2.0/shift
// 0.25 corner's jump narrows from window (2205) to 1470, and its interval from 1260 to
// 1470/1.75 = 840. Independently, at the plain (no time-stretch) rate 1.0 case, solving this
// same inequality for shift at P=1470 puts the failure threshold at shift = P/(jump+P): 0.4
// (-16 st) at the fixed-window jump (2205), 0.5 (-12 st) at the pitch-synchronous jump (1470) —
// the geometry fix that lets 30 Hz align AT ALL moves this unrelated cadence inequality's own
// trip point from roughly -16 st to roughly -12 st for the same source. Do NOT read this as a
// proven regression: the inequality above was calibrated for RANDOM-PHASE (unaligned) splices,
// and a pitch-synchronous splice is waveform-aligned by construction, which the inequality does
// not model — whether the shorter interval still produces audible debris once every splice
// lands in phase is what pitch_shift_tests' own P=1470 cadence-collapse-band measurement
// answers, not this derivation. Do not narrow kStretchRateMin/kStretchRateMax in response to
// this: sub-50 Hz sine material is first-class product material, not an edge case, and a
// narrower range does not fix a floor it does not reach.
//
// A SECOND, INDEPENDENT limit bound the same material, and no rate bound touched it. It is now
// CLOSED for any source whose period is detected, but the geometry is worth keeping because it
// is what the fixed-window fallback still lives under. A splice relocated the tap by the
// nominal window refined by a search over +/- window/4, so the reachable relocation distances
// were exactly [0.75, 1.25] * window; a phase-aligned splice needs a WHOLE NUMBER of source
// periods inside that interval. The interval is 0.5*window wide, so any period <= window/2
// always has a multiple in it — but above that, coverage breaks into disjoint bands (n=1 covers
// periods [0.75, 1.25]*window, n=2 covers [0.375, 0.625]*window) and the gap between them was
// reachable by nothing. Because both the interval and the period scale with the sample rate,
// that unalignable set is fixed in Hz by the window's MILLISECONDS: at 50 ms, f < 16 Hz and
// 26.7 Hz < f < 32 Hz. Measured there (Release, 44.1k and 48k) at 30 Hz: the rendered pitch
// stayed correct, but energy outside the fundamental was 3.6% at +2 st / rate 1.0 and 15.5% at
// rate 2.0, against 0.00% at 34 Hz under identical conditions; at 29 Hz / rate 2.0 the tone
// itself landed 7.4% flat (-133 cents).
//
// The fix is not a wider window: it is a nominal jump that is a whole number of the source's
// own periods, so an aligned landing point exists by construction (pitch_shift.h's
// periodAlignedJump, fed by period_detect at load). The same measurements then read 0.00% and
// 0.00%, and 29 Hz renders at +0.0 cents — all from `preserve_low_frequency_tests` (Release,
// hand-run; it is not in the gated ctest set), the same harness/config as the 3.6%/15.5%/-133
// cents readings above. The gated suite's own number for this is the floor-relative excess in
// pitch_shift_tests' testThirtyHertzSplicesAlignOnceTheSourcePeriodIsKnown, a different
// quantity from the raw percentages here. What survives: a period longer than the reachable
// jump (~1.25 windows, so below ~16 Hz at 50 ms) still cannot align, and a source with no
// single period falls back to it by design (periodAlignedJump, pitch_shift.h).
inline constexpr double kStretchRateMin = 0.5;
inline constexpr double kStretchRateMax = 2.0;
inline constexpr int kMaxFeedPerFrame = 2; // ceil(kStretchRateMax)
// Non-positive and NaN fold to unity rather than to the minimum: an unusable rate should leave
// playback alone, not silently quarter-speed it (the same stance as setShiftRatio's refusal to
// run the tap backward). 1.0 in gives exactly 1.0 out, which is what keeps the unity read
// bit-identical.
inline double clampStretchRate(double rate) {
if (!(rate > 0.0)) return 1.0;
if (rate < kStretchRateMin) return kStretchRateMin;
return rate > kStretchRateMax ? kStretchRateMax : rate;
}
// One Preserve voice's source-feed schedule: a fractional source cursor answering, per OUTPUT
// frame, which whole source frames fall due. At rate 1.0 that is exactly one frame per output
// frame with no residue carried — bit for bit the pre-stretch feed.
class StretchCursor {
public:
// `frame` is where the ring prime stopped; the per-frame feed continues there.
void start(std::int64_t frame) {
frame_ = frame;
debt_ = 0.0;
}
// Adds one output frame's worth of source at `rate` and returns how many whole source
// frames are now due, in [0, kMaxFeedPerFrame]. Take each of them with next(). The clamp
// lives here rather than at the caller because this return value is the loop bound.
std::int64_t due(double rate) {
debt_ += clampStretchRate(rate);
const std::int64_t whole = static_cast<std::int64_t>(debt_); // debt_ >= 0: trunc = floor
debt_ -= static_cast<double>(whole);
return whole;
}
// The next due source frame, wrapped into the sustain loop, advancing the cursor past it.
// Advances even past the playable span — the caller freezes the shifter's writer there, and
// a cursor that stalled instead would re-feed one frame forever.
std::int64_t next(const loop::ResolvedLoop& lp) {
if (lp.active) {
while (frame_ >= lp.end) frame_ -= lp.length;
}
return frame_++;
}
std::int64_t frame() const { return frame_; }
private:
std::int64_t frame_ = 0;
double debt_ = 0.0; // fractional source frames carried into the next output frame
};
} // namespace reasampler::instrument::engine
+120 -100
View File
@@ -11,159 +11,168 @@ namespace reasampler::instrument::engine {
namespace {
double clampVelocity(double v) { return std::clamp(v, kVelMin, kVelMax); }
double clampAmp(double a) { return std::clamp(a, kAmpMin, kAmpMax); }
double clampValue(double a, CurveDomain d) { return std::clamp(a, curveYMin(d), kCurveYMax); }
// X spans the width for [0,127]; Y spans (height-1) rows for amp [0,1] with amp 1 at the TOP
// (pixel y increases downward, so this axis is inverted relative to amp).
// X spans the width for [0,127]; Y spans (height-1) rows for the domain's range with its max at
// the TOP (pixel y increases downward, so this axis is inverted relative to the value).
double velPerPixel(const VelocityCurve::Box& box) {
const int w = std::max(0, box.width);
if (w <= 0) return 0.0;
return (kVelMax - kVelMin) / static_cast<double>(w);
}
double ampPerPixel(const VelocityCurve::Box& box) {
double valuePerPixel(const VelocityCurve::Box& box, CurveDomain d) {
const int h = std::max(0, box.height);
if (h <= 1) return 0.0;
return (kAmpMax - kAmpMin) / static_cast<double>(h - 1);
return (kCurveYMax - curveYMin(d)) / static_cast<double>(h - 1);
}
// The integer maps are these rounded — ONE mapping, so a sub-pixel trace and an integer hit-test
// cannot drift. Rounding the OFFSET (not the absolute coordinate) keeps the int results identical
// to what they were before the sub-pixel form existed: the offset is non-negative, so truncation
// is floor regardless of where the box sits.
double velToXf(const VelocityCurve::Box& box, double velocity) {
const int w = std::max(0, box.width);
if (w <= 0) return static_cast<double>(box.left);
const double frac = (clampVelocity(velocity) - kVelMin) / (kVelMax - kVelMin);
return static_cast<double>(box.left) + frac * static_cast<double>(w);
}
double valueToYf(const VelocityCurve::Box& box, double value, CurveDomain d) {
const int h = std::max(0, box.height);
if (h <= 1) return static_cast<double>(box.top);
const double lo = curveYMin(d);
const double frac = (clampValue(value, d) - lo) / (kCurveYMax - lo);
return static_cast<double>(box.top) + (1.0 - frac) * static_cast<double>(h - 1);
}
int velToX(const VelocityCurve::Box& box, double velocity) {
const int w = std::max(0, box.width);
if (w <= 0) return box.left;
const double frac = (clampVelocity(velocity) - kVelMin) / (kVelMax - kVelMin);
return box.left + static_cast<int>(frac * static_cast<double>(w) + 0.5);
return box.left +
static_cast<int>(velToXf(box, velocity) - static_cast<double>(box.left) + 0.5);
}
int ampToY(const VelocityCurve::Box& box, double amp) {
const int h = std::max(0, box.height);
if (h <= 1) return box.top;
const double frac = (clampAmp(amp) - kAmpMin) / (kAmpMax - kAmpMin);
return box.top + static_cast<int>((1.0 - frac) * static_cast<double>(h - 1) + 0.5);
int valueToY(const VelocityCurve::Box& box, double value, CurveDomain d) {
return box.top +
static_cast<int>(valueToYf(box, value, d) - static_cast<double>(box.top) + 0.5);
}
} // namespace
VelocityCurve VelocityCurve::flat() {
VelocityCurve c;
c.points_ = {{kVelMin, kAmpMax}, {kVelMax, kAmpMax}};
const double n = curveNeutral(CurveDomain::Unipolar);
c.points_ = {{kVelMin, n}, {kVelMax, n}};
return c;
}
VelocityCurve VelocityCurve::linear() {
VelocityCurve c;
c.points_ = {{kVelMin, kAmpMin}, {kVelMax, kAmpMax}};
c.points_ = {{kVelMin, 0.0}, {kVelMax, kCurveYMax}};
return c;
}
VelocityCurve VelocityCurve::fromPoints(std::vector<VelocityPoint> pts) {
VelocityCurve VelocityCurve::zero() {
VelocityCurve c;
c.domain_ = CurveDomain::Bipolar;
const double n = curveNeutral(CurveDomain::Bipolar);
c.points_ = {{kVelMin, n}, {kVelMax, n}};
return c;
}
VelocityCurve VelocityCurve::rampDown() {
VelocityCurve c;
c.points_ = {{kVelMin, kCurveYMax, false}, {kVelMax, 0.0, false}};
return c;
}
VelocityCurve VelocityCurve::fromPoints(std::vector<VelocityPoint> pts, CurveDomain domain) {
// Stable sort so coincident-X points keep their wire order (eval stays well-defined for
// duplicate-X knots).
// Trim before the endpoint synthesis below can add up to two more, then again after, so a
// corrupt over-long blob lands at exactly the ceiling with its two endpoints intact.
if (pts.size() > kMaxCurvePoints) pts.resize(kMaxCurvePoints);
for (VelocityPoint& p : pts) {
p.velocity = clampVelocity(p.velocity);
p.amp = clampAmp(p.amp);
p.value = clampValue(p.value, domain);
}
std::stable_sort(pts.begin(), pts.end(),
[](const VelocityPoint& a, const VelocityPoint& b) {
return a.velocity < b.velocity;
});
if (pts.size() < 2) return flat();
if (pts.size() < 2) {
return domain == CurveDomain::Bipolar ? zero() : flat();
}
if (pts.front().velocity > kVelMin) {
pts.insert(pts.begin(), VelocityPoint{kVelMin, pts.front().amp});
pts.insert(pts.begin(), VelocityPoint{kVelMin, pts.front().value, pts.front().hard});
} else {
pts.front().velocity = kVelMin;
}
if (pts.back().velocity < kVelMax) {
pts.push_back(VelocityPoint{kVelMax, pts.back().amp});
pts.push_back(VelocityPoint{kVelMax, pts.back().value, pts.back().hard});
} else {
pts.back().velocity = kVelMax;
}
if (pts.size() > kMaxCurvePoints) {
// Drop the interior points nearest the end, never an endpoint.
pts.erase(pts.begin() + static_cast<std::ptrdiff_t>(kMaxCurvePoints) - 1,
pts.end() - 1);
}
VelocityCurve c;
c.domain_ = domain;
c.points_ = std::move(pts);
return c;
}
namespace {
// Fritsch-Carlson monotone-cubic tangent: a sign change (or flat) neighbour is a local extremum,
// so the tangent pins to 0 to avoid overshoot; otherwise the weighted-harmonic-mean tangent,
// which for collinear knots (dPrev==dNext) reduces exactly to the shared secant — this is what
// makes the spline reproduce a straight line to ~1e-15 for linear()-style input.
double fritschCarlsonTangent(double dPrev, double dNext, double spanPrev, double spanNext) {
if (dPrev * dNext <= 0.0) return 0.0;
const double w1 = 2.0 * spanNext + spanPrev;
const double w2 = spanNext + 2.0 * spanPrev;
return (w1 + w2) / (w1 / dPrev + w2 / dNext);
}
} // namespace
double VelocityCurve::eval(double velocity) const {
if (points_.empty()) return kAmpMax;
if (points_.size() == 1) return clampAmp(points_[0].amp);
if (points_.empty()) return curveNeutral(domain_);
if (points_.size() == 1) return clampValue(points_[0].value, domain_);
const double v = clampVelocity(velocity);
if (v <= points_.front().velocity) return clampAmp(points_.front().amp);
if (v >= points_.back().velocity) return clampAmp(points_.back().amp);
if (v <= points_.front().velocity) return clampValue(points_.front().value, domain_);
if (v >= points_.back().velocity) return clampValue(points_.back().value, domain_);
// Linear walk: this overload is the COLD one (a note-on, a paint column). The per-sample
// reader is SplineCursor, which shares the same tangent + Hermite functions.
for (std::size_t i = 0; i + 1 < points_.size(); ++i) {
const VelocityPoint& a = points_[i];
const VelocityPoint& b = points_[i + 1];
if (v >= a.velocity && v <= b.velocity) {
const double span = b.velocity - a.velocity;
// Coincident-X neighbours (a step): zero-width segment, no interior to blend.
if (span <= 0.0) return clampAmp(b.amp);
// Monotone cubic Hermite (Fritsch-Carlson): provably stays within [a.amp, b.amp]
// between the two knots (no overshoot), reproducing a straight line for collinear input.
const double d = (b.amp - a.amp) / span;
double mA = d;
if (i > 0) {
const VelocityPoint& prev = points_[i - 1];
const double spanPrev = a.velocity - prev.velocity;
if (spanPrev > 0.0) {
const double dPrev = (a.amp - prev.amp) / spanPrev;
mA = fritschCarlsonTangent(dPrev, d, spanPrev, span);
} else {
mA = 0.0;
}
}
double mB = d;
if (i + 2 < points_.size()) {
const VelocityPoint& next = points_[i + 2];
const double spanNext = next.velocity - b.velocity;
if (spanNext > 0.0) {
const double dNext = (next.amp - b.amp) / spanNext;
mB = fritschCarlsonTangent(d, dNext, span, spanNext);
} else {
mB = 0.0;
}
}
const double t = (v - a.velocity) / span;
const double t2 = t * t;
const double t3 = t2 * t;
const double h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
const double h10 = t3 - 2.0 * t2 + t;
const double h01 = -2.0 * t3 + 3.0 * t2;
const double h11 = t3 - t2;
const double y = h00 * a.amp + h10 * span * mA + h01 * b.amp + h11 * span * mB;
return clampAmp(y);
if (span <= 0.0) return clampValue(b.value, domain_);
const double d = (b.value - a.value) / span;
const SegmentTangents m = segmentTangents(points_.data(), points_.size(), i, d, span);
const double y = hermiteAt(a.value, b.value, span, m.mA, m.mB,
(v - a.velocity) / span);
return clampValue(y, domain_);
}
}
return clampAmp(points_.back().amp); // unreachable (v is between the endpoints)
return clampValue(points_.back().value, domain_); // unreachable (v is between the endpoints)
}
std::size_t VelocityCurve::addPoint(double velocity, double amp) {
const VelocityPoint p{clampVelocity(velocity), clampAmp(amp)};
int VelocityCurve::addPoint(double velocity, double value) {
// At the ceiling the add is REFUSED outright rather than trading a point away — the existing
// contour must come through an over-add bit-identical.
if (points_.size() >= kMaxCurvePoints) return -1;
const VelocityPoint p{clampVelocity(velocity), clampValue(value, domain_), false};
// First index strictly greater, so a duplicate-X point lands immediately after the existing one.
std::size_t i = 0;
while (i < points_.size() && points_[i].velocity <= p.velocity) ++i;
points_.insert(points_.begin() + static_cast<std::ptrdiff_t>(i), p);
return i;
return static_cast<int>(i);
}
VelocityPoint VelocityCurve::movePoint(std::size_t index, double velocity, double amp) {
bool VelocityCurve::toggleHard(std::size_t index) {
if (index >= points_.size()) return false;
points_[index].hard = !points_[index].hard;
return true;
}
bool VelocityCurve::setHard(std::size_t index, bool hard) {
if (index >= points_.size()) return false;
points_[index].hard = hard;
return true;
}
VelocityPoint VelocityCurve::movePoint(std::size_t index, double velocity, double value) {
if (index >= points_.size()) return VelocityPoint{}; // no-op (out of range)
const bool isFirst = (index == 0);
const bool isLast = (index + 1 == points_.size());
double newAmp = clampAmp(amp);
double newValue = clampValue(value, domain_);
double newVel;
if (isFirst) {
newVel = kVelMin;
@@ -174,7 +183,7 @@ VelocityPoint VelocityCurve::movePoint(std::size_t index, double velocity, doubl
const double hi = points_[index + 1].velocity;
newVel = std::clamp(clampVelocity(velocity), lo, hi);
}
points_[index] = VelocityPoint{newVel, newAmp};
points_[index] = VelocityPoint{newVel, newValue, points_[index].hard};
return points_[index];
}
@@ -185,12 +194,18 @@ bool VelocityCurve::deletePoint(std::size_t index) {
return true;
}
VelocityCurve::CurvePixel VelocityCurve::pixelFromPoint(const Box& box, const VelocityPoint& p) {
return CurvePixel{velToX(box, p.velocity), ampToY(box, p.amp)};
VelocityCurve::CurvePixel VelocityCurve::pixelFromPoint(const Box& box,
const VelocityPoint& p) const {
return CurvePixel{velToX(box, p.velocity), valueToY(box, p.value, domain_)};
}
VelocityPoint VelocityCurve::pointFromPixel(const Box& box, int x, int y) {
// Exact inverse of velToX/ampToY (within one pixel); degenerate dims collapse the same way.
VelocityCurve::CurvePixelF VelocityCurve::subpixelFromPoint(const Box& box,
const VelocityPoint& p) const {
return CurvePixelF{velToXf(box, p.velocity), valueToYf(box, p.value, domain_)};
}
VelocityPoint VelocityCurve::pointFromPixel(const Box& box, int x, int y) const {
// Exact inverse of velToX/valueToY (within one pixel); degenerate dims collapse the same way.
VelocityPoint p;
const int w = std::max(0, box.width);
const int h = std::max(0, box.height);
@@ -198,17 +213,19 @@ VelocityPoint VelocityCurve::pointFromPixel(const Box& box, int x, int y) {
? kVelMin
: clampVelocity(kVelMin + static_cast<double>(x - box.left) / static_cast<double>(w) *
(kVelMax - kVelMin));
p.amp = (h <= 1)
? kAmpMax
: clampAmp(kAmpMax - static_cast<double>(y - box.top) / static_cast<double>(h - 1) *
(kAmpMax - kAmpMin));
const double lo = curveYMin(domain_);
p.value = (h <= 1)
? kCurveYMax
: clampValue(kCurveYMax - static_cast<double>(y - box.top) / static_cast<double>(h - 1) *
(kCurveYMax - lo),
domain_);
return p;
}
int VelocityCurve::pointAtPixel(const Box& box, int x, int y) const {
for (std::size_t i = 0; i < points_.size(); ++i) {
const int px = velToX(box, points_[i].velocity);
const int py = ampToY(box, points_[i].amp);
const int py = valueToY(box, points_[i].value, domain_);
if (std::abs(x - px) <= kCurveNodeGrabRadius && std::abs(y - py) <= kCurveNodeGrabRadius) {
return static_cast<int>(i);
}
@@ -221,22 +238,25 @@ VelocityCurve VelocityCurve::resolvePointDrag(const VelocityCurve& grabCurve, st
VelocityCurve out = grabCurve;
if (index >= out.points_.size()) return out; // out of range -> no motion
const double velPerPx = velPerPixel(box);
const double ampPerPx = ampPerPixel(box);
if (velPerPx <= 0.0 || ampPerPx <= 0.0) return out; // degenerate box -> no motion
const double valPerPx = valuePerPixel(box, grabCurve.domain_);
if (velPerPx <= 0.0 || valPerPx <= 0.0) return out; // degenerate box -> no motion
const VelocityPoint& grab = grabCurve.points_[index];
const double newVel = grab.velocity + static_cast<double>(dxPixels) * velPerPx;
// Y increases downward but amp increases upward, so a downward drag (positive dy) LOWERS amp.
const double newAmp = grab.amp - static_cast<double>(dyPixels) * ampPerPx;
out.movePoint(index, newVel, newAmp); // applies box + neighbour-X + endpoint-pin clamps
// Y increases downward but the value increases upward, so a downward drag (positive dy)
// LOWERS the value.
const double newValue = grab.value - static_cast<double>(dyPixels) * valPerPx;
out.movePoint(index, newVel, newValue); // applies box + neighbour-X + endpoint-pin clamps
return out;
}
bool VelocityCurve::equals(const VelocityCurve& other, double eps) const {
if (domain_ != other.domain_) return false;
if (points_.size() != other.points_.size()) return false;
for (std::size_t i = 0; i < points_.size(); ++i) {
if (std::fabs(points_[i].velocity - other.points_[i].velocity) > eps) return false;
if (std::fabs(points_[i].amp - other.points_[i].amp) > eps) return false;
if (std::fabs(points_[i].value - other.points_[i].value) > eps) return false;
if (points_[i].hard != other.points_[i].hard) return false;
}
return true;
}
+237 -34
View File
@@ -1,71 +1,169 @@
// velocity_curve.h — velocity->amp transfer curve. eval(velocity) is called once per note-on
// in Voice::start(), never per frame. Editor hit-test/inverse-map take an explicit pixel Box
// rather than a Rect: this module sits below sampler_core in the link graph and must not gain
// a transitive dependency on editor-layout types.
// velocity_curve.h — THE monotone spline, shared by every consumer: the three velocity
// transfer curves (amp gain, pitch offset, filter cutoff offset), evaluated once per note-on,
// and the spline EGs, evaluated per voice per sample through SplineCursor. Editor
// hit-test/inverse-map take an explicit pixel Box rather than a Rect: this module sits below
// sampler_core in the link graph and must not gain a dependency on editor-layout types.
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
namespace reasampler::instrument::engine {
// The MIDI velocity domain [0,127] and the amp range [0,1] — the box every point clamps into.
inline constexpr double kVelMin = 0.0;
inline constexpr double kVelMax = 127.0;
inline constexpr double kAmpMin = 0.0;
inline constexpr double kAmpMax = 1.0;
// The curve's canonical X span. For the three velocity consumers it IS the MIDI velocity
// domain; a spline EG maps normalized sample time onto the same span, which is what lets one
// implementation serve both without a second X domain to keep in sync.
inline constexpr double kCurveXMin = 0.0;
inline constexpr double kCurveXMax = 127.0;
inline constexpr double kVelMin = kCurveXMin; // the velocity consumers' spelling of the span
inline constexpr double kVelMax = kCurveXMax;
inline constexpr double kCurveYMax = 1.0;
// Point-count ceiling. A MUSICAL bound, not a performance one: long rhythmic phrases need the
// resolution, and at roughly two points per articulation event 128 is about four bars of 16ths.
// Segment lookup is logarithmic (<=7 steps at this ceiling), so there is no performance case for
// lowering it. DO NOT LOWER.
inline constexpr std::size_t kMaxCurvePoints = 128;
// The curve's Y range. UNIPOLAR [0,1] is a GAIN — the amp's domain, where the do-nothing
// curve is flat at 1. BIPOLAR [-1,1] is a SIGNED modulation shape — the pitch and filter
// domains, where the do-nothing curve is flat at 0 and the sign picks the direction. A
// bipolar curve does not preclude a depth control beside it: the filter has one, and the two
// compose multiplicatively (play_params.h).
enum class CurveDomain { Unipolar, Bipolar };
constexpr double curveYMin(CurveDomain d) { return d == CurveDomain::Bipolar ? -1.0 : 0.0; }
// The value that changes nothing in each domain — unity gain, or zero modulation. THE one home
// for that value: eval()'s own empty-curve fallback reads it directly, and flat()/zero() (what
// fromPoints' sub-2-point fallback constructs) are built from it too, so a corrupt blob always
// loses the shaping rather than inventing one, however the fallback is reached.
constexpr double curveNeutral(CurveDomain d) { return d == CurveDomain::Bipolar ? 0.0 : 1.0; }
// A raw-constructed point is NOT auto-clamped (the mutators own that invariant) — build curves
// through the named constructors / addPoint rather than pushing raw points.
struct VelocityPoint {
double velocity = 0.0; // X, [0,127]
double amp = 0.0; // Y, [0,1]
double velocity = 0.0; // X, over the canonical span
double value = 0.0; // Y, in the owning curve's domain
// A HARD point does no smoothing on either side: it terminates the monotone sub-curve, so
// the two adjacent segments meet at their own natural angle instead of a shared derivative.
// Points are smooth by default; see segmentTangents for the mechanism.
bool hard = false;
};
// Fritsch-Carlson monotone-cubic tangent: a sign change (or flat) neighbour is a local extremum,
// so the tangent pins to 0 to avoid overshoot; otherwise the weighted-harmonic-mean tangent,
// which for collinear knots (dPrev==dNext) reduces exactly to the shared secant — this is what
// makes the spline reproduce a straight line for linear()-style input.
inline double fritschCarlsonTangent(double dPrev, double dNext, double spanPrev, double spanNext) {
if (dPrev * dNext <= 0.0) return 0.0;
const double w1 = 2.0 * spanNext + spanPrev;
const double w2 = spanNext + 2.0 * spanPrev;
return (w1 + w2) / (w1 / dPrev + w2 / dNext);
}
struct SegmentTangents {
double mA = 0.0;
double mB = 0.0;
};
// The Hermite tangents for segment [i, i+1] of an X-ordered point array, where `d` is that
// segment's secant slope and `span` its X width (> 0).
//
// A HARD point is treated exactly as the array's own end is: the tangent there is the segment's
// own secant, so smoothing stops at it. That single rule is the whole hard-point enhancement —
// the contour becomes one or more monotone splines joined at their natural angles, and each
// sub-curve keeps Fritsch-Carlson's no-overshoot guarantee because m == d satisfies its bound.
inline SegmentTangents segmentTangents(const VelocityPoint* p, std::size_t n, std::size_t i,
double d, double span) {
SegmentTangents t{d, d};
if (i > 0 && !p[i].hard) {
const double spanPrev = p[i].velocity - p[i - 1].velocity;
t.mA = (spanPrev > 0.0)
? fritschCarlsonTangent((p[i].value - p[i - 1].value) / spanPrev, d, spanPrev,
span)
: 0.0;
}
if (i + 2 < n && !p[i + 1].hard) {
const double spanNext = p[i + 2].velocity - p[i + 1].velocity;
t.mB = (spanNext > 0.0)
? fritschCarlsonTangent(d, (p[i + 2].value - p[i + 1].value) / spanNext, span,
spanNext)
: 0.0;
}
return t;
}
// The cubic Hermite basis evaluated at t in [0,1] across a segment of width `span`.
inline double hermiteAt(double y0, double y1, double span, double mA, double mB, double t) {
const double t2 = t * t;
const double t3 = t2 * t;
return (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * span * mA +
(-2.0 * t3 + 3.0 * t2) * y1 + (t3 - t2) * span * mB;
}
// Pick radius (px) around a node's drawn point for the editor hit-test.
inline constexpr int kCurveNodeGrabRadius = 6;
// An X-ordered list of control points spanning [0,127], evaluated by a monotone cubic Hermite
// spline (Fritsch-Carlson slope limiting) — a genuine curve, not a polyline, that provably never
// overshoots a segment's amp range. For collinear knots the tangents reduce to the secant slope,
// so the spline reproduces linear()'s straight line to within ~1e-15. The two endpoints (velocity
// 0 and 127) are load-bearing: they keep eval total over the domain and are never deletable.
// An X-ordered list of control points spanning the canonical X span, evaluated as ONE OR MORE
// monotone cubic Hermite splines (Fritsch-Carlson slope limiting) joined at the hard points — a
// genuine curve, not a polyline, that provably never overshoots any segment's value range. The
// guarantee is PER SEGMENT, so a contour is free to rise and fall. For collinear knots the
// tangents reduce to the secant slope, so the spline reproduces linear()'s straight line to
// within ~1e-15. The two endpoints are load-bearing: they keep eval total over the domain and
// are never deletable.
class VelocityCurve {
public:
// flat() (endpoints (0,1)/(127,1), every velocity -> unity) is the default — see
// flat() (endpoints (0,1)/(127,1), every velocity -> unity) is the unipolar default — see
// velocity_curve in the directory CLAUDE.md for why this isn't bit-identical to the
// pre-existing linear() response.
static VelocityCurve flat();
static VelocityCurve linear();
// The bipolar default: flat at 0, so velocity modulates nothing until a curve is drawn.
static VelocityCurve zero();
// y = 1 - x: the smooth downward slope a freshly created spline EG opens on. Two collinear
// knots, so it is straight — and straight is smooth. NOT a change to any velocity curve's
// own default.
static VelocityCurve rampDown();
// Rebuilds from a deserialized point list, repairing the invariant defensively: box-clamps
// each point, stable-sorts by velocity, forces both endpoints present (synthesized if
// missing), falls back to flat() if fewer than 2 usable points remain. A corrupt/truncated
// blob yields a well-formed curve, never an invariant-violating one.
static VelocityCurve fromPoints(std::vector<VelocityPoint> pts);
// each point into `domain`, stable-sorts by velocity, forces both endpoints present
// (synthesized if missing), falls back to the domain's neutral curve if fewer than 2 usable
// points remain. A corrupt/truncated blob yields a well-formed curve, never an
// invariant-violating one.
static VelocityCurve fromPoints(std::vector<VelocityPoint> pts, CurveDomain domain);
CurveDomain domain() const { return domain_; }
const std::vector<VelocityPoint>& points() const { return points_; }
std::size_t size() const { return points_.size(); }
// Degenerate cases (shouldn't occur post-construction): empty curve returns kAmpMax; a
// one-point curve returns that point's amp.
// Degenerate cases (shouldn't occur post-construction): empty curve returns the domain's
// neutral; a one-point curve returns that point's value.
double eval(double velocity) const;
// Inserted at a velocity duplicating an existing point lands immediately after it, so a
// subsequent move can separate them. Returns the inserted index.
std::size_t addPoint(double velocity, double amp);
// subsequent move can separate them. Returns the inserted index, or -1 when the curve is
// already at kMaxCurvePoints — a refusal leaves the contour bit-identical.
int addPoint(double velocity, double value);
// Flips a point between hard and smooth. Out-of-range index is a no-op returning false.
// Permitted on the endpoints, where it changes nothing evaluable: an endpoint's outward
// tangent is already its own secant, which is what hard means.
bool toggleHard(std::size_t index);
bool setHard(std::size_t index, bool hard);
// Box-clamped and X-clamped between immediate neighbours (monotonic-X grammar). The two
// endpoints are pinned in X (only their amp moves); out-of-range index is a no-op.
VelocityPoint movePoint(std::size_t index, double velocity, double amp);
// endpoints are pinned in X (only their value moves); out-of-range index is a no-op.
VelocityPoint movePoint(std::size_t index, double velocity, double value);
// Endpoints (index 0 and last) are not deletable; that or an out-of-range index is a no-op
// returning false.
bool deletePoint(std::size_t index);
// The drawn box, in pixels: X = velocity across the width, Y = amp UP the height (amp 1 at
// top). Passed explicitly rather than a Rect — see header preamble.
// The drawn box, in pixels: X = velocity across the width, Y = value UP the height (the
// domain's max at top). Passed explicitly rather than a Rect — see header preamble.
struct Box {
int left = 0;
int top = 0;
@@ -82,14 +180,25 @@ public:
int x = 0;
int y = 0;
};
static CurvePixel pixelFromPoint(const Box& box, const VelocityPoint& p);
CurvePixel pixelFromPoint(const Box& box, const VelocityPoint& p) const;
// Exact inverse of pixelFromPoint (within the one-pixel quantum) — where an empty-space click
// lands as a new point. Degenerate box: zero-width reads velocity 0; height <= 1 reads amp 1.
static VelocityPoint pointFromPixel(const Box& box, int x, int y);
// The SAME mapping before rounding: pixelFromPoint IS this, rounded, so a sub-pixel trace and
// an integer hit-test cannot drift. An antialiased stroke needs the fraction — quantizing y to
// a whole pixel forces the slope into alternating 1/2-px steps, and that beat-frequency
// staircase is what read as a dotted line where a contour steepened.
struct CurvePixelF {
double x = 0.0;
double y = 0.0;
};
CurvePixelF subpixelFromPoint(const Box& box, const VelocityPoint& p) const;
// Exact inverse of pixelFromPoint (within the one-pixel quantum) — where an empty-space
// click lands as a new point. Degenerate box: zero-width reads velocity 0; height <= 1
// reads the domain's max (the top row is what a collapsed box draws).
VelocityPoint pointFromPixel(const Box& box, int x, int y) const;
// `grabCurve` is the curve as of mouse-down (shell snapshots it so the delta is absolute).
// Maps the pixel delta to velocity/amp over the box, then applies movePoint's clamp. Zero
// Maps the pixel delta to velocity/value over the box, then applies movePoint's clamp. Zero
// width/height box or out-of-range index returns grabCurve unchanged.
static VelocityCurve resolvePointDrag(const VelocityCurve& grabCurve, std::size_t index,
const Box& box, int dxPixels, int dyPixels);
@@ -97,9 +206,103 @@ public:
bool equals(const VelocityCurve& other, double eps = 1e-9) const;
private:
// Private: an implicit-default curve is empty (no endpoints) and Unipolar, so a stray
// default-construction wouldn't fail loudly — it would eval() to unity gain everywhere,
// or a full +/-1 (a full-scale transpose / wide-open filter) if ever read as bipolar. Build
// through flat()/linear()/zero()/fromPoints(), all of which establish the endpoint invariant.
VelocityCurve() = default;
// Always X-ordered with an endpoint at 0 and 127; constructors + deserialize establish the
// invariant, mutators preserve it.
std::vector<VelocityPoint> points_;
CurveDomain domain_ = CurveDomain::Unipolar;
};
// The RT read head over a contour: an indexed segment search plus one Hermite evaluation, with
// the segment and its two tangents cached across samples so a monotone read costs one compare.
// Header-inline, branch-only, NO allocation and NO virtual dispatch — it runs per voice per
// sample. A jump (a loop wrap, a fresh note) falls back to a binary search, <= 7 steps at the
// 128-point ceiling.
//
// Holds a RAW POINTER into the bound curve's point array: the caller guarantees the curve
// outlives the cursor. The voice binds against its SampleData, which has exactly that lifetime.
class SplineCursor {
public:
// Binds `c` if it has an evaluable segment; a shorter curve leaves the cursor inactive so
// the caller's `if (active())` skips the whole spline path.
void bind(const VelocityCurve& c) {
const std::vector<VelocityPoint>& pts = c.points();
if (pts.size() < 2) { clear(); return; }
pts_ = pts.data();
n_ = pts.size();
select(0);
}
void clear() { pts_ = nullptr; n_ = 0; }
bool active() const { return n_ >= 2; }
// True once the cursor has settled on the contour's LAST segment. On its own this does NOT
// make a 0 read here a terminus: the final segment's LEFT endpoint can also be 0 (a 2-point
// contour is nothing but a single "final" segment starting at frame 0), which would read 0
// while about to rise. Voice::tickAmplitude pairs this with segmentEndValue() == 0 — the
// segment's RIGHT endpoint, i.e. the whole contour's true end — before calling a 0 read the
// note's genuine permanent terminus.
bool onFinalSegment() const { return seg_ + 2 == n_; }
// The CURRENT SEGMENT's right endpoint — not a contour-level concept despite the name's
// shape; it is the whole contour's terminal Y only when paired with onFinalSegment() (see
// there). Named for what it returns, not for its one call site's use of it.
double segmentEndValue() const { return y1_; }
// `phase` is normalized position over the contour's whole span, [0,1]; out-of-range clamps
// to the terminal values (a note past its span holds the contour's last level).
double eval(double phase) {
const double x = (phase <= 0.0) ? kCurveXMin
: (phase >= 1.0) ? kCurveXMax
: kCurveXMin + phase * (kCurveXMax - kCurveXMin);
if (x <= x0_ && seg_ == 0) return y0_;
if (x >= x1_ && seg_ + 2 == n_) return y1_;
// x <= x0_ (not just <): landing exactly on the cached segment's LEFT edge normally
// reproduces y0_ either way, but at a duplicate-X step (coincident knots with
// DIFFERENT Y) the cached segment may be the LATER of the two — re-locate so a query
// sitting exactly on the shared X always resolves through locate()'s tie-break, which
// agrees with the cold VelocityCurve::eval's first-containing-segment rule.
if (x <= x0_ || x > x1_) locate(x);
if (span_ <= 0.0) return y1_; // coincident-X knots: a step, no interior to blend
return hermiteAt(y0_, y1_, span_, mA_, mB_, (x - x0_) / span_);
}
private:
// The common case is the next segment (a monotone read walking forward); anything else is a
// binary search over the X-ordered array.
void locate(double x) {
if (x > x1_ && seg_ + 2 < n_ && x <= pts_[seg_ + 2].velocity) { select(seg_ + 1); return; }
// Leftmost segment containing x: smallest lo with pts_[lo+1].velocity >= x. At
// coincident-X knots (a drawn step) this picks the FIRST segment ending at the shared X,
// matching VelocityCurve::eval's cold linear walk — the two readers must agree here or a
// backwards/jumping read can return a different knot's Y than a forward one would.
std::size_t lo = 0, hi = n_ - 2;
while (lo < hi) {
const std::size_t mid = lo + (hi - lo) / 2;
if (pts_[mid + 1].velocity < x) lo = mid + 1; else hi = mid;
}
select(lo);
}
void select(std::size_t i) {
seg_ = i;
x0_ = pts_[i].velocity;
x1_ = pts_[i + 1].velocity;
y0_ = pts_[i].value;
y1_ = pts_[i + 1].value;
span_ = x1_ - x0_;
const SegmentTangents t =
segmentTangents(pts_, n_, i, span_ > 0.0 ? (y1_ - y0_) / span_ : 0.0, span_);
mA_ = t.mA;
mB_ = t.mB;
}
const VelocityPoint* pts_ = nullptr;
std::size_t n_ = 0;
std::size_t seg_ = 0;
double x0_ = 0.0, x1_ = 0.0, y0_ = 0.0, y1_ = 0.0, span_ = 0.0, mA_ = 0.0, mB_ = 0.0;
};
} // namespace reasampler::instrument::engine
+192 -32
View File
@@ -18,7 +18,8 @@ void Voice::presizePreserveShifters(std::int64_t windowFrames) {
primeBuf_.assign(windowFrames > 1 ? static_cast<std::size_t>(windowFrames) : 0, 0.0f);
}
void Voice::start(int note, int velocity, const SampleData& sample, bool declickTakeover) {
void Voice::start(int note, int velocity, const SampleData& sample, bool declickTakeover,
double stretchRate, double keyTrack, double lengthFraction) {
// Before any state reset, record the pre-cut reference (last rendered output) and mark
// the compensation pending iff this start is a takeover/steal of a sounding voice and the
// caller opted in. The ramp is seeded on the first frame rendered after the restart, from
@@ -49,14 +50,33 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
// Velocity->amp mapped once at note-on; the per-frame render just multiplies the cached
// velocityGain_.
velocityGain_ = sample.velocityCurve.eval(static_cast<double>(velocity));
// Feeds both engines through baseRatio_ (Varispeed read-rate bias and Preserve shift
// amount both derive from it below).
baseRatio_ = keyTrackedRatio(note, sample.rootNote, sample.keyTrack);
sample_ = &sample;
const PlayParams& p = sample.play;
// Velocity->pitch is fixed for the note's lifetime, so it folds into baseRatio_ rather than
// costing a per-frame multiply. Feeds both engines through baseRatio_ (Varispeed read-rate
// bias and Preserve shift amount both derive from it below).
velPitchRatio_ = velocityPitchRatio(p.pitchVelocityCurve, velocity);
pitchOffsetRatio_ = semitoneRatio(p.pitchOffsetSemitones);
playMode_ = p.playMode;
pitchEngine_ = p.pitchEngine;
// THE clamp for both engines — the taper's ends are these bounds, so a knob can never ask for
// a rate this moves. Clamped once here so the read head's increment and the feed cursor's
// debt accumulate the SAME value: they must stay exactly one window apart for the note's
// whole life.
stretchRate_ = instrument::engine::clampStretchRate(stretchRate);
// Keyed on the read path this note will ACTUALLY take, which is not the same question as
// the stored engine: advanceFrame runs the Preserve branch only while the shifters are
// configured, and a Preserve voice whose shifters were never sized falls back to the
// varispeed read. Rate has to reach the increment there too, or that fallback would ignore
// the control outright — the predicate is spelled the same way advanceFrame spells it.
preserveRead_ = (pitchEngine_ == PitchEngine::Preserve) && shiftL_.configured();
rateRatio_ = preserveRead_ ? 1.0 : stretchRate_;
keyTrack_ = (keyTrack < 0.0) ? sample.keyTrack : keyTrack;
recomputeBaseRatio();
// pitchOffsetRatio_ is a power of 2 and never zero, so this inverse is well-defined — and at
// Pitch 0 it is a division by exactly 1.0.
pitchSpanBaseRate_ = baseRatio_ / pitchOffsetRatio_;
// Clamp into [0, frames): a start at or past the end degrades to 0 (play from the top)
// rather than starting a voice already off the end.
@@ -64,52 +84,102 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
std::int64_t start = sample.startFrame;
if (start < 0 || start >= frameCount) start = 0;
readPos_ = static_cast<double>(start);
startFrame_ = start; // Trigger fade offset origin (readPos - startFrame = span offset)
startFrame_ = start; // the span-offset origin: readPos - startFrame
// The one fold of the stored span + crossfade into what the read path wraps on.
loop_ = instrument::engine::loop::resolveLoop(sample.loop, sample.loopCrossfadeFrames,
frameCount, playMode_ == PlayMode::Gate);
// Bind whichever EGs are drawn. Rebound on EVERY note-on rather than cached: a reload hands
// the engine a fresh SampleData, so a stale pointer into the previous one is the bug this
// avoids. A Staged EG clears its cursor, which is what keeps the per-sample path off the
// spline branch entirely.
splineScale_ = frameCount > 0 ? 1.0 / static_cast<double>(frameCount) : 0.0;
if (p.ampSpline.mode == EnvMode::Spline) ampSplineCur_.bind(p.ampSpline.contour);
else ampSplineCur_.clear();
if (p.pitchEnv.enabled && p.pitchSpline.mode == EnvMode::Spline) {
pitchSplineCur_.bind(p.pitchSpline.contour);
pitchSplineDepth_ = p.pitchEnv.peakSemitones;
} else {
pitchSplineCur_.clear();
pitchSplineDepth_ = 0.0;
}
if (p.filter.enabled && p.filterSpline.mode == EnvMode::Spline) {
filterSplineCur_.bind(p.filterSpline.contour);
} else {
filterSplineCur_.clear();
}
// Amplitude envelope: Gate = AHDSR (all five fields read from play.adsr, resolved to
// frames from stored seconds at load time); Trigger = the time-boxed fade-in/out over the
// % play length.
// frames from stored seconds at load time); Trigger = the staged AHD over the % play span.
const std::int64_t postStart = frameCount - start; // >= 1 (start clamped < frameCount)
std::int64_t trigSpan = 0;
if (playMode_ == PlayMode::Gate) {
env_.configure(p.adsr);
env_.noteOn();
playEnd_ = 0; // unused in Gate
} else {
// Trigger: play [start, playEnd) where
// playEnd = start + round(lengthFraction*(frames-start)).
double frac = p.trigger.lengthFraction;
if (frac <= 0.0) frac = 0.0; // %=0 -> zero play length (finishes immediately)
// Trigger: play [start, playEnd) where playEnd = start + round(frac*(frames-start)) —
// map/trigger_seam.h's formula, evaluated inline because the engine does not depend on
// map/. The caller's value is ALREADY spline-folded (foldLive does it); the snapshot
// fallback folds here, because a stored-but-inert %-knob must not shorten the span.
double frac = (lengthFraction < 0.0) ? effectiveLengthFraction(p) : lengthFraction;
if (!(frac > 0.0)) frac = 0.0; // %=0 (or a corrupt NaN) -> finishes immediately
if (frac > 1.0) frac = 1.0;
const std::int64_t span = frameCount - start; // >= 1 (start clamped < frameCount)
std::int64_t playLen = static_cast<std::int64_t>(
static_cast<double>(span) * frac + 0.5); // round
static_cast<double>(postStart) * frac + 0.5); // round
if (playLen < 0) playLen = 0;
if (playLen > span) playLen = span;
if (playLen > postStart) playLen = postStart;
playEnd_ = start + playLen;
trigEnv_.configure(playLen, p.trigger.fadeInFrames, p.trigger.fadeOutFrames,
kDefaultFadeCurve);
trigSpan = playLen;
ampAhd_.configure(playLen, rateFittedAhd(p.trigAhd));
}
pitchEnv_.configure(p.pitchEnv);
// The pitch AHD's Hold fraction is taken against the whole playable span, so its three
// stages lay 1:1 over the waveform from the start point. The source->output conversion, and
// why it is only first-order, are pitchEnvSpanFrames' own (voice.h).
pitchEnv_.configure(pitchEnvSpanFrames(), p.pitchEnv);
pitchEnv_.noteOn();
// A restart lands every live glide back on the new note's own values, at a step derived
// from this sample's rate rather than any assumed one.
filterRamping_ = false;
const double rampStep = instrument::engine::liveRampStep(
static_cast<double>(sample.sampleRate));
rBaseCutoff_.step = rampStep;
rModAmount_.step = rampStep;
rResonance_.step = rampStep;
rMorph_.step = rampStep;
rDrive_.step = rampStep;
// Filter: reset() clears integrator state for the new note (prepare() preserves it —
// voice_filter.h / filter/CLAUDE.md). Velocity maps through the curve once here, off the
// per-frame path, exactly as the amp's velocityGain_ does.
filterOn_ = p.filter.enabled;
if (filterOn_) {
filterSettings_ = p.filter.settings;
filterCutoffNorm_ = static_cast<double>(p.filter.settings.cutoffNorm);
filterModAmount_ = p.filter.modAmount;
filterKeyTrack_ = p.filter.keyTrack;
filterVelOffset_ =
p.filter.velAmount * p.filter.velocityCurve.eval(static_cast<double>(velocity));
filterVelCurve_ = p.filter.velocityCurve.eval(static_cast<double>(velocity));
filterVelOffset_ = p.filter.velAmount * filterVelCurve_;
filterRate_ = static_cast<double>(sample.sampleRate);
filterEnv_.configure(p.filter.env);
filterEnv_.noteOn();
rModAmount_.set(p.filter.modAmount);
rResonance_.set(static_cast<double>(p.filter.settings.resonanceNorm));
rMorph_.set(static_cast<double>(p.filter.settings.morphNorm));
rDrive_.set(static_cast<double>(p.filter.settings.driveNorm));
if (playMode_ == PlayMode::Gate) {
filterEnv_.configure(p.filter.env);
filterEnv_.noteOn();
} else {
filterAhd_.configure(trigSpan, rateFittedAhd(p.filter.trigEnv));
}
filter_.reset();
updateFilterCutoffBase(note);
// The note's ONE full solve — Q, morph and drive are constants for its lifetime, so
// every later re-solve is the cheap cutoff-only path. A modulated voice supersedes this
// cutoff in tickFilterCutoff on its first frame, before any sample reaches the kernel.
// The note's ONE full solve — Q, morph and drive are constants for its lifetime unless
// a live move glides them, so every later re-solve is the cheap cutoff-only path. A
// modulated voice supersedes this cutoff in tickFilterCutoff on its first frame,
// before any sample reaches the kernel.
instrument::engine::filter::FilterSettings s = p.filter.settings;
s.cutoffNorm = filterBaseCutoff_;
filter_.prepare(s, filterRate_);
@@ -128,9 +198,7 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
// no per-frame shifter cost.
if (pitchEngine_ == PitchEngine::Preserve && shiftL_.configured()) {
const std::int64_t w = shiftL_.window();
const bool loopWrap = sustainLoopUsable();
const SampleLoop& loop = sample.loop;
const std::int64_t loopLen = loopWrap ? (loop.end - loop.start) : 0;
const bool loopWrap = loop_.active;
const bool stereoSample = sample.channelCount() == 2 && shiftR_.configured();
// The prime may only carry playable source. The per-frame feed stops at feedBound
// (playEnd_ for a bounded Trigger span, the sample end for Gate) and freezes the
@@ -155,12 +223,17 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
std::int64_t q = start;
for (std::int64_t i = 0; i < primeCount; ++i) {
if (loopWrap) {
while (q >= loop.end) q -= loopLen;
while (q >= loop_.end) q -= loop_.length;
}
// q < frameCount holds by construction on the non-loop path (primeCount is
// bounded); the guard stays as a belt for the loop-wrap walk.
// bounded); the guard stays as a belt for the loop-wrap walk. The prime runs
// the SAME crossfade the per-frame feed does — a ring primed with an un-faded
// seam would put the click back one window into the note.
primeBuf_[static_cast<std::size_t>(i)] =
(q < frameCount) ? pcmCh[static_cast<std::size_t>(q)] : 0.0f;
(q < frameCount)
? crossfadedSource(pcmCh, loop_, q, crossfadeWeight(loop_,
static_cast<double>(q)))
: 0.0f;
++q;
}
(ch == 0 ? shiftL_ : shiftR_).prime(primeBuf_.data(), primeCount);
@@ -168,7 +241,15 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
}
// Per-frame feed continues at `p` (the feed bound when the prime exhausted the
// playable span).
feedPos_ = p;
stretch_.start(p);
shiftL_.setFeedRate(stretchRate_);
shiftR_.setFeedRate(stretchRate_);
// Pitch-synchronous splices: the period was detected once at load (period_detect,
// which this library deliberately does not link — the loader hands the answer down on
// SampleData). 0 restores the fixed-window geometry, so a capture with no single
// period plays exactly as it always did.
shiftL_.setSourcePeriod(sample.sourcePeriodFrames);
shiftR_.setSourcePeriod(sample.sourcePeriodFrames);
if (!loopWrap && primeCount < w) {
// Sub-window playable span: the source is already exhausted at prime time.
shiftL_.freezeTail();
@@ -178,6 +259,77 @@ void Voice::start(int note, int velocity, const SampleData& sample, bool declick
ratio_ = baseRatio_; // seeded; advanceFrame recomputes per frame under the active engine.
}
void Voice::applyLive(const instrument::engine::LiveValues& live, bool snap) {
// Each envelope applies only the shape its play mode selected at note-on; the block
// carries both so the mode never changes what is published.
//
// A fresh note and a sounding one take DIFFERENT envelope entry points, never one with a
// flag: a voice that has rendered nothing has no phase to hold and nothing to be
// continuous with, and the mid-stage rule misreads its stage-0 position (envelopes.h).
//
// live.playRate is deliberately NOT read on either path: Rate is the note-on-latched class,
// delivered as start()'s argument by VoiceEngine::startVoice (live_params.h owns why). The
// latched stretchRate_ is what stageFitRate carries into every conversion below, so a
// stage-time move mid-note lands in this note's own rate domain rather than resetting it.
const bool gate = (playMode_ == PlayMode::Gate);
// The baseline Pitch offset IS live, under both engines: Varispeed picks the new baseRatio_
// up as one more factor of next frame's read increment, Preserve as the shifter's transpose.
// Applied BEFORE the envelopes below, because under Varispeed it is a factor of the read rate
// both of them are fitted against — a stale offset here would fit them to the previous move.
pitchOffsetRatio_ = semitoneRatio(live.pitchOffsetSemitones);
recomputeBaseRatio();
if (snap) {
if (gate) env_.snapLive(live.adsr);
else ampAhd_.snapLive(rateFittedAhd(live.ampAhd));
pitchEnv_.snapLive(pitchEnvSpanFrames(), live.pitchEnv);
} else {
if (gate) env_.applyLive(live.adsr);
else ampAhd_.applyLive(sourceOffset(), rateFittedAhd(live.ampAhd));
pitchEnv_.applyLive(pitchEnvSpanFrames(), live.pitchEnv);
}
// The pitch DEPTH knob stays live under a spline (core/instrument/CLAUDE.md), but
// pitchSplineDepth_ is a plain member latched at note-on — unlike filter's modAmount_,
// which already glides through rModAmount_'s live ramp regardless of spline state (below),
// this is the one place a live pitch-depth move must be re-applied by hand. Only meaningful
// while pitchSplineCur_ is bound; harmless (and cheap) to set otherwise.
pitchSplineDepth_ = live.pitchEnv.peakSemitones;
if (!filterOn_) return; // filter enable is a discrete toggle: it travels by reload
if (snap) {
if (gate) filterEnv_.snapLive(live.filterEnv);
else filterAhd_.snapLive(rateFittedAhd(live.filterAhd));
} else {
if (gate) filterEnv_.applyLive(live.filterEnv);
else filterAhd_.applyLive(sourceOffset(), rateFittedAhd(live.filterAhd));
}
filterCutoffNorm_ = static_cast<double>(live.filterSettings.cutoffNorm);
filterKeyTrack_ = live.filterKeyTrack;
// The note's curve value stays latched; only the depth over it is live. Both this and the
// key-track depth land in the base cutoff, so they glide through rBaseCutoff_ below.
filterVelOffset_ = live.filterVelAmount * filterVelCurve_;
filterSettings_.morphLaw = live.filterSettings.morphLaw;
const double baseTarget = filterCutoffBaseTarget(note_);
if (snap) {
rBaseCutoff_.set(baseTarget);
rModAmount_.set(live.filterModAmount);
rResonance_.set(static_cast<double>(live.filterSettings.resonanceNorm));
rMorph_.set(static_cast<double>(live.filterSettings.morphNorm));
rDrive_.set(static_cast<double>(live.filterSettings.driveNorm));
filterBaseCutoff_ = static_cast<float>(baseTarget);
filterModAmount_ = live.filterModAmount;
filterRamping_ = false;
prepareFilterFromRamps();
return;
}
rBaseCutoff_.aim(baseTarget);
rModAmount_.aim(live.filterModAmount);
rResonance_.aim(static_cast<double>(live.filterSettings.resonanceNorm));
rMorph_.aim(static_cast<double>(live.filterSettings.morphNorm));
rDrive_.aim(static_cast<double>(live.filterSettings.driveNorm));
filterRamping_ = rBaseCutoff_.moving() || rModAmount_.moving() || rResonance_.moving() ||
rMorph_.moving() || rDrive_.moving();
}
void Voice::retune(int note) {
// Mono legato takeover: move the pitch, touch NOTHING else — the amplitude envelope keeps
// running (no re-attack), the read head keeps its position, the shifter keeps its ring
@@ -186,10 +338,18 @@ void Voice::retune(int note) {
// legato phrase is one gesture, one strike (classic mono-synth behavior).
if (!active_ || sample_ == nullptr) return;
note_ = note;
baseRatio_ = keyTrackedRatio(note, sample_->rootNote, sample_->keyTrack);
// Changes baseRatio_ without re-converting pitchEnv_'s already-configured span
// (pitchEnvSpanFrames, whose base rate this deliberately does not move), so a slide leaves
// that envelope on the first note's domain — consistent with "touch nothing else," but the
// drift lives here.
// The velocity->pitch factor rides through the slide unchanged, matching velocityGain_ —
// one gesture, one strike. Rate and the Pitch offset ride through too: only the note moved.
recomputeBaseRatio();
// Filter key-tracking follows the pitch: it is a function of the note, so a slide moves it
// too. The velocity offset deliberately stays the first note's, matching velocityGain_.
if (filterOn_) updateFilterCutoffBase(note);
// stretchRate_ (Preserve's duration control) is untouched here too — it is a note-on latch
// like velocityGain_, not a per-note property to re-resolve on a legato slide.
}
void Voice::release() {
+388 -78
View File
@@ -15,16 +15,24 @@
#include "core/instrument/engine/envelopes.h"
#include "core/instrument/engine/filter/filter_params.h"
#include "core/instrument/engine/filter/voice_filter.h"
#include "core/instrument/engine/live_params.h"
#include "core/instrument/engine/loop/loop_span.h"
#include "core/instrument/engine/pitch_shift.h"
#include "core/instrument/engine/play_params.h"
#include "core/instrument/engine/time_stretch.h"
#include "core/instrument/engine/velocity_curve.h"
namespace reasampler {
using audio::AudioSample;
using instrument::engine::PitchShifter;
using instrument::engine::SplineCursor;
using instrument::engine::VelocityCurve;
using instrument::engine::VelocityPoint;
using instrument::engine::loop::ResolvedLoop;
using instrument::engine::loop::crossfadeWeight;
using instrument::engine::loop::crossfadedSource;
using instrument::engine::loop::lerpSource;
// 2^((note - rootNote) / 12). note == rootNote -> 1.0. Pure equal temperament; no
// reference-frequency needed.
@@ -37,11 +45,27 @@ inline double pitchRatio(int note, int rootNote) {
// ((note-root)*1.0 is exact in IEEE-754 for an integer-valued double, feeding the same
// std::pow call); 0.0 means every key plays the root pitch; 2.0 doubles the tracking rate.
// At the root note the offset is 0 regardless of keyTrack.
// "Not supplied" for Voice::start's two snapshot-defaulted note-on latches; see start().
inline constexpr double kLatchFromSnapshot = -1.0;
inline double keyTrackedRatio(int note, int rootNote, double keyTrack) {
const double semis = static_cast<double>(note - rootNote) * keyTrack;
return std::pow(2.0, semis / 12.0);
}
// 2^(semitones/12). Exactly 1.0 at zero — and it SKIPS the pow there, so an unset offset
// transposes nothing and costs nothing.
inline double semitoneRatio(double semitones) {
return (semitones == 0.0) ? 1.0 : std::pow(2.0, semitones / 12.0);
}
// The velocity->pitch transpose, which the voice folds into baseRatio_ once at note-on. A curve
// flat at 0 — the default — yields EXACTLY 1.0 at every velocity.
inline double velocityPitchRatio(const VelocityCurve& curve, int velocity) {
return semitoneRatio(curve.eval(static_cast<double>(velocity)) *
kVelocityPitchRangeSemitones);
}
// One octave expressed in the cutoff control's normalized domain, read out of the filter
// module's OWN inverse rather than re-derived from its endpoints — the log law belongs to
// filter_params, and a second copy here could drift from it. Evaluated at note-on only.
@@ -59,13 +83,24 @@ inline double filterNormPerOctave() {
// kDeclickDecay/frame — so the boundary frame reproduces the old level exactly regardless of
// the new envelope's first value, and the residue fades to the -80 dB floor in a few ms.
// An earlier revision gated the compensation by (1 - newAmp): any restart whose new
// amplitude was instantly ~1 (Trigger with no fade-in, zero-attack Gate) got zero
// amplitude was instantly ~1 (a zero-attack Trigger or Gate) got zero
// compensation and kept the full click — the difference-seed has no such hole. Off by
// default so the bare core stays byte-identical to the pre-fix engine; the processor
// shell opts in.
inline constexpr double kDeclickDecay = 0.95; // per-frame decay of the compensation
inline constexpr double kDeclickFloor = 1e-4; // below this the ramp is done (~ -80 dB)
// How many frames the ramp emits before the weight drops under the floor. Counted the way
// advanceFrame runs it — emit, decay, test — rather than solved in closed form, so the two
// can never disagree. RATE-INDEPENDENT: the decay is per frame, not per second, so an offline
// pass at any rate pads by the same count.
inline constexpr std::int64_t declickRampFrames() {
std::int64_t n = 0;
for (double w = 1.0; w >= kDeclickFloor; w *= kDeclickDecay) ++n;
return n;
}
inline constexpr std::int64_t kDeclickFrames = declickRampFrames();
// A single voice: one active note playing the loaded capture, repitched and enveloped.
// Reads the sample by fractional frame position with linear interpolation, advancing by the
// pitch ratio; loops the sustain region for held notes past the loop end.
@@ -82,7 +117,26 @@ public:
// and this voice is currently active (a takeover/steal restart, not a fresh start), arms
// the difference-seeded declick compensation on the first frame after the restart (see
// kDeclickDecay above). A fresh start never declicks.
void start(int note, int velocity, const SampleData& sample, bool declickTakeover = false);
//
// `stretchRate` is the playback rate — source frames consumed per output frame, clamped to
// [kStretchRateMin, kStretchRateMax]. It is a note-on latch by construction (an argument, not
// a member set separately) because the loop fold and the contour scale it composes with are
// both note-on folds. Under Preserve it is the stretcher's feed rate and duration alone moves;
// under Varispeed it folds into the read increment beside key-tracking, so pitch moves with
// it. 1.0 is the bare engine, bit for bit, in both. Defaulted so a caller with no live block
// to consult gets exactly that; VoiceEngine::startVoice is what resolves the real value —
// sample.play.playRate is NOT read here, because the published block outranks the snapshot's
// possibly-stale copy of it.
//
// `keyTrack` and `lengthFraction` are the other two members of stretchRate's note-on-latched
// class and arrive the same way, for the same structural reason. Negative = not supplied,
// which reads the snapshot's own value (sample.keyTrack, effectiveLengthFraction(play)) —
// both are non-negative by domain, so the sentinel can never collide with a real one.
// VoiceEngine::startVoice always supplies them, resolved from the published block when there
// is one; the sentinel is for a caller that has no block to consult.
void start(int note, int velocity, const SampleData& sample, bool declickTakeover = false,
double stretchRate = 1.0, double keyTrack = kLatchFromSnapshot,
double lengthFraction = kLatchFromSnapshot);
// Mono legato takeover: re-pitch this active voice to `note` without touching the
// amplitude envelope, read position, or shifter state — pitch moves, no re-attack. Both
@@ -115,6 +169,16 @@ public:
// meaningful while active().
PitchEngine pitchEngine() const { return pitchEngine_; }
// Applies the live-parameter block to a voice that is already sounding (or, with `snap`,
// to one just started). Called at BLOCK boundaries by VoiceEngine — never per frame — so
// the per-sample shape is unchanged; every continuous control glides toward its new value
// from here rather than jumping to it. `snap` takes the values outright — glides AND
// envelopes: a fresh note has nothing to glide from, and its copy may predate the edit.
//
// What is NOT here is the point: velocity and its curve result, the note number and the
// pitch ratio, and the decoded PCM stay latched at note-on.
void applyLive(const instrument::engine::LiveValues& live, bool snap);
// Pre-sizes this voice's Preserve pitch shifters (both channels) to `windowFrames`, off
// the audio thread (allocates; also sizes the prime scratch buffer), so start() — which
// runs inside process() — never allocates. <= 1 leaves the shifters pass-through.
@@ -140,36 +204,105 @@ public:
}
private:
// True when the sustain loop applies: Gate mode with a valid, non-empty loop inside the
// sample (Trigger one-shots never loop). Single source of truth for the wrap rule shared
// by the output anchor, the Preserve feed, and the start()-time ring prime.
bool sustainLoopUsable() const {
if (sample_ == nullptr || playMode_ != PlayMode::Gate) return false;
const SampleLoop& loop = sample_->loop;
return loop.hasLoop && loop.end > loop.start && loop.start >= 0 &&
loop.end <= static_cast<std::int64_t>(sample_->frames.size());
// THE fold of every pitch factor that is constant for the note into one number, so
// advanceFrame's read increment stays the single multiply `baseRatio_ * envFactor` it has
// always been: key-tracked repitch, the velocity->pitch transpose, the baseline Pitch offset,
// and the Rate ratio — which start() zeroes out of this product when the note is running the
// Preserve read, since Rate feeds stretch_ (duration) there and must never reach the
// shifter's transpose. Cold: note-on, legato retune, and a live block, never per frame.
void recomputeBaseRatio() {
if (sample_ == nullptr) return;
baseRatio_ = keyTrackedRatio(note_, sample_->rootNote, keyTrack_) *
velPitchRatio_ * pitchOffsetRatio_ * rateRatio_;
}
// This frame's amplitude in [0,1] from the active envelope. Gate: AHDSR ticks once per
// output frame (envelope time is wall-clock, independent of read rate). Trigger: fade
// shape is evaluated at the source offset (readPos - startFrame) so fades anchor to
// source frames regardless of pitch engine. Sets amplitudeDone_ on finish so
// The rate the read head consumes SOURCE at, counting only the factors whose stage-time
// coupling is compensated. Under Preserve that is the stretch rate alone — the Pitch offset
// transposes inside the shifter and never touches the read. Under Varispeed both Rate and
// Pitch are factors of the read increment and both are compensated: they are two views of one
// multiply, so the "30 ms is 30 ms" rule binds them identically. Key-tracking and the
// velocity->pitch transpose are deliberately LEFT OUT — those predate Rate, are shipped
// sounds, and compensating them would move every note off the root.
double stageFitRate() const {
return preserveRead_ ? stretchRate_ : stretchRate_ * pitchOffsetRatio_;
}
// A staged AHD's wall-clock stage frames converted into the SOURCE-offset domain the
// sustain-less envelopes are evaluated in (sourceOffset()). The read stretches the source
// span those envelopes are fitted over, but a 30 ms attack is 30 ms at any rate —
// multiplying by the read rate is exactly that conversion. A fit of exactly 1.0 (Rate 100 %,
// Pitch 0 st) returns the argument untouched, which is what keeps the unity render
// bit-identical.
AhdParams rateFittedAhd(const AhdParams& a) const {
const double fit = stageFitRate();
if (fit == 1.0) return a;
AhdParams out = a;
out.attackFrames =
static_cast<std::int64_t>(static_cast<double>(a.attackFrames) * fit + 0.5);
out.decayFrames =
static_cast<std::int64_t>(static_cast<double>(a.decayFrames) * fit + 0.5);
return out;
}
// The pitch AHD's span. That envelope counts OUTPUT frames while its Hold fraction is taken
// against the playable SOURCE span, so the span converts by the rate the read head consumes
// source at. Divides by that alone though the Varispeed read rate is really baseRatio_ x
// envFactor: a deep pitch envelope makes it a first-order approximation, not exact.
//
// Shared by note-on and every live re-application, so a live Pitch move re-fits the envelope
// rather than leaving it on the offset the note started at. Only that live factor is
// re-read — pitchSpanBaseRate_ has it divided out — which is what leaves a legato retune's
// documented drift (retune) exactly where it was.
std::int64_t pitchEnvSpanFrames() const {
if (sample_ == nullptr) return 0;
const double postStart = static_cast<double>(
static_cast<std::int64_t>(sample_->frames.size()) - startFrame_);
const double readRate =
preserveRead_ ? stretchRate_ : pitchSpanBaseRate_ * pitchOffsetRatio_;
const double span = (readRate > 0.0) ? postStart / readRate : postStart;
return static_cast<std::int64_t>(span + 0.5);
}
// The read head as a fraction of the whole sample — the domain every spline EG is a pure
// function of. Zero-length sample leaves splineScale_ at 0, which parks every contour on
// its opening value.
double splinePhase() const { return readPos_ * splineScale_; }
// This frame's amplitude in [0,1] from the active envelope. Spline: the drawn contour read
// at the normalized position (one cached-segment compare per frame). Gate: AHDSR ticks once
// per output frame (envelope time is wall-clock, independent of read rate). Trigger: the AHD
// is evaluated at the source offset (readPos - startFrame), which is why its stage frames are
// fitted to the read rate at configure time (rateFittedAhd). Sets amplitudeDone_ on finish so
// advanceFrame frees the voice.
double tickAmplitude() {
double amp;
if (playMode_ == PlayMode::Gate) {
// playMode_ is Trigger whenever a spline is genuinely reachable (resolvePlay forces it —
// splineActive, play_params.h); the guard is a pure-core defense against a hand-built
// SampleData pairing Gate with an amp spline, which would otherwise bypass env_
// entirely — release() then has no envelope to end, and an active sustain loop rings
// forever.
if (ampSplineCur_.active() && playMode_ == PlayMode::Trigger) {
// Early-free at a genuine permanent terminus (the spline analogue of a staged AHD's
// finished()) — onFinalSegment()/segmentEndValue()'s own doc comments own the why.
amp = ampSplineCur_.eval(splinePhase());
if (amp == 0.0 && ampSplineCur_.onFinalSegment() &&
ampSplineCur_.segmentEndValue() == 0.0) {
amplitudeDone_ = true;
}
} else if (playMode_ == PlayMode::Gate) {
amp = env_.tick();
if (env_.finished()) amplitudeDone_ = true;
} else {
// Anchored to the source offset so fades land on the same source frames under
// either engine's read rate. The voice also frees on readPos_ >= playEnd_ in
// advanceFrame; finished() here is the belt to that suspenders.
amp = trigEnv_.amplitudeAt(readPos_ - static_cast<double>(startFrame_));
if (trigEnv_.finished()) amplitudeDone_ = true;
amp = ampAhd_.amplitudeAt(sourceOffset());
if (ampAhd_.finished()) amplitudeDone_ = true;
}
return amp;
}
// Frames into the Trigger play span at the current read head — the domain both
// sustain-less envelopes are evaluated over.
double sourceOffset() const { return readPos_ - static_cast<double>(startFrame_); }
// Advances the filter envelope and re-solves the corner from the modulated cutoff. The
// solve is UNQUANTIZED: the corner tracks the envelope continuously, so a sweep glides
// rather than staircasing. State preservation across the solve is voice_filter's own
@@ -184,8 +317,15 @@ private:
// through both so a moved base always re-solves.
void tickFilterCutoff() {
if (filterModAmount_ == 0.0 && filterSolved_) return;
double cut = static_cast<double>(filterBaseCutoff_) +
filterModAmount_ * filterEnv_.tick();
// The filter envelope takes the amp's shape under the active mode — AHDSR in Gate,
// the source-offset AHD in Trigger. playMode_ is fixed for the note's lifetime, so the
// branch is perfectly predicted.
const double envOut = filterSplineCur_.active()
? filterSplineCur_.eval(splinePhase())
: ((playMode_ == PlayMode::Gate)
? filterEnv_.tick()
: filterAhd_.amplitudeAt(sourceOffset()));
double cut = static_cast<double>(filterBaseCutoff_) + filterModAmount_ * envOut;
if (cut < 0.0) cut = 0.0;
if (cut > 1.0) cut = 1.0;
const float cutNorm = static_cast<float>(cut);
@@ -196,9 +336,10 @@ private:
}
// The cutoff position before the envelope: the stored knob position plus this note's
// velocity offset and key-tracking. Recomputed at note-on and at a legato retune (both
// move the note), never per frame.
void updateFilterCutoffBase(int note) {
// velocity offset and key-tracking. Evaluated at note-on, at a legato retune (both move
// the note), and when a live move changes the knob position or the key-track depth —
// never per frame.
double filterCutoffBaseTarget(int note) const {
double base = filterCutoffNorm_ + filterVelOffset_;
if (filterKeyTrack_ != 0.0 && sample_ != nullptr) {
base += filterKeyTrack_ *
@@ -207,10 +348,52 @@ private:
}
if (base < 0.0) base = 0.0;
if (base > 1.0) base = 1.0;
return base;
}
// Takes the base outright (no glide) — a note-on or a retune is a new note position, not a
// knob move, so there is nothing to glide from.
void updateFilterCutoffBase(int note) {
const double base = filterCutoffBaseTarget(note);
rBaseCutoff_.set(base);
filterBaseCutoff_ = static_cast<float>(base);
filterSolved_ = false; // forces the next frame to solve
}
// The full solve, from the tone-control ramps' current values, at the current base cutoff —
// the same shape start() performs, and it leaves the same solved-cutoff bookkeeping behind
// so an unmoved live block reproduces start()'s state exactly. State is preserved across
// prepare() by contract (voice_filter.h), which is what makes a live tone move glide
// rather than click.
void prepareFilterFromRamps() {
filterSettings_.resonanceNorm = static_cast<float>(rResonance_.value);
filterSettings_.morphNorm = static_cast<float>(rMorph_.value);
filterSettings_.driveNorm = static_cast<float>(rDrive_.value);
filterSettings_.cutoffNorm = filterBaseCutoff_;
filter_.prepare(filterSettings_, filterRate_);
filterSolvedCutoff_ = filterBaseCutoff_;
filterSolved_ = true;
}
// Advances the five live filter-control glides by one frame. Q, morph and drive are
// prepare()-cadence constants, so a move on any of them costs the full solve while the
// glide runs (~20 ms) and nothing once it lands; the base cutoff and the mod depth feed
// tickFilterCutoff's own cheap cutoff-only solve instead.
void tickFilterRamps() {
bool tone = false;
if (rResonance_.tick()) tone = true;
if (rMorph_.tick()) tone = true;
if (rDrive_.tick()) tone = true;
if (rBaseCutoff_.tick()) {
filterBaseCutoff_ = static_cast<float>(rBaseCutoff_.value);
filterSolved_ = false;
}
if (rModAmount_.tick()) filterModAmount_ = rModAmount_.value;
if (tone) prepareFilterFromRamps();
filterRamping_ = rResonance_.moving() || rMorph_.moving() || rDrive_.moving() ||
rBaseCutoff_.moving() || rModAmount_.moving();
}
// Seeds the takeover compensation on the first frame after a restart: the ramp is the
// actual discontinuity — (pre-cut reference - the new voice's raw output this frame) —
// applied ungated so the boundary frame reproduces the old level exactly.
@@ -230,6 +413,22 @@ private:
declickRefR_ > kDeclickFloor || declickRefR_ < -kDeclickFloor);
}
// Rings the voice's last rendered output out instead of hard-cutting it when the read head
// reaches the end of its span, on the PRESERVE path only. Varispeed's final sample is real
// source content at its natural end and its stop is left byte-identical; Preserve's is
// recycled synthetic tail (freezeTail stops the writer a full window before the read head
// arrives), whose level bears no relation to the source's own ending — cutting it at
// whatever amplitude the splice machinery happens to be at is the end-of-sample click.
// Reuses the takeover blend so the boundary frame reproduces the last level exactly.
void seedTerminalDeclick() {
if (pitchEngine_ != PitchEngine::Preserve) return;
declickRefL_ = (lastOutL_ > 1.0) ? 1.0 : (lastOutL_ < -1.0) ? -1.0 : lastOutL_;
declickRefR_ = (lastOutR_ > 1.0) ? 1.0 : (lastOutR_ < -1.0) ? -1.0 : lastOutR_;
declickWeight_ = 1.0;
declickActive_ = (declickRefL_ > kDeclickFloor || declickRefL_ < -kDeclickFloor ||
declickRefR_ > kDeclickFloor || declickRefR_ < -kDeclickFloor);
}
// Shared read/advance for both render paths: computes the interpolated per-channel
// value(s) at the current read head, ticks the amplitude + pitch envelopes once, applies
// the pitch engine, advances the head, and latches idle on exhaustion. `stereo` selects
@@ -249,14 +448,13 @@ private:
const bool haveR = stereo && sample_->channelCount() == 2;
const std::vector<AudioSample>& pcmR = haveR ? sample_->framesR : pcm;
// Loop-aware sustain (Gate only — Trigger is a one-shot with no sustain loop). A
// valid, non-zero-length loop wraps the read head back into [start, end); a
// zero-length loop is "no loop". Under Preserve the loop is over the source read
// (loop the source, shift the output).
const SampleLoop& loop = sample_->loop;
const bool loopUsable = sustainLoopUsable();
if (loopUsable) {
const double loopLen = static_cast<double>(loop.end - loop.start);
// Loop-aware sustain (Gate only — Trigger is a one-shot with no sustain loop). The
// span was folded once at note-on (loop_span.h); an invalid or absent loop leaves
// loop_.active false and this whole path off. Under Preserve the loop is over the
// source read (loop the source, shift the output).
const ResolvedLoop& loop = loop_;
if (loop.active) {
const double loopLen = static_cast<double>(loop.length);
while (readPos_ >= static_cast<double>(loop.end)) {
readPos_ -= loopLen; // wrap by exactly one loop length, preserving phase.
}
@@ -272,7 +470,14 @@ private:
// play span ends within the ramp). With no declick (the common case) this is
// byte-identical to the plain idle-out.
if (triggerRanOff || readPos_ >= static_cast<double>(frameCount)) {
// The NOTE is over the moment the read head leaves its span, whether or not a ramp
// still rings: no later frame can carry envelope output. Latching here is what keeps
// a ringing-out voice out of soundingNote() — the Preserve cap would otherwise
// refuse a new onset, and mono legato would retune a voice already past its end
// (silencing the new note) for the whole ~4 ms ramp.
amplitudeDone_ = true;
if (declickPending_) seedDeclick();
if (!declickActive_) seedTerminalDeclick();
if (declickActive_) {
// Bounded blend at silence: outCurrent == 0, so the blend is
// w*(ref 0) == w*ref. The weight decays by kDeclickDecay each frame,
@@ -296,8 +501,22 @@ private:
// Envelopes tick once per output frame. Pitch envelope biases pitch under either engine.
const double amp = tickAmplitude();
// Peer of the read-head exhaustion path above: a Trigger AHD whose stages end BEFORE
// the play span (a zero decay, which the shape deliberately keeps expressible) cuts the
// same synthetic Preserve tail at whatever level it was at. Seeded from lastOut, which
// still holds the PREVIOUS frame — this one is already silent. Gate is left out of THIS
// site only: its amplitude reaches zero through a release, so nothing here is cut
// mid-level. The exhaustion path above deliberately does NOT exclude Gate — a held Gate
// note whose source runs out with no loop is cut at its sustain level, and under
// Preserve that cut lands on the same recycled synthetic tail.
if (amplitudeDone_ && amp == 0.0 && !declickActive_ &&
playMode_ == PlayMode::Trigger) {
seedTerminalDeclick();
}
const double gain = amp * velocityGain_;
const double pitchEnvSemis = pitchEnv_.tick();
const double pitchEnvSemis = pitchSplineCur_.active()
? pitchSplineDepth_ * pitchSplineCur_.eval(splinePhase())
: pitchEnv_.tick();
// 2^(semis/12); when the envelope is off (semis exactly 0) this is 1.0 and skips the
// pow entirely — no per-frame transcendental on the common path.
@@ -309,53 +528,78 @@ private:
// and the amp envelope shapes the filtered result (drive included).
double outL, outRlocal = 0.0;
if (pitchEngine_ == PitchEngine::Preserve && shiftL_.configured()) {
// Feed the shifters the source stream at unity rate (duration held) and transpose
// the output by 2^((note-root + pitchEnvSemis)/12) — pitch envelope adds to the
// shift amount, not the read rate. The feed runs one window ahead of readPos_ (the
// rings were primed with that window at start()), under the same sustain-loop wrap
// rule, reading integer source frames (nothing to interpolate). Past the last real
// frame the shifter's writer is frozen — it recycles the real tail it already holds.
if (loopUsable) {
const std::int64_t loopLen = loop.end - loop.start;
while (feedPos_ >= loop.end) feedPos_ -= loopLen;
}
// feedPos_ runs one window ahead of readPos_; the last real source frame is
// playEnd_-1 for Trigger or frameCount-1 for Gate. Once feedPos_ reaches that bound
// the source is exhausted — feeding the held last sample instead would give the
// splice correlation a DC plateau it can't align on (periodic troughs at the splice
// cadence, growing toward the note end). Freezing the shifter's writer means no
// padding ever enters the ring, so the splice machinery keeps recycling the frozen
// all-real tail — a continuous tone through the voice's own end. The sustain-loop
// path never gets here: the wrap above keeps feedPos_ < loop.end forever.
// The two rates the shifter takes (pitch_shift.h owns why they are independent):
// the source is FED at stretchRate_, and the tap is SHIFTED by
// 2^((note-root + pitchEnvSemis)/12) — the pitch envelope adds to the shift amount,
// never to the read rate. The feed runs one window ahead of readPos_ (the rings were
// primed with that window at start()), under the same sustain-loop wrap rule,
// reading integer source frames into the ring — no RATE-DEPENDENT interpolation
// (unlike Varispeed's readPos_ below). The shifter's own read tap still carries a
// splice's sub-sample `frac` (pitch_shift.cpp), so it interpolates on every read,
// splice or no; that constant fractional delay is not a rate coupling.
const bool stereoOut = stereo && haveR && shiftR_.configured();
// The last real source frame is playEnd_-1 for Trigger or frameCount-1 for Gate.
// Once the feed reaches that bound the source is exhausted — feeding the held last
// sample instead would give the splice correlation a DC plateau it can't align on
// (periodic troughs at the splice cadence, growing toward the note end). Freezing the
// shifter's writer means no padding ever enters the ring, so the splice machinery
// keeps recycling the frozen all-real tail — a continuous tone through the voice's
// own end. The sustain-loop path never gets here: the wrap keeps the cursor inside
// the loop forever.
const std::int64_t feedBound =
(playMode_ == PlayMode::Trigger && playEnd_ > 0 && playEnd_ < frameCount)
? playEnd_ : frameCount;
const bool exhausted = feedPos_ >= feedBound;
if (exhausted) shiftL_.freezeTail(); // idempotent; input ignored while frozen
const bool feedOk = (!exhausted && feedPos_ >= 0 && feedPos_ < frameCount);
const AudioSample feedL = feedOk ? pcm[static_cast<std::size_t>(feedPos_)] : 0.0f;
const double shift = baseRatio_ * envFactor;
shiftL_.setShiftRatio(shift);
const double shiftedL = static_cast<double>(shiftL_.process(feedL));
if (stereoOut) shiftR_.setShiftRatio(shift);
// 0..kMaxFeedPerFrame source frames fall due this output frame. All but the LAST are
// written without producing output; the last rides the ordinary 1-in-1-out
// process(), so a rate of exactly 1.0 walks the pre-stretch code path unchanged.
// Crossfaded on the way IN to the shifter, not on the way out: loop the source,
// shift the output.
const std::int64_t due = stretch_.due(stretchRate_);
AudioSample feedL = 0.0f, feedR = 0.0f;
bool fed = false;
for (std::int64_t k = 0; k < due; ++k) {
if (fed) { // an earlier frame of this batch: write-only, no output
shiftL_.writeFrame(feedL);
if (stereoOut) shiftR_.writeFrame(feedR);
}
const std::int64_t q = stretch_.next(loop);
if (q >= feedBound) {
shiftL_.freezeTail(); // idempotent; input ignored while frozen
if (stereoOut) shiftR_.freezeTail();
feedL = feedR = 0.0f;
} else {
const double xw = crossfadeWeight(loop, static_cast<double>(q));
feedL = crossfadedSource(pcm, loop, q, xw);
if (stereoOut) feedR = crossfadedSource(pcmR, loop, q, xw);
}
fed = true;
}
const double shiftedL =
fed ? static_cast<double>(shiftL_.process(feedL))
: static_cast<double>(shiftL_.processNoInput());
outL = shiftedL;
if (stereo) {
if (haveR && shiftR_.configured()) {
if (stereoOut) {
// Genuine stereo (linked lag): channel 1's shifter FOLLOWS channel 0's
// splice decisions via processLinked — one correlation search, one lag, one
// splice schedule for both channels (standard stereo SOLA). An independent
// per-channel search re-drew an inter-channel offset of up to +/-maxLag at
// every splice: stereo image wander at the splice cadence + mono-sum
// combing. Each shifter is still processed EXACTLY ONCE per output frame
// (never twice — that would advance its heads twice and corrupt the state).
// (never twice — that would advance its heads twice and corrupt the state);
// the batch's earlier frames go through writeFrame, which produces none.
// Gated on haveR so a MONO sample never touches shiftR_ — start() only
// primes it for genuinely stereo samples, and a stale un-primed ring must
// not leak a previous note.
if (exhausted) shiftR_.freezeTail();
const AudioSample feedR =
feedOk ? pcmR[static_cast<std::size_t>(feedPos_)] : 0.0f;
shiftR_.setShiftRatio(shift);
outRlocal =
static_cast<double>(shiftR_.processLinked(feedR, shiftL_.lastSplice()));
fed ? static_cast<double>(
shiftR_.processLinked(feedR, shiftL_.lastSplice()))
: static_cast<double>(
shiftR_.processNoInputLinked(shiftL_.lastSplice()));
} else {
// Mono sample in stereo mode (dual-mono): shiftL_ already produced the
// shifted value from the mono feed; mirror it to R. Do NOT call
@@ -363,9 +607,13 @@ private:
outRlocal = shiftedL;
}
}
++feedPos_;
// Preserve advances the read head at the SOURCE rate (duration preserved).
ratio_ = 1.0;
// Preserve advances the read head at the STRETCH rate — the one duration control.
// Everything downstream of it (the loop wrap, the Trigger span, the spline phase)
// therefore stays a source-frame fact and scales by construction.
//
// The two sustain-less envelopes are evaluated at sourceOffset(), which advances at
// this rate — rateFittedAhd is what keeps their stage times wall-clock anyway.
ratio_ = stretchRate_;
} else {
// VARISPEED: pitch and duration coupled. The read rate carries the repitch; the
// pitch envelope multiplies the ratio for the read-rate bias (unchanged idiom when
@@ -376,7 +624,7 @@ private:
const std::int64_t i0 = static_cast<std::int64_t>(readPos_);
const double frac = readPos_ - static_cast<double>(i0);
std::int64_t i1 = i0 + 1;
if (loopUsable && i1 >= loop.end) {
if (loop.active && i1 >= loop.end) {
i1 = loop.start; // seamless wrap for the interpolation partner.
}
const bool i0ok = (i0 >= 0 && i0 < frameCount);
@@ -391,12 +639,23 @@ private:
(i0ok ? static_cast<double>(pcmR[i0]) : 0.0)) * frac;
outRlocal = srcR;
}
// Loop crossfade: blend toward the same read head one loop length earlier, which
// is the material the wrap is about to hand over to. Zero outside the fade region
// (and always, with no fade dialled), so the un-crossfaded read stays exactly the
// shape it was.
const double xw = crossfadeWeight(loop, readPos_);
if (xw > 0.0) {
const double tap = readPos_ - static_cast<double>(loop.length);
outL += xw * (lerpSource(pcm, frameCount, tap) - outL);
if (stereo) outRlocal += xw * (lerpSource(pcmR, frameCount, tap) - outRlocal);
}
ratio_ = baseRatio_ * envFactor;
}
// Skipped whole when disengaged (the default), so an un-filtered render stays
// bit-identical to the pre-filter engine.
if (filterOn_) {
if (filterRamping_) tickFilterRamps(); // false at rest: one predicted branch
tickFilterCutoff();
outL = static_cast<double>(filter_.process(0, static_cast<float>(outL)));
// Dual-mono feeds channel 1 the value channel 0 already carried, so mirroring the
@@ -458,46 +717,96 @@ private:
bool releasing_ = false;
int note_ = 0;
double velocityGain_ = 1.0;
double baseRatio_ = 1.0; // 2^((note-root)/12): the un-modulated repitch ratio
double baseRatio_ = 1.0; // recomputeBaseRatio's product: every constant pitch factor
double velPitchRatio_ = 1.0; // the velocity->pitch factor alone; retune re-applies it
double pitchOffsetRatio_ = 1.0; // the Pitch knob's factor — LIVE, re-applied by applyLive
double rateRatio_ = 1.0; // Rate's factor of the read increment; start() owns when it is 1
// Key-track, LATCHED at note-on beside the rate. Held here rather than re-read off the
// snapshot so a legato retune and a live block re-apply the note's own value; a published
// move reaches the next note only.
double keyTrack_ = kKeyTrackDefault;
// Whether this note is ACTUALLY taking the Preserve read — a Preserve voice whose shifters
// were never sized falls back to the varispeed one, and the two domains differ. Latched at
// note-on beside rateRatio_, which start() resolves from the same predicate.
bool preserveRead_ = false;
// baseRatio_ with the live Pitch factor divided back out, latched at note-on: what
// pitchEnvSpanFrames multiplies the CURRENT offset onto. Exact at Pitch 0 (the factor is
// exactly 1.0), which is what keeps the unity span bit-identical.
double pitchSpanBaseRate_ = 1.0;
double ratio_ = 1.0; // fractional source frames advanced per output frame (this frame)
double readPos_ = 0.0; // fractional frame index into the sample
const SampleData* sample_ = nullptr;
// Gate uses env_ (AHDSR); Trigger uses trigEnv_ — only one active per voice (selected by
// Gate uses env_ (AHDSR); Trigger uses ampAhd_ — only one active per voice (selected by
// playMode_ at start). playEnd_ is Trigger's source-frame stop (frees when
// readPos_ >= playEnd_).
PlayMode playMode_ = PlayMode::Gate;
AdsrEnvelope env_;
TriggerEnvelope trigEnv_;
std::int64_t startFrame_ = 0; // clamped initial read frame; Trigger fade offset origin
AhdEnvelope ampAhd_;
std::int64_t startFrame_ = 0; // clamped initial read frame; the span-offset origin
std::int64_t playEnd_ = 0; // Trigger: source-frame end; Gate: unused
bool amplitudeDone_ = false; // set when the active amplitude envelope finished
// The three drawn contours, bound at note-on to the loaded capture's own point arrays (the
// SampleData outlives the voice — same contract as sample_). A Staged EG leaves its cursor
// inactive, so a purely staged instrument's per-sample path gains three predicted branches
// and nothing else. splineScale_ is 1/frameCount, the readPos -> [0,1] map every contour
// shares; pitchSplineDepth_ is the pitch envelope's peak, zero while it is disabled.
SplineCursor ampSplineCur_;
SplineCursor pitchSplineCur_;
SplineCursor filterSplineCur_;
double splineScale_ = 0.0;
double pitchSplineDepth_ = 0.0;
// The sustain loop folded ONCE at note-on: the sample, the play mode and the stored span
// are all fixed for the note's lifetime, so re-deriving validity per frame bought nothing.
// Shared by the output anchor, the Preserve feed, and the start()-time ring prime.
ResolvedLoop loop_;
// The voice's OWN filter and filter envelope — per-voice, never shared, so two notes at
// different envelope phases are filtered independently. filterCutoffNorm_ keeps the
// unmodulated knob position the base is rebuilt from. Q, morph and drive are note-constants
// solved once by start()'s prepare(), which is why every later re-solve is cutoff-only.
// filterRate_ <= 0 makes prepare() bypass rather than invent a rate.
instrument::engine::filter::VoiceFilter filter_;
AdsrEnvelope filterEnv_;
AdsrEnvelope filterEnv_; // Gate
AhdEnvelope filterAhd_; // Trigger
bool filterOn_ = false;
double filterRate_ = 0.0;
double filterCutoffNorm_ = 1.0;
double filterModAmount_ = 0.0;
double filterVelOffset_ = 0.0; // velAmount * velocityCurve.eval(velocity), fixed per note
// The curve's value at THIS note's velocity — a fact about the note, latched at note-on —
// and the product with the live depth, which a live depth move recomputes.
double filterVelCurve_ = 0.0;
double filterVelOffset_ = 0.0;
double filterKeyTrack_ = 0.0;
instrument::engine::filter::FilterSettings filterSettings_{}; // the note's tone controls
float filterBaseCutoff_ = 1.0f; // cutoff before the envelope, clamped
float filterSolvedCutoff_ = 1.0f; // the position the live coefficients were solved from
bool filterSolved_ = false; // false forces the next frame to solve
// Live-parameter glides (live_params.h). Every one is parked at its target unless a move
// is in flight, so filterRamping_ is false and the per-sample path keeps the pre-live
// engine's exact shape. All five live in the filter's control domains — the envelopes
// need no ramp here, because holding normalized stage position is continuous by
// construction and their two genuine level steps are absorbed inside AdsrEnvelope /
// PitchEnvelope themselves.
bool filterRamping_ = false;
instrument::engine::ValueRamp rBaseCutoff_;
instrument::engine::ValueRamp rModAmount_;
instrument::engine::ValueRamp rResonance_;
instrument::engine::ValueRamp rMorph_;
instrument::engine::ValueRamp rDrive_;
// pitchEngine_ selects Varispeed (ratio bias) vs Preserve (source-rate read + shifter).
// shiftL_/shiftR_ transpose the Preserve output per channel. pitchEnv_ rides either engine.
//
// The shifter rings are primed at start() with the first window of the actual upcoming
// source (silence past the end) — output frame 0 is source frame `start`, no ring-fill
// silence, and splices always land in real history. feedPos_ is the integer source frame
// fed to the shifters next; it runs exactly one window ahead of readPos_ under the same
// sustain-loop wrap rule. Once feedPos_ passes the last real frame (Gate: sample end;
// silence, and splices always land in real history. stretch_ is the integer source frame
// fed to the shifters next plus the fractional rate debt; it runs one window ahead of
// readPos_ under the same sustain-loop wrap rule and at the same rate, so the two stay one
// window apart at every stretch. Once it passes the last real frame (Gate: sample end;
// Trigger: playEnd_), the shifters' writers freeze — no padding enters the rings and the
// splice machinery recycles the frozen real tail through the note end (see advanceFrame).
// primeBuf_ is the presized scratch the prime stream is assembled into.
@@ -505,7 +814,8 @@ private:
PitchEnvelope pitchEnv_;
PitchShifter shiftL_;
PitchShifter shiftR_;
std::int64_t feedPos_ = 0;
instrument::engine::StretchCursor stretch_;
double stretchRate_ = 1.0; // Preserve playback rate, clamped and latched at note-on
std::vector<AudioSample> primeBuf_;
// lastOut{L,R}_ track the voice's most recent rendered output. A takeover/steal start()
+40 -6
View File
@@ -33,6 +33,41 @@ VoiceEngine::VoiceEngine(std::size_t maxVoices, const SampleData& sample,
}
}
bool VoiceEngine::refreshLive() {
const instrument::engine::LiveParams* block = sample_.live;
if (block == nullptr) return false; // bare engine: the latched note-on values stand
instrument::engine::LiveValues observed;
const std::uint32_t generation = block->read(observed);
if (generation == 0 || generation == liveGeneration_) return false;
liveGeneration_ = generation;
live_ = observed;
haveLive_ = true;
return true;
}
void VoiceEngine::applyLiveToActive() {
if (!refreshLive()) return;
for (Voice& voice : voices_) {
if (voice.active()) voice.applyLive(live_, /*snap=*/false);
}
}
void VoiceEngine::startVoice(Voice& voice, int note, int velocity) {
refreshLive();
// THE read of the note-on-latched commit class, and the only one: a published block outranks
// the snapshot's own copy (a live edit deliberately leaves that stale), and applyLive below
// touches none of these three — so a move reaches the next note and no sounding one.
const double rate = haveLive_ ? live_.playRate : sample_.play.playRate;
const double keyTrack = haveLive_ ? live_.keyTrack : sample_.keyTrack;
// Already spline-folded in the block; the snapshot branch folds here so the two agree.
const double lengthFraction =
haveLive_ ? live_.lengthFraction : effectiveLengthFraction(sample_.play);
voice.start(note, velocity, sample_, /*declickTakeover=*/takeoverDeclick_, rate, keyTrack,
lengthFraction);
if (haveLive_) voice.applyLive(live_, /*snap=*/true);
voice.setStartOrder(nextStartOrder_++);
}
std::size_t VoiceEngine::activePreserveVoices() const {
// Count only voices that are SOUNDING A NOTE (playable span still running), not voices
// that have finished their note but are still ringing out a declick tail. A ramp-only
@@ -122,8 +157,7 @@ std::size_t VoiceEngine::monoNoteOn(int note, int velocity) {
// RETRIGGER takeover / first note of a phrase: (re)start the voice. The declick opt-in
// rides every mono restart; start() self-gates it on the voice being ACTIVE, so a
// first-note fresh start never ramps — only a hard cut of a sounding tone.
v.start(note, velocity, sample_, /*declickTakeover=*/takeoverDeclick_);
v.setStartOrder(nextStartOrder_++);
startVoice(v, note, velocity);
return 0;
}
@@ -150,8 +184,7 @@ void VoiceEngine::monoNoteOff(int note) {
// Retrigger fallback: re-strike the fallen-back-to note at its own original velocity.
// Peer restart site of monoNoteOn's takeover — same declick opt-in (the fallback also
// hard-cuts the sounding tone).
v.start(fb.note, fb.velocity, sample_, /*declickTakeover=*/takeoverDeclick_);
v.setStartOrder(nextStartOrder_++);
startVoice(v, fb.note, fb.velocity);
}
std::size_t VoiceEngine::noteOn(int note, int velocity) {
@@ -174,8 +207,7 @@ std::size_t VoiceEngine::noteOn(int note, int velocity) {
// active, so a free-voice start never ramps — only an at-cap steal, which is the same hard
// cut of a sounding tone as the mono retrig takeover.
const std::size_t v = allocateVoice();
voices_[v].start(note, velocity, sample_, /*declickTakeover=*/takeoverDeclick_);
voices_[v].setStartOrder(nextStartOrder_++);
startVoice(voices_[v], note, velocity);
return v;
}
@@ -225,6 +257,7 @@ void VoiceEngine::render(AudioSample* out, std::size_t frameCount) {
// The VST3 process callback hands us the host's output channel buffer here, so the
// audio thread never touches the heap.
if (out == nullptr || frameCount == 0) return;
applyLiveToActive(); // block boundary, once — never inside the frame loop
for (Voice& voice : voices_) {
if (!voice.active()) continue;
for (std::size_t f = 0; f < frameCount; ++f) {
@@ -240,6 +273,7 @@ void VoiceEngine::render(AudioSample* left, AudioSample* right, std::size_t fram
// iteration, same mid-block idle short-circuit) so stereo and mono share one stealing/idle
// discipline; only the per-frame call differs (renderFrameStereo vs renderFrame).
if (left == nullptr || right == nullptr || frameCount == 0) return;
applyLiveToActive(); // block boundary, once — never inside the frame loop
for (Voice& voice : voices_) {
if (!voice.active()) continue;
for (std::size_t f = 0; f < frameCount; ++f) {
+18
View File
@@ -10,6 +10,7 @@
#include <vector>
#include "core/audio/peaks.h"
#include "core/instrument/engine/live_params.h"
#include "core/instrument/engine/play_params.h"
#include "core/instrument/engine/voice.h"
@@ -106,6 +107,23 @@ private:
// one per the documented policy. Always returns a valid index (maxVoices >= 1).
std::size_t allocateVoice();
// --- Live-parameter observation (live_params.h) ---
// The ONE place the seqlock is read: at block start and at each note-on, on the audio
// thread, never per frame. A torn or never-published read leaves the last good snapshot
// in place rather than spinning. Returns whether a NEW generation landed.
bool refreshLive();
// Block-boundary refresh: pushes a newly-observed generation into every sounding voice,
// which glides toward it. No-op when nothing changed (and when no block is attached).
void applyLiveToActive();
// The one restart path: start the voice, hand it the live values outright (it has nothing
// to glide from), and stamp its age. Shared by the poly steal and both mono restarts so
// no restart site can miss the live handoff.
void startVoice(Voice& voice, int note, int velocity);
instrument::engine::LiveValues live_{};
std::uint32_t liveGeneration_ = 0; // last generation observed; 0 = none yet
bool haveLive_ = false;
// Count of active Preserve-engine voices (for the Preserve cap). Rescanned per note-on
// (cheap: bounded by maxVoices) rather than maintained as a running tally.
std::size_t activePreserveVoices() const;
+19 -5
View File
@@ -2,8 +2,8 @@ reasampler_pure_library(bridge_marshal SOURCES bridge_marshal.cpp)
reasampler_test(bridge_marshal LINK bridge_marshal)
reasampler_pure_library(trigger_seam SOURCES trigger_seam.cpp)
# Links only trigger_seam not even editor_geometry the plainest data-boundary proof
# available.
# Plain frame arithmetic over doubles: no engine, no value layer, no editor geometry. The
# %-length fold it used to host lives with its siblings in play_params.h.
reasampler_test(trigger_seam LINK trigger_seam)
reasampler_pure_library(bank_sync
@@ -17,17 +17,31 @@ reasampler_test(bank_sync LINK bank_sync)
# the voice engine: velocity_curve (the curve field) and master_gain (the wire gain cap) only.
# play_params.h also pulls in filter/'s headers (FilterSettings, MorphLaw) for the v9 filter
# tail -- plain value types, so no filter symbol is linked and this stays true.
# Two TUs on the format's OWN seam: the envelope's version ladder and the payload's, which
# the format already keeps on independent version axes (see component_state_io.h).
reasampler_pure_library(component_state_io
SOURCES component_state_io.cpp
LINK PUBLIC velocity_curve master_gain)
SOURCES component_state_io.cpp params_payload.cpp
LINK PUBLIC velocity_curve master_gain curve_law musical_division)
# Links only component_state_io, deliberately no sampler_core/pitch_shift: the structural
# proof the codec is engine-free, which is what keeps engine object code out of the extension.
reasampler_test(component_state_io LINK component_state_io)
# The stored seconds value layer, header-only (hence INTERFACE) PlaySeconds and the four
# stage-time structs it composes. Split from sample_map so a consumer that only edits those
# values reaches them WITHOUT the bank model and the WAV codec: the editor's deck_values
# binding is exactly that consumer, and linking sample_map for one value struct would put
# bank_book + wav_codec into a test whose subject is a knob. Links the same value-layer set
# play_params.h needs (velocity_curve's out-of-line zero() is a default member initializer).
add_library(play_seconds INTERFACE)
target_include_directories(play_seconds INTERFACE ${REASAMPLER_SRC_DIR})
target_link_libraries(play_seconds INTERFACE velocity_curve peaks curve_law)
# The mapping's product is plain SampleData, so the voice engine is not a dependency.
reasampler_pure_library(sample_map
SOURCES sample_map.cpp
LINK PUBLIC bank_book wav_codec velocity_curve peaks)
LINK PUBLIC bank_book wav_codec play_seconds velocity_curve peaks curve_law
musical_division
PRIVATE period_detect)
# Links only sample_map + component_state_io: the same plain-data-boundary proof, spanning
# both halves of the mapping/codec split where the frozen-format assertions live.
reasampler_test(sample_map LINK sample_map component_state_io)
+6 -269
View File
@@ -1,292 +1,29 @@
// component_state_io — the ComponentState envelope + params-payload binary codec. See
// component_state_io.h for the format ladders (envelope v1..v11, params payload v1..v9).
// Every wire format is FROZEN — byte-identical across revisions.
// component_state_io — the ComponentState ENVELOPE codec. See component_state_io.h for both
// format ladders (envelope v1..v11, params payload v1..v11); the payload half lives in
// params_payload, which grows on its own version axis. Every wire format is FROZEN —
// byte-identical across revisions.
#include "core/instrument/map/component_state_io.h"
#include <algorithm> // std::min (bounded curve-point reserve)
#include <cassert> // assert (v3-lift projectRate guard)
#include <cmath> // std::isfinite (v8 master-gain validation)
#include <cstring> // std::memcpy (serializeSelection)
#include <utility> // std::move
#include "core/instrument/engine/master_gain.h" // masterGainMaxLinear — the v8 master-gain wire cap
#include "core/instrument/map/params_payload.h" // the payload half of this codec
#include "core/wire/bytes.h" // putLE / ByteReader / doubleToBits (the ONE LE codec)
namespace reasampler::instrument::map {
using engine::masterGainMaxLinear;
using reasampler::wire::ByteReader;
using reasampler::wire::asU64;
using reasampler::wire::bitsToDouble;
using reasampler::wire::doubleToBits;
using reasampler::wire::putLE;
namespace {
// Signed 64-bit values ride the wire as their two's-complement unsigned image.
std::uint64_t asU64(std::int64_t v) { return static_cast<std::uint64_t>(v); }
// What a payload read yields. `adoptedSampleId` is non-empty ONLY for a retired zone-list
// payload that carried at least one zone: the first zone's capture, which supersedes the
// envelope's selection id (see the adoption rule in the header).
struct PayloadRead {
InstrumentParams params;
std::string adoptedSampleId;
};
// Emit the OVERRIDE trio shared by the v2..v7 per-zone record and the v8 single record, so
// the two shapes cannot drift byte-for-byte.
void putOverrides(std::vector<std::uint8_t>& out, const InstrumentParams& p) {
out.push_back(p.rootOverride ? 1 : 0);
if (p.rootOverride) {
putLE(out, static_cast<std::uint32_t>(static_cast<std::int32_t>(*p.rootOverride)));
}
out.push_back(p.loopOverride ? 1 : 0);
if (p.loopOverride) {
out.push_back(p.loopOverride->hasLoop ? 1 : 0);
putLE(out, asU64(p.loopOverride->start));
putLE(out, asU64(p.loopOverride->end));
}
out.push_back(p.startPoint ? 1 : 0);
if (p.startPoint) putLE(out, asU64(*p.startPoint));
}
// A velocity curve: 4-byte LE control-point count, then per point velocity + amp as doubles.
// The amp curve (v7) and the filter's own curve (v9) share this shape.
void putCurve(std::vector<std::uint8_t>& out, const VelocityCurve& curve) {
const std::vector<VelocityPoint>& pts = curve.points();
putLE(out, static_cast<std::uint32_t>(pts.size()));
for (const VelocityPoint& pt : pts) {
putLE(out, doubleToBits(pt.velocity));
putLE(out, doubleToBits(pt.amp));
}
}
// Append the params payload: marker + version + the single parameter record. Always emits
// the CURRENT payload version; the marker precedes the record so any reader detects the
// shape independent of the envelope version (see component_state_io.h).
void putParamsPayload(std::vector<std::uint8_t>& out, const InstrumentParams& p) {
putLE(out, kParamsFormatMarker);
putLE(out, kParamsPayloadVersion);
putOverrides(out, p);
// Play params: wall-clock times are SECONDS (doubles); trigger %-length + fades stay
// source frames/fraction. Field order matches the header's v5 tail spec verbatim.
const PlaySeconds& pp = p.play;
out.push_back(pp.playMode == PlayMode::Trigger ? 1 : 0);
putLE(out, doubleToBits(pp.adsr.holdSeconds)); // wall-clock seconds
putLE(out, doubleToBits(pp.trigger.lengthFraction)); // fraction
putLE(out, asU64(pp.trigger.fadeInFrames)); // source frames
putLE(out, asU64(pp.trigger.fadeOutFrames)); // source frames
out.push_back(pp.pitchEngine == PitchEngine::Preserve ? 1 : 0);
out.push_back(pp.pitchEnv.enabled ? 1 : 0);
putLE(out, doubleToBits(pp.pitchEnv.attackSeconds)); // wall-clock seconds
putLE(out, doubleToBits(pp.pitchEnv.decaySeconds)); // wall-clock seconds
putLE(out, doubleToBits(pp.pitchEnv.peakSemitones)); // depth
// Full AHDSR A/D/S/R tail — wall-clock SECONDS (sustainLevel is a level).
putLE(out, doubleToBits(pp.adsr.attackSeconds));
putLE(out, doubleToBits(pp.adsr.decaySeconds));
putLE(out, doubleToBits(pp.adsr.sustainLevel));
putLE(out, doubleToBits(pp.adsr.releaseSeconds));
// Key-tracking scalar (1.0 = 100% ET).
putLE(out, doubleToBits(p.keyTrack));
// The velocity->amp transfer curve: 4-byte LE control-point count, then per point
// velocity + amp as doubles (endpoints included, so N >= 2).
putCurve(out, p.velocityCurve);
// v9: the per-voice filter tail. The module's floats widen to doubles on the wire so the
// whole payload stays one numeric shape.
const FilterSeconds& f = pp.filter;
out.push_back(f.enabled ? 1 : 0);
putLE(out, doubleToBits(static_cast<double>(f.settings.cutoffNorm)));
putLE(out, doubleToBits(static_cast<double>(f.settings.resonanceNorm)));
putLE(out, doubleToBits(static_cast<double>(f.settings.morphNorm)));
putLE(out, doubleToBits(static_cast<double>(f.settings.driveNorm)));
out.push_back(f.settings.morphLaw == engine::filter::MorphLaw::HighNotchLow ? 1 : 0);
putLE(out, doubleToBits(f.modAmount));
putLE(out, doubleToBits(f.velAmount));
putLE(out, doubleToBits(f.keyTrack));
putLE(out, doubleToBits(f.env.attackSeconds));
putLE(out, doubleToBits(f.env.holdSeconds));
putLE(out, doubleToBits(f.env.decaySeconds));
putLE(out, doubleToBits(f.env.sustainLevel));
putLE(out, doubleToBits(f.env.releaseSeconds));
putCurve(out, f.velocityCurve);
}
// Read the play tail (v5 shape onward) into `p`. Shared by the legacy zone reader and the
// v8 single-record reader so the two can never disagree about field order.
void readSecondsPlayTail(ByteReader& r, InstrumentParams& p) {
p.play.playMode = (r.u8() != 0) ? PlayMode::Trigger : PlayMode::Gate;
p.play.adsr.holdSeconds = bitsToDouble(r.u64());
p.play.trigger.lengthFraction = bitsToDouble(r.u64());
p.play.trigger.fadeInFrames = r.i64();
p.play.trigger.fadeOutFrames = r.i64();
p.play.pitchEngine = (r.u8() != 0) ? PitchEngine::Preserve : PitchEngine::Varispeed;
p.play.pitchEnv.enabled = (r.u8() != 0);
p.play.pitchEnv.attackSeconds = bitsToDouble(r.u64());
p.play.pitchEnv.decaySeconds = bitsToDouble(r.u64());
p.play.pitchEnv.peakSemitones = bitsToDouble(r.u64());
p.play.adsr.attackSeconds = bitsToDouble(r.u64());
p.play.adsr.decaySeconds = bitsToDouble(r.u64());
p.play.adsr.sustainLevel = bitsToDouble(r.u64());
p.play.adsr.releaseSeconds = bitsToDouble(r.u64());
}
// Read a velocity curve tail into `curve`. fromPoints repairs the X-order/endpoint invariant
// defensively; a truncated read leaves `curve` at whatever default it came in with.
void readCurveTail(ByteReader& r, VelocityCurve& curve) {
const std::uint32_t ptCount = r.u32();
std::vector<VelocityPoint> pts;
// Bound the reserve to what the blob can hold (16 bytes/point) so a corrupt huge count
// can't trigger a giant allocation before the bounded reads fail.
const std::size_t remaining = r.bytes.size() > r.pos ? r.bytes.size() - r.pos : 0;
pts.reserve(std::min(static_cast<std::size_t>(ptCount), remaining / 16));
for (std::uint32_t i = 0; i < ptCount && r.ok; ++i) {
const double vel = bitsToDouble(r.u64());
const double amp = bitsToDouble(r.u64());
pts.push_back(VelocityPoint{vel, amp});
}
if (r.ok) {
curve = reasampler::instrument::engine::VelocityCurve::fromPoints(std::move(pts));
}
}
// Read the v9 filter tail into `p`. A blob that stops short leaves the off/neutral default,
// which is what makes a v8 blob play bit-identically under the new codec.
void readFilterTail(ByteReader& r, InstrumentParams& p) {
FilterSeconds& f = p.play.filter;
f.enabled = (r.u8() != 0);
f.settings.cutoffNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.resonanceNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.morphNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.driveNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.morphLaw = (r.u8() != 0) ? engine::filter::MorphLaw::HighNotchLow
: engine::filter::MorphLaw::HighBandLow;
// Same non-finite-falls-back-to-neutral guard as the v8 master gain above: these three
// reach Voice::tickFilterCutoff's clamp compares and a static_cast<int>, both UB on NaN.
double modAmount = bitsToDouble(r.u64());
double velAmount = bitsToDouble(r.u64());
double keyTrack = bitsToDouble(r.u64());
f.modAmount = std::isfinite(modAmount) ? modAmount : 0.0;
f.velAmount = std::isfinite(velAmount) ? velAmount : 0.0;
f.keyTrack = std::isfinite(keyTrack) ? keyTrack : 0.0;
f.env.attackSeconds = bitsToDouble(r.u64());
f.env.holdSeconds = bitsToDouble(r.u64());
f.env.decaySeconds = bitsToDouble(r.u64());
f.env.sustainLevel = bitsToDouble(r.u64());
f.env.releaseSeconds = bitsToDouble(r.u64());
readCurveTail(r, f.velocityCurve);
}
// Read a RETIRED zone-list payload (v1..v7) and adopt zone ONE. Every zone is still parsed
// so the truncation ladder behaves exactly as it did — a record that fails mid-way stops the
// walk — but only the first zone's capture and parameters survive; the rest drop, touching
// no file and no bank entry.
// `pv` is the already-consumed payload version (0 = v1, no marker). `projectRate` converts
// the LEGACY v3 wall-clock frame counts to seconds (seconds = frames / projectRate); v5+
// blobs carry seconds directly and need no rate.
PayloadRead readLegacyZonePayload(ByteReader& r, std::uint32_t pv, double projectRate) {
PayloadRead out;
const bool extended = (pv >= 2); // v2+: the loop/start tail is present
const bool legacyV3Play = (pv == 3); // legacy play tail, wall-clock in nominal frames
const bool secondsPlay = (pv >= 5); // v5+: full play params, wall-clock in seconds
const bool keyTrackTail = (pv >= 6); // v6+: keyTrack scalar
const bool curveTail = (pv >= 7); // v7+: velocity->amp curve, appended last
const std::uint32_t count = r.u32();
bool adopted = false;
for (std::uint32_t i = 0; i < count && r.ok; ++i) {
// A v1/v2 payload (no play tail) lifts to the product defaults (Gate + Preserve +
// tier-0 AHDSR seconds) — InstrumentParams' own construction defaults.
InstrumentParams p;
std::string sampleId;
const std::uint32_t idLen = r.u32();
sampleId = r.str(idLen);
r.i32(); // lowNote — the retired key range; read to keep the record walk aligned
r.i32(); // highNote
const std::uint8_t hasOverride = r.u8();
if (hasOverride) p.rootOverride = r.i32();
if (extended) {
const std::uint8_t hasLoop = r.u8();
if (hasLoop) {
SampleLoop lp;
lp.hasLoop = (r.u8() != 0);
lp.start = r.i64();
lp.end = r.i64();
p.loopOverride = lp;
}
const std::uint8_t hasStart = r.u8();
if (hasStart) p.startPoint = r.i64();
}
if (legacyV3Play) {
// LEGACY v3 play tail. Wall-clock fields (hold, pitchEnv A/D) were written as
// frames -> divide by `projectRate` to reach seconds. Trigger %-length + fades
// are source-timeline, read as-is. A/D/S/R are ABSENT in v3 -> keep the defaults.
assert(projectRate > 0.0 && "readLegacyZonePayload: projectRate must be > 0 for v3 lift");
const double liftRate = projectRate > 0.0 ? projectRate : 1.0; // avoids div-by-zero; assert fires first
p.play.playMode = (r.u8() != 0) ? PlayMode::Trigger : PlayMode::Gate;
p.play.adsr.holdSeconds = static_cast<double>(r.i64()) / liftRate;
p.play.trigger.lengthFraction = bitsToDouble(r.u64());
p.play.trigger.fadeInFrames = r.i64();
p.play.trigger.fadeOutFrames = r.i64();
p.play.pitchEngine = (r.u8() != 0) ? PitchEngine::Preserve : PitchEngine::Varispeed;
p.play.pitchEnv.enabled = (r.u8() != 0);
p.play.pitchEnv.attackSeconds = static_cast<double>(r.i64()) / liftRate;
p.play.pitchEnv.decaySeconds = static_cast<double>(r.i64()) / liftRate;
p.play.pitchEnv.peakSemitones = bitsToDouble(r.u64());
} else if (secondsPlay) {
readSecondsPlayTail(r, p);
}
// A pre-v6 payload leaves keyTrack = 1.0 (100% ET), so an already-saved instance
// repitches BIT-IDENTICALLY. A pre-v7 payload leaves VelocityCurve::flat().
if (keyTrackTail) p.keyTrack = bitsToDouble(r.u64());
if (curveTail) readCurveTail(r, p.velocityCurve);
// Payload version 4 (a branch-only frames tail, never shipped) and any unknown pv
// leave the seconds product defaults on p.play.
if (!r.ok) break; // truncated mid-record -> keep what parsed cleanly, drop the rest
if (!adopted) {
out.params = std::move(p);
out.adoptedSampleId = std::move(sampleId);
adopted = true;
}
}
return out;
}
// Read whichever payload shape follows: the single-record shape (v8 onward, growing by
// appended tails), or a retired v1..v7 zone list (adopting zone one). An absent marker means
// v1 (a plain small zone count).
PayloadRead readParamsPayload(ByteReader& r, double projectRate) {
std::uint32_t pv = 0; // 0 = v1, no marker
if (r.peekU32() == kParamsFormatMarker) {
r.u32(); // consume the marker
pv = r.u32(); // payload version
}
if (pv < kParamsSingleRecordVersion) return readLegacyZonePayload(r, pv, projectRate);
PayloadRead out;
InstrumentParams& p = out.params;
const std::uint8_t hasRoot = r.u8();
if (hasRoot) p.rootOverride = r.i32();
const std::uint8_t hasLoop = r.u8();
if (hasLoop) {
SampleLoop lp;
lp.hasLoop = (r.u8() != 0);
lp.start = r.i64();
lp.end = r.i64();
p.loopOverride = lp;
}
const std::uint8_t hasStart = r.u8();
if (hasStart) p.startPoint = r.i64();
readSecondsPlayTail(r, p);
p.keyTrack = bitsToDouble(r.u64());
readCurveTail(r, p.velocityCurve);
if (pv >= kParamsFilterVersion) readFilterTail(r, p);
// A truncated record leaves whatever parsed plus construction defaults for the rest —
// the same degrade-don't-throw contract the zone ladder always had.
if (!r.ok) return PayloadRead{};
return out;
}
// Apply a payload read to the state: the adoption rule (a retired payload's first zone
// supersedes the envelope's selection id) lives here, once.
void applyPayload(ComponentState& out, PayloadRead read) {
+128 -9
View File
@@ -8,7 +8,8 @@
// own links are velocity_curve + master_gain (wire value validation), never the engine.
//
// EVERY wire format below is FROZEN; the full version ladders (envelope v1..v11, params
// payload v1..v8) must be preserved exactly.
// payload v1..v16) must be preserved exactly. This header is the ONE home for both ladders
// and every version constant; the payload half is IMPLEMENTED in params_payload.
#include <cstdint>
#include <string>
@@ -70,22 +71,113 @@ namespace reasampler::instrument::map {
// startPoint (iff set); the v5 play tail verbatim (SECONDS); 8-byte LE keyTrack; then the
// velocity curve (count + points) as in v7.
//
// v9 (CURRENT WRITE FORMAT) is v8 PLUS the per-voice filter tail, appended after the velocity
// curve: 1 byte enabled; 8-byte LE cutoffNorm, resonanceNorm, morphNorm, driveNorm (doubles,
// widened from the module's floats); 1 byte morphLaw (0 HighBandLow / 1 HighNotchLow); 8-byte
// LE modAmount, velAmount, keyTrack; 8-byte LE filter-env attack/hold/decay/sustain/release
// SECONDS; then the filter's OWN velocity curve (count + points, same shape as v7's). A v8
// blob is a strict prefix, so it lifts to the off/neutral filter default and plays
// bit-identically.
// v9 is v8 PLUS the per-voice filter tail, appended after the velocity curve: 1 byte enabled;
// 8-byte LE cutoffNorm, resonanceNorm, morphNorm, driveNorm (doubles, widened from the
// module's floats); 1 byte morphLaw (0 HighBandLow / 1 HighNotchLow); 8-byte LE modAmount,
// velAmount, keyTrack; 8-byte LE filter-env attack/hold/decay/sustain/release SECONDS; then
// the filter's OWN velocity curve (count + points, same shape as v7's). A v8 blob is a strict
// prefix, so it lifts to the off/neutral filter default and plays bit-identically.
//
// v10 is v9 PLUS the staged-curve tail, appended after the filter's velocity curve, all
// 8-byte LE doubles in this order: amp AHDSR attack/decay/release curve
// exponents; the Trigger amp AHD (attack SECONDS, decay SECONDS, hold FRACTION, attack curve,
// decay curve); the pitch envelope's hold FRACTION + attack/decay curve exponents; the filter
// AHDSR's attack/decay/release curve exponents; the filter's Trigger AHD (same five fields as
// the amp's). A v9-or-older blob is a strict prefix and lifts to the neutral exponent 1.0.
//
// v11 is v10 PLUS one 8-byte LE int64: the loop crossfade in SOURCE frames (a source-timeline
// quantity like the loop points, so no rate resolves it). A v10-or-older blob is a strict
// prefix and lifts to 0 — the hard seam it always played.
//
// v12 (CURRENT WRITE FORMAT) is v11 PLUS the velocity->PITCH transfer curve (count + points,
// the same shape as v7's), appended after the loop crossfade. Its y is a normalized fraction
// of kVelocityPitchRangeSemitones (play_params.h) — a full-scale constant that lives OUTSIDE
// this frozen ladder, so retuning it re-tunes every saved v12 project's pitch-curve throw. It
// also RE-TAGS the DOMAIN of one frozen slot inside the v9 filter tail: that curve's y is read
// as BIPOLAR [-1,+1] from v12 on, having been UNIPOLAR [0,1] before. Every other filter slot,
// velAmount included, keeps its meaning — the cutoff contribution is still
// velAmount * curve(velocity).
// PRE-v12 LIFT: a domain re-tag and nothing more. A pre-v12 curve's stored y values all lie in
// [0,1], which is inside [-1,+1], so the widened box-clamp alters no knot and eval is unchanged
// at every velocity — a pre-v12 project sounds identical without any rounding argument. A
// pre-v12 blob carries no pitch curve at all and lifts to the bipolar flat-at-zero default,
// which transposes nothing. A DOWNGRADE to a pre-v12 binary re-narrows the domain, so a curve
// drawn into the negative half comes back with that half clamped to 0.
//
// v13 is v12 PLUS the DUAL Staged/Spline envelope state, appended after
// the velocity->pitch curve. Its two halves, in order:
// (a) the three spline EGs — amp, pitch, filter, in that order. Each: 1 byte mode (0 Staged /
// 1 Spline), then a SPLINE CURVE block: 4-byte LE point count N, then per point 8-byte LE
// x + 8-byte LE y (doubles) + 1 byte hard. x spans the curve's canonical [0,127] (a
// normalized-time contour maps onto that same span — velocity_curve.h owns why one span
// serves both), y is UNIPOLAR [0,1]; the pitch and filter depth knobs scale it.
// (b) the HARD-FLAG tails for the three v7/v9/v12 velocity curves — amp, filter, pitch, in
// that order. Each: 4-byte LE count N, then N bytes. Those three curve blocks are FROZEN
// at 16 bytes/point and cannot grow a per-point flag, so the flags ride here instead. A
// tail whose count does not match the curve as read is IGNORED (the curve keeps its
// flags-off default) rather than applied to the wrong knots — a repaired blob loses the
// hard points, never misplaces them.
// A v12-or-older blob is a strict prefix and lifts to {Staged, the y = 1 - x default contour}
// on all three EGs with no hard point anywhere, so it plays exactly as it did.
//
// v14 is v13 PLUS the resample bake's Hold division, appended after the
// hard-flag tails: 4-byte LE quarterExponent (two's-complement int32) + 1 byte modifier (0
// Straight / 1 Dotted / 2 Triplet). Decoded through makeDivision, which clamps both fields —
// never memcpy'd into the type (core/instrument/note/CLAUDE.md owns why). A v13-or-older blob
// is a strict prefix and lifts to one bar, and Hold reaches no audio path, so a pre-v14
// instance plays and bakes identically except where its window was underived to begin with.
// A blob truncated INSIDE this tail costs the Hold alone rather than resetting the record —
// the same revive discipline the v13 hard-flag tails follow, and for the same reason.
//
// v15 is v14 PLUS ONE byte: the master-bus limiter's enable, appended after the Hold
// division. A v14-or-older blob is a strict prefix and lifts to 0 — bypassed,
// which is also the field's product default, so a project saved before the limiter existed
// reopens with the limiter off and sounding identical. It carries the Hold's revive
// discipline too: now that it, not the Hold, is the last tail, a truncation inside this byte
// would otherwise reset the record the Hold's own revive just preserved.
//
// v16 (CURRENT WRITE FORMAT) is v15 PLUS TWO 8-byte LE doubles, appended after the limiter
// byte: the playback RATE as a ratio, then the baseline PITCH offset in semitones. A v15-or-
// older blob is a strict prefix and lifts to 1.0 / 0.0 — unity rate and no offset, which is
// what every instance before them played, so it reopens bit-identical. Both are rate-free
// values, so nothing about them is resolved against the project rate. Same revive-and-drain
// discipline as the two tails above. The two wire GUARDS deliberately differ, and
// readRateAndPitchOffset owns why: the offset is range-checked here because nothing downstream
// bounds it, while the rate is only checked for usability because its range belongs to the
// engine's own clamp.
//
// The two int64 slots the v5 play tail spends on the RETIRED Trigger fade pair are frozen in
// shape and still read: a pre-v10 blob's fade-in/fade-out become the Trigger AHD that replaced
// them (attack <- fade-in, decay <- fade-out, hold <- the whole remainder), converted to
// seconds at the project rate the reader is handed. v10+ writes ZERO into both — the values
// live in the AHD now, so a DOWNGRADE to a pre-v10 binary loses the Trigger amp shape.
//
// LOSSY UNDER A RATE MISMATCH. The fades were SOURCE frames and the AHD stores wall-clock
// seconds, so the lift divides by the PROJECT rate while the build later multiplies by the
// DECODE rate: a file whose own rate differs from the project's comes back scaled by that
// ratio (a 441-frame fade on a 44.1 kHz file in a 48 kHz project resolves to 405 source
// frames, ~8% short). The codec cannot close this — it never sees the file — and deferring the
// lift to build time would mean carrying the retired fade pair through the parameter set,
// reintroducing the mechanism the AHD replaced.
//
// A truncated/unknown/empty payload yields the DEFAULT parameter set.
// The exponents the lifted fades take. The AHD's curve law is phi^p (core/util/curve_law.h),
// which cannot reproduce the retired pair's equal-power sin/cos exactly at ANY exponent — so
// the lift takes the MINIMAX fit rather than the linear neutral, which is free (one constant,
// written once here) and several times closer. The two differ because the two stages fit
// different forms: attack fits phi^p to sin(pi*phi/2), decay fits 1 - t^q to cos(pi*t/2).
// The measured bounds are asserted in tests/test_component_state_io.cpp. Every OTHER curve on
// a migrated blob still lifts to the neutral — only the fades had a prior shape to reproduce.
inline constexpr double kTriggerFadeLiftAttackCurve = 0.6133;
inline constexpr double kTriggerFadeLiftDecayCurve = 1.7437;
inline constexpr std::uint32_t kPerformanceStateVersion = 2;
// The params-payload format version and its detection marker. The marker is a high sentinel
// no legitimate v1 zone count (bounded by 128 MIDI zones, always tiny) could ever equal, so
// a reader detects record shape independent of the envelope version.
inline constexpr std::uint32_t kParamsPayloadVersion = 9; // v8 + the per-voice filter tail
inline constexpr std::uint32_t kParamsPayloadVersion = 16; // v15 + Rate and the pitch offset
inline constexpr std::uint32_t kParamsFormatMarker = 0xFFFFFF00u;
// The first SINGLE-RECORD payload version. Everything below it is a retired zone list and
@@ -98,6 +190,33 @@ inline constexpr std::uint32_t kParamsSingleRecordVersion = 8;
// self-describing, mirroring the envelope's version constants.
inline constexpr std::uint32_t kParamsFilterVersion = 9;
// v9 + the staged-curve tail (curve exponents, the Trigger AHDs, the pitch Hold fraction).
inline constexpr std::uint32_t kParamsCurveVersion = 10;
// v10 + the loop-crossfade frame count.
inline constexpr std::uint32_t kParamsLoopVersion = 11;
// v11 + the velocity->pitch curve; the appended tail branches on THIS, never on
// kParamsPayloadVersion. The filter curve's v12 domain re-tag needs no branch of its own — a
// pre-v12 curve's y values are already valid bipolar ones.
inline constexpr std::uint32_t kParamsVelocityVersion = 12;
// v12 + the dual Staged/Spline state; the appended tail branches on THIS, never on
// kParamsPayloadVersion.
inline constexpr std::uint32_t kParamsSplineVersion = 13;
// v13 + the bake Hold division; the appended tail branches on THIS, never on
// kParamsPayloadVersion.
inline constexpr std::uint32_t kParamsBakeHoldVersion = 14;
// v14 + the master-bus limiter enable; the appended byte branches on THIS, never on
// kParamsPayloadVersion.
inline constexpr std::uint32_t kParamsLimiterVersion = 15;
// v15 + the playback rate and the baseline pitch offset; the appended pair branches on THIS,
// never on kParamsPayloadVersion.
inline constexpr std::uint32_t kParamsRateVersion = 16;
// (No nominal-rate constant.) The legacy v3 payload's wall-clock frame counts convert to
// seconds at the v3 read boundary using the PROJECT sample rate threaded in as a parameter
// (frames / projectRate = seconds) — the same rate the build already receives, so the
+598
View File
@@ -0,0 +1,598 @@
// params_payload.cpp — see params_payload.h. The format ladder it implements is documented
// in component_state_io.h; every wire format below is FROZEN.
#include "core/instrument/map/params_payload.h"
#include <algorithm> // std::min (bounded curve-point reserve)
#include <cassert> // assert (v3-lift projectRate guard)
#include <cmath> // std::isfinite (wire-value validation)
#include <utility> // std::move
#include "core/instrument/engine/time_stretch.h" // clampStretchRate (THE rate bound)
#include "core/util/curve_law.h" // clampCurve / kCurveNeutral (wire validation)
#include "core/wire/bytes.h" // putLE / ByteReader / doubleToBits (the ONE LE codec)
namespace reasampler::instrument::map {
using reasampler::wire::ByteReader;
using reasampler::wire::asU64;
using reasampler::wire::bitsToDouble;
using reasampler::wire::doubleToBits;
using reasampler::wire::putLE;
namespace {
// Emit the OVERRIDE trio shared by the v2..v7 per-zone record and the v8 single record, so
// the two shapes cannot drift byte-for-byte.
void putOverrides(std::vector<std::uint8_t>& out, const InstrumentParams& p) {
out.push_back(p.rootOverride ? 1 : 0);
if (p.rootOverride) {
putLE(out, static_cast<std::uint32_t>(static_cast<std::int32_t>(*p.rootOverride)));
}
out.push_back(p.loopOverride ? 1 : 0);
if (p.loopOverride) {
out.push_back(p.loopOverride->hasLoop ? 1 : 0);
putLE(out, asU64(p.loopOverride->start));
putLE(out, asU64(p.loopOverride->end));
}
out.push_back(p.startPoint ? 1 : 0);
if (p.startPoint) putLE(out, asU64(*p.startPoint));
}
// A velocity curve: 4-byte LE control-point count, then per point velocity + value as doubles.
// The amp curve (v7), the filter's own curve (v9) and the pitch curve (v12) share this shape;
// the y DOMAIN is not on the wire — it is a property of the slot, so the reader supplies it.
void putCurve(std::vector<std::uint8_t>& out, const VelocityCurve& curve) {
const std::vector<VelocityPoint>& pts = curve.points();
putLE(out, static_cast<std::uint32_t>(pts.size()));
for (const VelocityPoint& pt : pts) {
putLE(out, doubleToBits(pt.velocity));
putLE(out, doubleToBits(pt.value));
}
}
// A spline EG: 1 byte mode, then the contour as count + (x, y, hard) per point. Distinct from
// putCurve because the three velocity-curve blocks are frozen at 16 bytes/point and cannot grow
// the hard flag; this block was born with it.
void putSplineEnv(std::vector<std::uint8_t>& out, const SplineEnv& s) {
out.push_back(s.mode == EnvMode::Spline ? 1 : 0);
const std::vector<VelocityPoint>& pts = s.contour.points();
putLE(out, static_cast<std::uint32_t>(pts.size()));
for (const VelocityPoint& pt : pts) {
putLE(out, doubleToBits(pt.velocity));
putLE(out, doubleToBits(pt.value));
out.push_back(pt.hard ? 1 : 0);
}
}
// The hard flags of an already-written velocity curve: count + one byte per point.
void putHardFlags(std::vector<std::uint8_t>& out, const VelocityCurve& curve) {
const std::vector<VelocityPoint>& pts = curve.points();
putLE(out, static_cast<std::uint32_t>(pts.size()));
for (const VelocityPoint& pt : pts) out.push_back(pt.hard ? 1 : 0);
}
// A stored AHD's five doubles, in one order shared by every AHD on the wire.
void putAhd(std::vector<std::uint8_t>& out, const AhdSeconds& a) {
putLE(out, doubleToBits(a.attackSeconds));
putLE(out, doubleToBits(a.decaySeconds));
putLE(out, doubleToBits(a.holdFraction));
putLE(out, doubleToBits(a.attackCurve));
putLE(out, doubleToBits(a.decayCurve));
}
// THE lift of the retired Trigger fade pair onto the AHD that replaced it: Attack takes the
// fade-in, Decay the fade-out, Hold the whole remainder — so a zero fade-out lands Decay = 0
// and the abrupt end an old instance could express stays representable. The seconds conversion
// and its rate-mismatch bound, and the two fitted exponents, are documented in
// component_state_io.h. A v10-or-newer blob overwrites all five fields from its own tail.
void liftTriggerFades(std::int64_t fadeInFrames, std::int64_t fadeOutFrames, double projectRate,
AhdSeconds& out) {
const double rate = projectRate > 0.0 ? projectRate : 1.0;
out.attackSeconds = static_cast<double>(fadeInFrames > 0 ? fadeInFrames : 0) / rate;
out.decaySeconds = static_cast<double>(fadeOutFrames > 0 ? fadeOutFrames : 0) / rate;
out.holdFraction = 1.0;
out.attackCurve = kTriggerFadeLiftAttackCurve;
out.decayCurve = kTriggerFadeLiftDecayCurve;
}
// A wire double whose consumers assume a domain they cannot check: the seconds fields reach
// resolvePlay's static_cast<std::int64_t> and peakSemitones reaches the bake's pow() and the
// voice's ratio multiply — both undefined or poisoning on NaN. Degrades to the field's own
// construction default, so a damaged blob loses that field rather than the record.
double finiteOr(double v, double fallback) { return std::isfinite(v) ? v : fallback; }
// A root-note override off the wire. Clamped HERE and not only where it is consumed: planBake
// clamps the note it renders at into MIDI range while the SampleData keeps the raw override as
// its root, and the two disagreeing makes the read rate something other than 1 — which
// mis-sizes the bake's window in the truncating direction.
int clampMidiNote(int note) { return (std::max)(0, (std::min)(127, note)); }
// Read the play tail (v5 shape onward) into `p`. Shared by the legacy zone reader and the
// v8 single-record reader so the two can never disagree about field order.
void readSecondsPlayTail(ByteReader& r, InstrumentParams& p, double projectRate) {
const PlaySeconds fallback; // the construction defaults, read rather than restated
p.play.playMode = (r.u8() != 0) ? PlayMode::Trigger : PlayMode::Gate;
p.play.adsr.holdSeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.holdSeconds);
p.play.trigger.lengthFraction =
finiteOr(bitsToDouble(r.u64()), fallback.trigger.lengthFraction);
const std::int64_t fadeIn = r.i64();
const std::int64_t fadeOut = r.i64();
liftTriggerFades(fadeIn, fadeOut, projectRate, p.play.trigAhd);
p.play.pitchEngine = (r.u8() != 0) ? PitchEngine::Preserve : PitchEngine::Varispeed;
p.play.pitchEnv.enabled = (r.u8() != 0);
p.play.pitchEnv.shape.attackSeconds =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.shape.attackSeconds);
p.play.pitchEnv.shape.decaySeconds =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.shape.decaySeconds);
p.play.pitchEnv.peakSemitones =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.peakSemitones);
p.play.adsr.attackSeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.attackSeconds);
p.play.adsr.decaySeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.decaySeconds);
p.play.adsr.sustainLevel = finiteOr(bitsToDouble(r.u64()), fallback.adsr.sustainLevel);
p.play.adsr.releaseSeconds = finiteOr(bitsToDouble(r.u64()), fallback.adsr.releaseSeconds);
}
// Read a velocity curve tail into `curve`, interpreting its y values in `domain` — the domain
// is not on the wire, it is a property of the slot. fromPoints repairs the X-order/endpoint
// invariant defensively; a truncated read leaves `curve` at whatever default it came in with.
void readCurveTail(ByteReader& r, VelocityCurve& curve,
reasampler::instrument::engine::CurveDomain domain) {
const std::uint32_t ptCount = r.u32();
std::vector<VelocityPoint> pts;
// Bound the reserve to what the blob can hold (16 bytes/point) so a corrupt huge count
// can't trigger a giant allocation before the bounded reads fail.
const std::size_t remaining = r.bytes.size() > r.pos ? r.bytes.size() - r.pos : 0;
pts.reserve(std::min(static_cast<std::size_t>(ptCount), remaining / 16));
for (std::uint32_t i = 0; i < ptCount && r.ok; ++i) {
const double vel = bitsToDouble(r.u64());
const double value = bitsToDouble(r.u64());
// A NaN velocity breaks fromPoints' stable_sort (not a strict weak ordering with NaN
// present); a NaN value reaches the RT eval's multiply. Same non-finite-falls-back-to-0
// guard as every other wire double this codec reads.
pts.push_back(VelocityPoint{std::isfinite(vel) ? vel : 0.0,
std::isfinite(value) ? value : 0.0});
}
if (r.ok) {
curve = reasampler::instrument::engine::VelocityCurve::fromPoints(std::move(pts), domain);
}
}
// Read a spline EG. A truncated read leaves `s` at its Staged/default-contour construction
// value, which is what makes a pre-v13 blob play exactly as it did.
void readSplineEnv(ByteReader& r, SplineEnv& s) {
const bool spline = (r.u8() != 0);
const std::uint32_t ptCount = r.u32();
std::vector<VelocityPoint> pts;
// Bound the reserve to what the blob can hold (17 bytes/point) so a corrupt huge count
// can't trigger a giant allocation before the bounded reads fail.
const std::size_t remaining = r.bytes.size() > r.pos ? r.bytes.size() - r.pos : 0;
pts.reserve(std::min(static_cast<std::size_t>(ptCount), remaining / 17));
for (std::uint32_t i = 0; i < ptCount && r.ok; ++i) {
const double x = bitsToDouble(r.u64());
const double y = bitsToDouble(r.u64());
const bool hard = (r.u8() != 0);
// Same NaN guard as readCurveTail: an x NaN breaks fromPoints' sort, a y NaN reaches
// SplineCursor::eval's multiply into the per-sample amp gain.
pts.push_back(VelocityPoint{std::isfinite(x) ? x : 0.0, std::isfinite(y) ? y : 0.0, hard});
}
if (!r.ok) return;
s.mode = spline ? EnvMode::Spline : EnvMode::Staged;
if (pts.size() < 2) {
// fromPoints' own sub-2-point fallback is flat()/zero() by DOMAIN — the neutral velocity
// curve response (a full-open gate). A spline EG's documented neutral is y = 1 - x
// instead, so a malformed/short block substitutes that rather than fromPoints' default.
s.contour = VelocityCurve::rampDown();
return;
}
s.contour = VelocityCurve::fromPoints(std::move(pts),
reasampler::instrument::engine::CurveDomain::Unipolar);
}
// A block whose declared length overruns what the blob still holds has no realignment point:
// every byte after it belongs to a block that was truncated, so a later tail that reads them
// as its own gets an ARBITRARY value — and a tail that clamps (the bake Hold does) turns that
// into a legal-looking fabrication rather than an obvious one. Draining is what makes the
// stream's end honest: each later tail then reads past it and degrades to absent through its
// own revive, while the record that parsed cleanly ahead of the damage survives.
void drainUnaligned(ByteReader& r) { r.pos = r.bytes.size(); }
// Apply a hard-flag tail to an already-read velocity curve. A count that disagrees with the
// curve fromPoints actually produced — including an out-of-bounds or truncated one — is
// dropped rather than applied to shifted knots, and the whole params record parsed ahead of
// this tail survives (component_state_io.h's documented promise): if THIS call is what tripped
// r.ok (a truncated count field), it is revived before returning. An r.ok already false on
// entry (an earlier, unrelated field genuinely truncated) is left alone — that failure is not
// this tail's to forgive.
void readHardFlags(ByteReader& r, VelocityCurve& curve) {
const bool enteredOk = r.ok;
const std::uint32_t count = r.u32();
if (!r.ok) {
if (enteredOk) r.ok = true; // a truncated count field: nothing to apply
return;
}
const std::size_t remaining = r.bytes.size() > r.pos ? r.bytes.size() - r.pos : 0;
if (count > remaining) {
drainUnaligned(r); // the flags this count promised are not all there
return;
}
std::vector<std::uint8_t> flags;
flags.reserve(count);
for (std::uint32_t i = 0; i < count; ++i) flags.push_back(r.u8());
if (flags.size() != curve.size()) return;
for (std::size_t i = 0; i < flags.size(); ++i) curve.setHard(i, flags[i] != 0);
}
// THE shared ending for every appended tail past the hard flags: revive, then DRAIN. Both
// halves are load-bearing and neither is optional.
//
// Revive, because these tails reach no audio path — a blob truncated inside one must cost
// that field alone and not reset the whole record that parsed cleanly ahead of it. An r.ok
// already false on entry (an earlier, unrelated field genuinely truncated) is left alone;
// that failure is not this tail's to forgive.
//
// Drain, because a FAILED read does not advance the cursor. The bytes it rejected are still
// sitting there for the NEXT tail to consume as its own — a truncated Hold whose two
// surviving exponent bytes arrive at the limiter byte reads back as ENABLED. Reviving without
// draining does not degrade to absent; it fabricates. Every tail added after this one must
// end here too.
//
// Returns true when the caller must abandon its field.
bool reviveTruncatedTail(ByteReader& r, bool enteredOk) {
if (r.ok) return false;
if (enteredOk) r.ok = true;
drainUnaligned(r);
return true;
}
// Read the v14 bake Hold.
void readBakeHold(ByteReader& r, InstrumentParams& p) {
const bool enteredOk = r.ok;
const std::int32_t exponent = r.i32();
const std::uint8_t modifier = r.u8();
if (reviveTruncatedTail(r, enteredOk)) return;
// makeDivision clamps BOTH fields, so a corrupt pair becomes the nearest legal rung
// rather than an unrepresentable one — never a memcpy into the type.
p.bakeHold = note::makeDivision(exponent, static_cast<note::DivisionModifier>(modifier));
}
// Read the v15 limiter enable. Bypassed is what a truncation means and what the field already
// holds, so a missing byte costs nothing beyond the enable itself.
void readLimiterEnable(ByteReader& r, InstrumentParams& p) {
const bool enteredOk = r.ok;
const std::uint8_t flag = r.u8();
if (reviveTruncatedTail(r, enteredOk)) return;
p.limiterEnabled = (flag != 0);
}
// Read the v16 rate + pitch-offset pair. A truncation, or either value unusable, leaves the
// neutral the field already holds — unity rate, no offset — which is exactly what a pre-v16
// blob means and what every instance before them played.
//
// The two guards are deliberately DIFFERENT. Rate is RESOLVED through clampStretchRate rather
// than merely admitted: the stretcher owns its range, so a second copy of the bounds here could
// disagree with it — but a value that only playback clamped would re-serialize out of range and
// leave the stored value disagreeing with the needle, and with the host normalization once the
// instrument reports parameters. Finiteness stays a separate test in front of it, because
// corruption is not an out-of-range value: an infinite rate degrades to the neutral, where a
// merely-too-fast one clamps to the bound. The offset gets a real range test instead, because
// nothing downstream bounds it: it reaches 2^(x/12) and then a read increment, and a wild
// exponent there is UB on the per-sample path.
void readRateAndPitchOffset(ByteReader& r, InstrumentParams& p) {
const bool enteredOk = r.ok;
const double rate = bitsToDouble(r.u64());
const double offset = bitsToDouble(r.u64());
if (reviveTruncatedTail(r, enteredOk)) return;
if (std::isfinite(rate)) p.play.playRate = engine::clampStretchRate(rate);
// The throw is kVelocityPitchRangeSemitones — the SAME +/-24 the pitch envelope's depth and
// the velocity->pitch curve speak (play_params.h), reached directly rather than through the
// deck's alias of it.
if (std::isfinite(offset) && offset >= -kVelocityPitchRangeSemitones &&
offset <= kVelocityPitchRangeSemitones) {
p.play.pitchOffsetSemitones = offset;
}
}
// Read the v9 filter tail into `p`. A blob that stops short leaves the off/neutral default,
// which is what makes a v8 blob play bit-identically under the new codec. The curve reads as
// bipolar at EVERY version — a pre-v12 blob's y values are already valid bipolar ones, so its
// v12 domain re-tag needs no version branch (see component_state_io.h).
void readFilterTail(ByteReader& r, InstrumentParams& p) {
const FilterSeconds fallback; // the construction defaults, read rather than restated
FilterSeconds& f = p.play.filter;
f.enabled = (r.u8() != 0);
f.settings.cutoffNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.resonanceNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.morphNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.driveNorm = static_cast<float>(bitsToDouble(r.u64()));
f.settings.morphLaw = (r.u8() != 0) ? engine::filter::MorphLaw::HighNotchLow
: engine::filter::MorphLaw::HighBandLow;
// Same non-finite-falls-back-to-neutral guard as the v8 master gain above: these three
// reach Voice::tickFilterCutoff's clamp compares and a static_cast<int>, both UB on NaN.
double modAmount = bitsToDouble(r.u64());
double velAmount = bitsToDouble(r.u64());
double keyTrack = bitsToDouble(r.u64());
f.modAmount = std::isfinite(modAmount) ? modAmount : 0.0;
f.velAmount = std::isfinite(velAmount) ? velAmount : 0.0;
f.keyTrack = std::isfinite(keyTrack) ? keyTrack : 0.0;
f.env.attackSeconds = finiteOr(bitsToDouble(r.u64()), fallback.env.attackSeconds);
f.env.holdSeconds = finiteOr(bitsToDouble(r.u64()), fallback.env.holdSeconds);
f.env.decaySeconds = finiteOr(bitsToDouble(r.u64()), fallback.env.decaySeconds);
f.env.sustainLevel = finiteOr(bitsToDouble(r.u64()), fallback.env.sustainLevel);
f.env.releaseSeconds = finiteOr(bitsToDouble(r.u64()), fallback.env.releaseSeconds);
readCurveTail(r, f.velocityCurve, reasampler::instrument::engine::CurveDomain::Bipolar);
}
// A curve exponent off the wire. A corrupt/non-finite value degrades to the LINEAR neutral
// rather than to an endpoint: neutral is the one exponent that cannot change how a stage
// sounds, so a damaged blob loses the shaping instead of inventing one.
double readCurveExponent(ByteReader& r) {
const double v = bitsToDouble(r.u64());
return std::isfinite(v) ? reasampler::util::clampCurve(v) : reasampler::util::kCurveNeutral;
}
void readAhd(ByteReader& r, AhdSeconds& a) {
// attackSeconds/decaySeconds reach resolvePlay's static_cast<std::int64_t> (sample_map.cpp)
// unguarded — UB on NaN, and on a large-enough finite value — so a corrupt/non-finite wire
// value degrades to 0 seconds rather than reaching that cast, the same guard readSecondsPlayTail
// and the v9 filter tail already apply to their own wall-clock fields.
const double attack = bitsToDouble(r.u64());
const double decay = bitsToDouble(r.u64());
a.attackSeconds = std::isfinite(attack) ? attack : 0.0;
a.decaySeconds = std::isfinite(decay) ? decay : 0.0;
const double frac = bitsToDouble(r.u64());
a.holdFraction = std::isfinite(frac) ? frac : 0.0;
a.attackCurve = readCurveExponent(r);
a.decayCurve = readCurveExponent(r);
}
// Read the v10 staged-curve tail into `p`. A blob that stops short leaves the neutral
// exponents and the fade-lifted Trigger AHD, which is what makes a v9 blob play as before.
void readCurveStageTail(ByteReader& r, InstrumentParams& p) {
PlaySeconds& pp = p.play;
pp.adsr.attackCurve = readCurveExponent(r);
pp.adsr.decayCurve = readCurveExponent(r);
pp.adsr.releaseCurve = readCurveExponent(r);
readAhd(r, pp.trigAhd);
const double pitchHold = bitsToDouble(r.u64());
pp.pitchEnv.shape.holdFraction = std::isfinite(pitchHold) ? pitchHold : 0.0;
pp.pitchEnv.shape.attackCurve = readCurveExponent(r);
pp.pitchEnv.shape.decayCurve = readCurveExponent(r);
pp.filter.env.attackCurve = readCurveExponent(r);
pp.filter.env.decayCurve = readCurveExponent(r);
pp.filter.env.releaseCurve = readCurveExponent(r);
readAhd(r, pp.filter.trigEnv);
}
// Read a RETIRED zone-list payload (v1..v7) and adopt zone ONE. Every zone is still parsed
// so the truncation ladder behaves exactly as it did — a record that fails mid-way stops the
// walk — but only the first zone's capture and parameters survive; the rest drop, touching
// no file and no bank entry.
// `pv` is the already-consumed payload version (0 = v1, no marker). `projectRate` converts
// the LEGACY v3 wall-clock frame counts to seconds (seconds = frames / projectRate); v5+
// blobs carry seconds directly and need no rate.
PayloadRead readLegacyZonePayload(ByteReader& r, std::uint32_t pv, double projectRate) {
PayloadRead out;
const bool extended = (pv >= 2); // v2+: the loop/start tail is present
const bool legacyV3Play = (pv == 3); // legacy play tail, wall-clock in nominal frames
const bool secondsPlay = (pv >= 5); // v5+: full play params, wall-clock in seconds
const bool keyTrackTail = (pv >= 6); // v6+: keyTrack scalar
const bool curveTail = (pv >= 7); // v7+: velocity->amp curve, appended last
const std::uint32_t count = r.u32();
bool adopted = false;
for (std::uint32_t i = 0; i < count && r.ok; ++i) {
// A v1/v2 payload (no play tail) lifts to the product defaults (Gate + Preserve +
// tier-0 AHDSR seconds) — InstrumentParams' own construction defaults.
InstrumentParams p;
std::string sampleId;
const std::uint32_t idLen = r.u32();
sampleId = r.str(idLen);
r.i32(); // lowNote — the retired key range; read to keep the record walk aligned
r.i32(); // highNote
const std::uint8_t hasOverride = r.u8();
if (hasOverride) p.rootOverride = clampMidiNote(r.i32());
if (extended) {
const std::uint8_t hasLoop = r.u8();
if (hasLoop) {
SampleLoop lp;
lp.hasLoop = (r.u8() != 0);
lp.start = r.i64();
lp.end = r.i64();
p.loopOverride = lp;
}
const std::uint8_t hasStart = r.u8();
if (hasStart) p.startPoint = r.i64();
}
if (legacyV3Play) {
// LEGACY v3 play tail. Wall-clock fields (hold, pitchEnv A/D) were written as
// frames -> divide by `projectRate` to reach seconds. Trigger %-length + fades
// are source-timeline, read as-is. A/D/S/R are ABSENT in v3 -> keep the defaults.
assert(projectRate > 0.0 && "readLegacyZonePayload: projectRate must be > 0 for v3 lift");
const double liftRate = projectRate > 0.0 ? projectRate : 1.0; // avoids div-by-zero; assert fires first
const PlaySeconds fallback; // same guard as readSecondsPlayTail's peer fields
p.play.playMode = (r.u8() != 0) ? PlayMode::Trigger : PlayMode::Gate;
p.play.adsr.holdSeconds = static_cast<double>(r.i64()) / liftRate;
p.play.trigger.lengthFraction =
finiteOr(bitsToDouble(r.u64()), fallback.trigger.lengthFraction);
const std::int64_t fadeIn = r.i64();
const std::int64_t fadeOut = r.i64();
liftTriggerFades(fadeIn, fadeOut, liftRate, p.play.trigAhd);
p.play.pitchEngine = (r.u8() != 0) ? PitchEngine::Preserve : PitchEngine::Varispeed;
p.play.pitchEnv.enabled = (r.u8() != 0);
p.play.pitchEnv.shape.attackSeconds = static_cast<double>(r.i64()) / liftRate;
p.play.pitchEnv.shape.decaySeconds = static_cast<double>(r.i64()) / liftRate;
p.play.pitchEnv.peakSemitones =
finiteOr(bitsToDouble(r.u64()), fallback.pitchEnv.peakSemitones);
} else if (secondsPlay) {
readSecondsPlayTail(r, p, projectRate);
}
// A pre-v6 payload leaves keyTrack = 1.0 (100% ET), so an already-saved instance
// repitches BIT-IDENTICALLY. A pre-v7 payload leaves VelocityCurve::flat(). A NaN
// reaches keyTrackedRatio -> baseRatio_ -> readPos_'s per-sample cast (voice.h) — the
// same guard the v8+ single-record reader applies to its own keyTrack below.
if (keyTrackTail) p.keyTrack = finiteOr(bitsToDouble(r.u64()), InstrumentParams{}.keyTrack);
if (curveTail) {
readCurveTail(r, p.velocityCurve,
reasampler::instrument::engine::CurveDomain::Unipolar);
}
// Payload version 4 (a branch-only frames tail, never shipped) and any unknown pv
// leave the seconds product defaults on p.play.
if (!r.ok) break; // truncated mid-record -> keep what parsed cleanly, drop the rest
if (!adopted) {
out.params = std::move(p);
out.adoptedSampleId = std::move(sampleId);
adopted = true;
}
}
return out;
}
} // namespace
// Append the params payload: marker + version + the single parameter record. Always emits
// the CURRENT payload version; the marker precedes the record so any reader detects the
// shape independent of the envelope version (see component_state_io.h).
void putParamsPayload(std::vector<std::uint8_t>& out, const InstrumentParams& p) {
putLE(out, kParamsFormatMarker);
putLE(out, kParamsPayloadVersion);
putOverrides(out, p);
// Play params: wall-clock times are SECONDS (doubles); trigger %-length + fades stay
// source frames/fraction. Field order matches the header's v5 tail spec verbatim.
const PlaySeconds& pp = p.play;
out.push_back(pp.playMode == PlayMode::Trigger ? 1 : 0);
putLE(out, doubleToBits(pp.adsr.holdSeconds)); // wall-clock seconds
putLE(out, doubleToBits(pp.trigger.lengthFraction)); // fraction
// The retired fade pair's two frozen slots (see the header): the shape stays, the values
// moved into the Trigger AHD tail below.
putLE(out, asU64(std::int64_t{0}));
putLE(out, asU64(std::int64_t{0}));
out.push_back(pp.pitchEngine == PitchEngine::Preserve ? 1 : 0);
out.push_back(pp.pitchEnv.enabled ? 1 : 0);
putLE(out, doubleToBits(pp.pitchEnv.shape.attackSeconds)); // wall-clock seconds
putLE(out, doubleToBits(pp.pitchEnv.shape.decaySeconds)); // wall-clock seconds
putLE(out, doubleToBits(pp.pitchEnv.peakSemitones)); // depth
// Full AHDSR A/D/S/R tail — wall-clock SECONDS (sustainLevel is a level).
putLE(out, doubleToBits(pp.adsr.attackSeconds));
putLE(out, doubleToBits(pp.adsr.decaySeconds));
putLE(out, doubleToBits(pp.adsr.sustainLevel));
putLE(out, doubleToBits(pp.adsr.releaseSeconds));
// Key-tracking scalar (1.0 = 100% ET).
putLE(out, doubleToBits(p.keyTrack));
// The velocity->amp transfer curve: 4-byte LE control-point count, then per point
// velocity + amp as doubles (endpoints included, so N >= 2).
putCurve(out, p.velocityCurve);
// v9: the per-voice filter tail. The module's floats widen to doubles on the wire so the
// whole payload stays one numeric shape.
const FilterSeconds& f = pp.filter;
out.push_back(f.enabled ? 1 : 0);
putLE(out, doubleToBits(static_cast<double>(f.settings.cutoffNorm)));
putLE(out, doubleToBits(static_cast<double>(f.settings.resonanceNorm)));
putLE(out, doubleToBits(static_cast<double>(f.settings.morphNorm)));
putLE(out, doubleToBits(static_cast<double>(f.settings.driveNorm)));
out.push_back(f.settings.morphLaw == engine::filter::MorphLaw::HighNotchLow ? 1 : 0);
putLE(out, doubleToBits(f.modAmount));
putLE(out, doubleToBits(f.velAmount));
putLE(out, doubleToBits(f.keyTrack));
putLE(out, doubleToBits(f.env.attackSeconds));
putLE(out, doubleToBits(f.env.holdSeconds));
putLE(out, doubleToBits(f.env.decaySeconds));
putLE(out, doubleToBits(f.env.sustainLevel));
putLE(out, doubleToBits(f.env.releaseSeconds));
putCurve(out, f.velocityCurve);
// v10: the staged-curve tail.
putLE(out, doubleToBits(pp.adsr.attackCurve));
putLE(out, doubleToBits(pp.adsr.decayCurve));
putLE(out, doubleToBits(pp.adsr.releaseCurve));
putAhd(out, pp.trigAhd);
putLE(out, doubleToBits(pp.pitchEnv.shape.holdFraction));
putLE(out, doubleToBits(pp.pitchEnv.shape.attackCurve));
putLE(out, doubleToBits(pp.pitchEnv.shape.decayCurve));
putLE(out, doubleToBits(f.env.attackCurve));
putLE(out, doubleToBits(f.env.decayCurve));
putLE(out, doubleToBits(f.env.releaseCurve));
putAhd(out, f.trigEnv);
// v11: the loop crossfade, in SOURCE frames.
putLE(out, asU64(p.loopCrossfadeFrames));
// v12: the velocity->pitch curve.
putCurve(out, pp.pitchVelocityCurve);
// v13: the dual Staged/Spline state — the three contours, then the hard flags the three
// frozen velocity-curve blocks above had no room for.
putSplineEnv(out, pp.ampSpline);
putSplineEnv(out, pp.pitchSpline);
putSplineEnv(out, pp.filterSpline);
putHardFlags(out, p.velocityCurve);
putHardFlags(out, f.velocityCurve);
putHardFlags(out, pp.pitchVelocityCurve);
// v14: the bake's Hold division, as its {quarterExponent, modifier} pair — never its
// picker index, which the ladder gaining a rung would silently re-map.
putLE(out, static_cast<std::uint32_t>(
static_cast<std::int32_t>(p.bakeHold.quarterExponent())));
out.push_back(static_cast<std::uint8_t>(p.bakeHold.modifier()));
// v15: the master-bus limiter enable.
out.push_back(p.limiterEnabled ? 1 : 0);
// v16: the playback rate (a ratio) and the baseline pitch offset (semitones), both rate-free.
putLE(out, doubleToBits(pp.playRate));
putLE(out, doubleToBits(pp.pitchOffsetSemitones));
}
// Read whichever payload shape follows: the single-record shape (v8 onward, growing by
// appended tails), or a retired v1..v7 zone list (adopting zone one). An absent marker means
// v1 (a plain small zone count).
PayloadRead readParamsPayload(ByteReader& r, double projectRate) {
std::uint32_t pv = 0; // 0 = v1, no marker
if (r.peekU32() == kParamsFormatMarker) {
r.u32(); // consume the marker
pv = r.u32(); // payload version
}
if (pv < kParamsSingleRecordVersion) return readLegacyZonePayload(r, pv, projectRate);
PayloadRead out;
InstrumentParams& p = out.params;
const std::uint8_t hasRoot = r.u8();
if (hasRoot) p.rootOverride = clampMidiNote(r.i32());
const std::uint8_t hasLoop = r.u8();
if (hasLoop) {
SampleLoop lp;
lp.hasLoop = (r.u8() != 0);
lp.start = r.i64();
lp.end = r.i64();
p.loopOverride = lp;
}
const std::uint8_t hasStart = r.u8();
if (hasStart) p.startPoint = r.i64();
readSecondsPlayTail(r, p, projectRate);
// NaN reaches keyTrackedRatio (voice.h) -> baseRatio_ -> readPos_'s per-sample
// static_cast<std::int64_t> — UB on the per-sample path. Guarded here, codec-side, so
// that path needs no check of its own.
p.keyTrack = finiteOr(bitsToDouble(r.u64()), InstrumentParams{}.keyTrack);
readCurveTail(r, p.velocityCurve, reasampler::instrument::engine::CurveDomain::Unipolar);
if (pv >= kParamsFilterVersion) readFilterTail(r, p);
if (pv >= kParamsCurveVersion) readCurveStageTail(r, p);
if (pv >= kParamsLoopVersion) {
// A negative fade is meaningless and would reach resolveLoop's clamp anyway; refusing
// it here keeps the parameter set itself sane for the editor that reads it back.
const std::int64_t xf = r.i64();
p.loopCrossfadeFrames = xf > 0 ? xf : 0;
}
if (pv >= kParamsVelocityVersion) {
readCurveTail(r, p.play.pitchVelocityCurve,
reasampler::instrument::engine::CurveDomain::Bipolar);
}
if (pv >= kParamsSplineVersion) {
readSplineEnv(r, p.play.ampSpline);
readSplineEnv(r, p.play.pitchSpline);
readSplineEnv(r, p.play.filterSpline);
readHardFlags(r, p.velocityCurve);
readHardFlags(r, p.play.filter.velocityCurve);
readHardFlags(r, p.play.pitchVelocityCurve);
}
if (pv >= kParamsBakeHoldVersion) readBakeHold(r, p);
if (pv >= kParamsLimiterVersion) readLimiterEnable(r, p);
if (pv >= kParamsRateVersion) readRateAndPitchOffset(r, p);
// A truncated record leaves whatever parsed plus construction defaults for the rest —
// the same degrade-don't-throw contract the zone ladder always had.
if (!r.ok) return PayloadRead{};
return out;
}
} // namespace reasampler::instrument::map
+41
View File
@@ -0,0 +1,41 @@
#pragma once
// params_payload — the params-payload half of the ComponentState codec, split from the
// ENVELOPE half on the axis the format itself already has: the payload carries its OWN
// version and grows independently of the envelope's, so the two version ladders are two
// responsibilities. An INTERNAL seam of `component_state_io` — the public entry points stay
// serialize/deserializeComponentState; nothing outside the codec calls these.
//
// The format ladder (payload v1..v16) is documented in component_state_io.h, which stays its
// one home. EVERY wire format is FROZEN.
#include <cstdint>
#include <string>
#include <vector>
// The payload's version constants and the prose ladder stay in component_state_io.h, their
// one home — this half implements them rather than re-declaring them.
#include "core/instrument/map/component_state_io.h"
#include "core/wire/bytes.h" // ByteReader
namespace reasampler::instrument::map {
// What a payload read yields. `adoptedSampleId` is non-empty ONLY for a retired zone-list
// payload that carried at least one zone: the first zone's capture, which supersedes the
// envelope's selection id (see the adoption rule in component_state_io.h).
struct PayloadRead {
InstrumentParams params;
std::string adoptedSampleId;
};
// Append the params payload: marker + version + the single parameter record. Always emits
// the CURRENT payload version; the marker precedes the record so any reader detects the
// shape independent of the envelope version.
void putParamsPayload(std::vector<std::uint8_t>& out, const InstrumentParams& p);
// Read whichever payload shape follows: the single-record shape (v8 onward, growing by
// appended tails), or a retired v1..v7 zone list (adopting zone one). An absent marker means
// v1 (a plain small zone count). `projectRate` converts the LEGACY v3 wall-clock frame counts
// and the retired Trigger fade pair to the seconds domain at the read boundary.
PayloadRead readParamsPayload(reasampler::wire::ByteReader& r, double projectRate);
} // namespace reasampler::instrument::map

Some files were not shown because too many files have changed in this diff Show More