diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml
index b7ea6f60b..57c7646df 100644
--- a/.github/workflows/p1-windows.yml
+++ b/.github/workflows/p1-windows.yml
@@ -145,6 +145,15 @@ jobs:
run: |
g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math tests/builtin_channel_compressor_test.cpp -o "$RUNNER_TEMP/native-compressor-core-test"
"$RUNNER_TEMP/native-compressor-core-test"
+ # Catch DSP recovery failures in seconds, before any exact-SHA MSVC
+ # qualification. Portable core tests intentionally exclude JUCE.
+ - name: Vocal Throw portable native C++ DSP / beat relock regression
+ if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/arson-vocal-throw-') }}
+ run: |
+ g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math tests/native_music_tempo_test.cpp -o "$RUNNER_TEMP/native-music-tempo-test"
+ "$RUNNER_TEMP/native-music-tempo-test"
+ g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math tests/builtin_vocal_throw_test.cpp -o "$RUNNER_TEMP/native-vocal-throw-test"
+ "$RUNNER_TEMP/native-vocal-throw-test"
windows-build:
name: Windows MSVC / realtime CTest
needs: quick
diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml
index a57b32e9e..605c61924 100644
--- a/.github/workflows/ui-smoke.yml
+++ b/.github/workflows/ui-smoke.yml
@@ -109,6 +109,7 @@ jobs:
node --check site/preview-v2/assets/mixer-native-compressor.js
node --check site/preview-v2/assets/mixer-native-harmony.js
python tests/native_harmony_assembly_test.py
+ node --check site/preview-v2/assets/mixer-native-vocal-throw.js
python tests/native_peq_assembly_test.py
python tests/approved_operator_ux_smoke.py
python scripts/build_ui_css.py --check
@@ -128,6 +129,32 @@ jobs:
- name: Block incomplete product release only when preparing product review
if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft && startsWith(github.head_ref, 'integration/product-') }}
run: node scripts/check_console_puzzle.mjs --release
+ vocal-throw-preview:
+ name: Vocal Throw native editor desktop/mobile Chromium FAT
+ needs: quick
+ if: ${{ github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feature/arson-vocal-throw-') || startsWith(github.head_ref, 'integration/arson-vocal-throw-')) }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - name: Install Chromium for targeted Vocal Throw UI
+ run: |
+ python -m pip install playwright
+ python -m playwright install --with-deps chromium
+ - name: Check exact mixer picker, native ACK and editor in desktop/mobile
+ run: python tests/approved_native_vocal_throw_smoke.py
+ - name: Keep compact editor screenshot evidence
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: ArSonMix-Vocal-Throw-Desktop-Mobile-${{ github.run_id }}
+ path: arsonmix-vocal-throw-*.png
+ if-no-files-found: ignore
+ retention-days: 7
+
operator-ux-fat:
name: Operator UX real Chromium / native-assembled GUI (5 viewports)
needs: quick
diff --git a/CMakeLists.txt b/CMakeLists.txt
index eb89c69c9..2b30080e4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -433,6 +433,30 @@ if(BUILD_TESTING)
COMMAND ARMixNativeCompressorLifecycleTests)
add_dependencies(ARMixMixerRoutingTests ARMixNativeCompressorLifecycleTests)
+ add_executable(ARMixNativeVocalThrowTests tests/builtin_vocal_throw_test.cpp
+ engine/builtin_fx/VocalThrow.h)
+ target_compile_features(ARMixNativeVocalThrowTests PRIVATE cxx_std_20)
+ add_test(NAME NativeVocalThrowPhraseCaptureManualAutoAndNoHeap COMMAND ARMixNativeVocalThrowTests)
+ add_dependencies(ARMixMixerRoutingTests ARMixNativeVocalThrowTests)
+ # A stopped ASIO callback must not execute old, UI-rejected THROW cues
+ # on resume. Exercise the real JUCE processor and its SPSC completion.
+ juce_add_console_app(ARMixVocalThrowCancelTests PRODUCT_NAME
+ "ArSonMix Vocal Throw Expired Cue Safety Tests")
+ target_sources(ARMixVocalThrowCancelTests PRIVATE
+ tests/native_vocal_throw_cancel_test.cpp
+ engine/builtin_fx/VocalThrowProcessor.h)
+ target_link_libraries(ARMixVocalThrowCancelTests PRIVATE
+ juce::juce_audio_processors juce::juce_recommended_config_flags)
+ target_compile_features(ARMixVocalThrowCancelTests PRIVATE cxx_std_20)
+ add_test(NAME NativeVocalThrowExpiredCueCancellation COMMAND ARMixVocalThrowCancelTests)
+ add_dependencies(ARMixMixerRoutingTests ARMixVocalThrowCancelTests)
+ add_executable(ARMixNativeMusicTempoTests tests/native_music_tempo_test.cpp
+ engine/core/NativeMusicTempoMonitor.h)
+ target_compile_features(ARMixNativeMusicTempoTests PRIVATE cxx_std_20)
+ add_test(NAME NativeMusicTempoSourceOnsetsAndFallback COMMAND ARMixNativeMusicTempoTests)
+ add_dependencies(ARMixMixerRoutingTests ARMixNativeMusicTempoTests)
+
+
add_executable(ARMixNativeMasterLoudnessTests tests/native_master_loudness_test.cpp engine/dsp/NativeMasterLoudness.h)
target_compile_features(ARMixNativeMasterLoudnessTests PRIVATE cxx_std_20)
add_test(NAME P1KMeasuredNativeBS1770StereoAnd4xTruePeak COMMAND ARMixNativeMasterLoudnessTests)
diff --git a/docs/ARSON_VOCAL_THROW_BEAT_GRID_M3_20261109.md b/docs/ARSON_VOCAL_THROW_BEAT_GRID_M3_20261109.md
new file mode 100644
index 000000000..6cb0512fb
--- /dev/null
+++ b/docs/ARSON_VOCAL_THROW_BEAT_GRID_M3_20261109.md
@@ -0,0 +1,45 @@
+# ArSon Vocal Throw M3 — native music beat-phase quantized echo
+
+**Branch:** `feature/arson-vocal-throw-phase-grid-m3-20261109`; builds on draft M2 PR #474 (which builds on M1 PR #469). Product issue #473. **Not a hardware-certified stage release.**
+
+## What changed
+
+A stable BPM alone cannot locate the *beat boundary*. M3 shares the existing native ChannelId audio renderer's monotonically increasing callback frame counter with its built-in FX processing, then quantizes **only the newly scheduled echo** when the selected MUSIC ChannelId has a credible beat-phase estimate.
+
+```
+ONE native ASIO/JUCE ChannelId render (epoch + graph revision)
+ beginAudioBlock(frames) -> monotonic native sample-frame start
+ NativeBeatFrameScope (thread-local, callback-only and restored on exit)
+ pre-FX MUSIC ChannelId -> 10ms nonmutating energy frames
+ each summary carries its exact observed audio end-frame (within 10ms)
+ SPSC -> existing control timer -> BPM, onset anchor, phase confidence
+ CONTROL publishes BPM + sample-frame anchor + epoch/revision to FX
+ -> atomic version-fenced snapshot (one read attempt per callback)
+ VOICE FX on SAME callback/thread
+ -> read versioned tempo + scoped native frame origin
+ -> if source/epoch/revision invalid: accepted Manual/TAP
+ -> if BPM stable, beat phase weak: BPM-derived interval, NO grid
+ -> if BPM and phase credible: snapshot anchor & interval at THROW
+ -> freeze voice with existing two-tail bounded PCM
+ -> schedule next echo at FIRST native music grid point >=
+ intended (phrase end + musical subdivision), with correction
+ bounded to ONE subdivision and zero change to dry PCM
+ -> already sounding echo tails retain frozen timing across BPM/graph edits
+```
+
+### Realtime invariant
+No new audio callback, dynamic allocation, model inference, FFT, lock, waiting, JS audio, logging or file I/O from the callback. Channel PCM enters one mixer graph and is never processed twice. The timing scope is a trivially copied thread-local struct, no global audio clock thread. Tempo/phase inference (up to 121 BPM candidates) is CONTROL-only. Packed atomic scalar fields are protected by an even/odd version; the audio callback makes **one** bounded read attempt and immediately falls back on inconsistency.
+
+### Confidence and fallback
+- BPM confidence and beat-phase confidence are independent. A musical onset beat grid is used only if a majority of percussive onset strength agrees on a single pulse lattice.
+- Ambiguous rhythmic patterns remain **AUTO BPM · BPM only**, not a speculative grid. A missing source or stale graph becomes **Manual / TAP** without losing the accepted preset.
+- A 10ms analysis window means onset time has approximately up to one window of inherent beat-position uncertainty, even though *subsequent scheduling* uses exact callback sample indices. This is not sample-perfect transient detection.
+- Phase quantization is measured against **pre-FX** selected music PCM, not against a fully latency-compensated external performance clock. Vendor VST3 latency, off-beat percussion, compressed music, drift, sample-rate changes, ASIO callback reentrancy and sparse backing must still pass field tests.
+
+### Automated acceptance
+- Native DSP unit test verifies an actual frozen phrase's first echo is scheduled on the music frame lattice and remains there after transport disappears, compared with Manual/TAP quarter-note fallback; repeats at 64/128-frame PCM chunks with callback heap forbidden.
+- Native graph PCM test stamps the selected music ChannelId from one authoritative callback at variable 64+36 sample chunks, verifies anchored BPM/phase confidence at 72/95/120/160 BPM, one block-clock scope, frame counter continuity after a graph revision, and restoration of callback-only context.
+- Desktop/mobile Chromium smoke explicitly distinguishes a native ACKed source's **BPM only** from **BEAT GRID** status. No user-facing opt-in or extra monitor/arm step.
+
+### Deferred release qualification
+Physical ASIO 64/128 frame loops at 44.1/48/96 kHz; on-stage singer/backing leakage, syncopated 4/4 and half/double-time, large FX PDC, dropout/replug, fade/no-click audition, real CPU/xrun vs bypass, and sustained stress still require field evidence. Do not merge while the PR chain and these safety gates remain unresolved.
diff --git a/docs/ARSON_VOCAL_THROW_MUSIC_TEMPO_M2_20261108.md b/docs/ARSON_VOCAL_THROW_MUSIC_TEMPO_M2_20261108.md
new file mode 100644
index 000000000..088665a93
--- /dev/null
+++ b/docs/ARSON_VOCAL_THROW_MUSIC_TEMPO_M2_20261108.md
@@ -0,0 +1,45 @@
+# ArSon Vocal Throw M2 — Native Music Channel Tempo Detection
+
+**Status:** implementation and qualification draft, stacked on Vocal Throw M1 PR #469. M1 green head `4db384851e6f6378cca4fd037b744c98bd1f0ba3`; M2 is PR #474 and tracks issue #473.
+
+## Signal authority
+
+```
+Authoritative ChannelId native PCM graph, single JUCE / ASIO callback
+ MUSIC ChannelId selected explicitly by singer/operator
+ -> PRE-FX non-mutating read-only music tap
+ -> 10ms stereo absolute-energy summary, bounded SPSC
+ -> existing 12Hz JUCE control timer: onset search + BPM confidence
+ -> accepted tempo precomputed into sample intervals, CONTROL only
+ -> per-VocalThrow atomic pending interval
+ -> next dry/vocal PCM callback copies interval BEFORE any THROW
+ -> new frozen vocal echo gets music interval, old tails keep prior schedule
+ VOICE ChannelId -> VocalThrow (no added dry PCM delay) -> WIRE/BUS/MAIN
+```
+
+**AUDIO callback contract:** no memory allocations, FFT, file I/O, logging, locks, networking, JS DSP, or new audio threads. Only the explicitly selected source channel's input stereo samples are summarized; every other channel skips the per-sample music tap. Existing JUCE callback remains the only audio authority. Core audio buffers and retained FX leases remain with the native graph.
+
+**CONTROL contract:** only an accepted `ChannelId` with input / GROUP / FX_RETURN role and an actually scheduled PCM lane is a permissible tempo source. The native FX editor validates both its own vocal insert instance and source identity, device epoch and graph revision. Monitor/MAIN and the vocal channel itself are not accepted. On a valid structural graph recompile, an existing source ID is rebound with a new analysis generation; if absent or stale, the music clock is disabled, and Vocal Throw falls back to its saved BPM or TAP tempo.
+
+## Detector
+
+- A 10ms energy onset, 80ms transient refractory and adaptive floor reject a simple repeated rise from a sustained note.
+- Bounded pairwise onset-period candidate scoring (60–180 BPM), with penalty for octave half/double candidates, three consistent estimates and confidence threshold.
+- Native readback distinguishes **AUTO BPM locked**, **Listening**, and **Manual/TAP fallback**. A silence period exceeding 3.2s resets lock.
+- UI conveys confidence as measured by estimator; this number is not field-certified reliability.
+
+**Explicit limitations:** Music/onset BPM estimation does not provide sample-perfect beat-phase grid alignment. A recent transient anchor is retained for diagnostics only; it is not used as a globally compensated sample clock. Syncopated and heavily compressed music, live mic bleed, time-signature changes, half/double-time ambiguity and device-specific ASIO timing remain hardware field gates. Tempo selection is ephemeral song-wide, not yet persisted per Show. The fallback path always remains audible on the singer's dry stream.
+
+## Qualification evidence
+
+- Prior M1 Windows MSVC/JUCE: 63/63 CTest on exact SHA `4db384851e6f6378cca4fd037b744c98bd1f0ba3`.
+- M2 Windows MSVC/JUCE: 64/64 CTest, including `NativeMusicTempoSourceOnsetsAndFallback`, on exact SHA `cce63231da52f69e6789873ecc406adba69aa1cb`. See [Actions run 42498186748](https://github.com/masarray/arsonmix/actions/runs/42498186748).
+- Chromium FAT M2 native Vocal Throw picker, music source ACK, BPM readback and stale instance handling passed on same SHA.
+- Later hardening: inbound tempo sampled before same-callback THROW and reset on plugin audio reprepare; corresponding regression checks for manual fallback and active tail interval stability. Qualification on the later SHA must be checked independently.
+- Deterministic PCM: 72, 95, 120, 160 BPM; non-vocal source, stale revision, source change, dropout, default fallback. The CTest calls the *actual* native publisher to verify a music signal traverses the accepted graph, not only the isolated estimator.
+
+**Not qualified:** physical ASIO 64/128 frame load at 44.1/48/96 kHz; prolonged simultaneous singer/backing test; live beat-grid sync / stereo echo hearing test; WASAPI secondary stream callback load; long-run xrun/restart and voice-music bleed reliability. Green CI is necessary but not sufficient for release.
+
+## Next DSP/UX milestone
+
+Prove stable beat phase with a source-specific latency-compensated anchor; handle half/double-time ambiguity with confidence floor and long-window hysteresis; permit song/Show fallback preference; add footswitch mapping and live capture metrics without callback work. Until then label UI as estimated **AUTO BPM** rather than **sample-accurate beat quantization**.
diff --git a/docs/ARSON_VOCAL_THROW_NATIVE_20261108.md b/docs/ARSON_VOCAL_THROW_NATIVE_20261108.md
new file mode 100644
index 000000000..e39acc139
--- /dev/null
+++ b/docs/ARSON_VOCAL_THROW_NATIVE_20261108.md
@@ -0,0 +1,54 @@
+# ArSon Vocal Throw — native phrase-aware live delay
+
+**Status: functional prototype on a separate feature branch; not a certified live-performance release.**
+
+This is a first-class native ChannelId insert in ArSonMix's single JUCE PCM render graph, not a second audio callback, browser-generated sound or independent DAW.
+
+## Implemented
+
+- **Manual:** rolling ring buffer holds up to 1.5 seconds of the most recent vocal. THROW captures a word or phrase and schedules up to six decaying repeats. Two independent tail voices allow a subsequent phrase to overlap an existing echo instead of cutting it.
+- **Auto:** energy envelope, minimum voice duration, silence threshold and cooldown detect the end of a sung phrase without letting the wet echo re-trigger itself.
+- **Hybrid (default):** phrase-end automation and manual cue together, with manual-cue suppression of a subsequent auto event for the same phrase.
+- **Tempo:** BPM entry (60-200), TAP BPM, quarter/eighth/dotted-eighth/half note subdivisions. Interval timing is in native samples at the actual device rate.
+- **Mix:** direct dry input with zero added samples, stereo echo, decay, short fades, smoothed wet edits, and ducking while the singer is active. A bounded active-tap gain normalizer prevents dense repeats/overlapping phrases from amplifying the wet bus simply because taps stack; dry is never attenuated.
+- **Real-time:** all rolling/frozen buffers are allocated off-callback; a fixed maximum 24-stereo-frame-per-sample capture copy budget per active tail avoids a single large callback memcpy. Contiguous copy chunks eliminate per-frame modulo, and the ring write cursor rolls over without division. A lock-free SPSC transfers host settings and manual cue to the audio callback. Callback never allocates/logs/locks.
+- **Identity & persistence:** stable native catalog ID; ChannelId, device epoch, graph revision, and insert instance fencing. DSP completed ACK and later readback precede accepted display. Schema-versioned 48-byte AVTH settings blob validated during Show restore; audio capture and tails are not persisted.
+- **UX:** a compact FX editor inside the exact approved /preview/ mixer; presets in header, uniform power/close, BPM/note/repeat, THROW, TAP and collapsible advanced controls. One shared FX stylesheet.
+
+## Architecture
+
+Hardware input → ChannelId mixer strip → upstream EQ/Compressor/VST3 → VocalThrowProcessor → downstream inserts → fader/pan → WIRE/BUS/MAIN → hardware output.
+
+Core files: engine/builtin_fx/VocalThrow.h (DSP), VocalThrowProcessor.h (JUCE), src/LiveAudioEngine.h (graph install), src/Main.cpp (validated command/readback), src/NativeMixerSessionFxRestore.h (versioned state), scripts/compose_native_peq.py (one picker), web/approved-native-bridge.js (real insert), site/preview-v2/assets/mixer-native-vocal-throw.js (controls only).
+
+## Tests / qualification
+
+The ARMixNativeVocalThrowTests CTest covers zero-added-sample dry, tempo divisions, captured stereo echoes after manual cue, auto-end detection and no self-trigger, bad parameter rejection, 8/44.1/48 kHz sample rates and a global allocator guard around realtime processing. Additional deterministic tests cover 8/48/96 kHz two-tail preservation during a second cue, a full two-tail pool reporting cue refusal rather than overwriting a running phrase, suppression of manual/auto double-cues, and peak containment of dense six-tap echoes. Python native picker/compiled-gui tests enforce no extra mixer screen and real-ACK event names.
+
+Before shipping: exact-SHA Windows MSVC + CTest, actual approved /preview/ Chromium screenshots, ASIO 64/128-frame stress at 44.1/48/96 kHz, live singer audition, device restart, bypass/tail behavior, and Show restore.
+
+## Explicit limitations
+
+1. **Automatic BPM analysis from the music/backing bus is not yet implemented.** Auto currently means automatic vocal phrase-end trigger, not auto-estimated music tempo. BPM is entered or TAP-derived. Full beat tracking requires an independent music-bus feed, beat confidence and phase tracking.
+2. Voice end detector uses an adjustable energy-envelope heuristic, not linguistic speech recognition or a trained singing model. Breaths, falsetto and microphone bleed can cause false cues.
+3. No MIDI footswitch binding, more than two simultaneous phrase layers, stretchable echo phrases, global music BPM transport integration, or direct song-snapshot binding in this milestone. When both frozen-tail slots are busy, further THROW requests are rejected (native ACK reports not applied) rather than cutting an existing musical phrase.
+4. Green quick CI is not equivalent to real Windows native compilation or ASIO device certification. Zero reported PDC applies only to the FX DSP's dry path; end-to-end hardware/driver latency and callback CPU load still require ASIO measurements.
+5. Existing channel routing and independent secondary audio clock remain authoritative; the FX insert makes no new claims about unresolved WIRE/SOURCE ONLY issues.
+
+## Field test
+
+Insert ID armix.builtin.vocal-throw.v1 into real ChannelId vocal strip; confirm graph ACK; sing “atau tidak” then press THROW at 72/95/120/160 BPM; try Auto with varying held notes and short breaths; toggle bypass while dry vocal remains direct; change device/quantum and reject stale instance requests. Compare physical ASIO callback xruns, stereo/feedback, click-free fades and singer subjective quality.
+
+## 2026-11-08 — performance and musicality hardening audit
+
+Audit of the first native revision identified these concrete risks:
+- Triggering a second phrase reset `playing_` and overwrote the frozen buffer of the first tail; audible repeat discontinuity was possible.
+- The original capture copied 24 frames via two per-frame ring modulo operations; this was an avoidable callback hot-path cost.
+- Hybrid manual cues could be followed by auto-trigger of the same sung phrase, producing unintended double repeats.
+- Wet level changed immediately on edits; close-spaced six-tap feedback-like echoes could produce unnecessarily high wet peaks.
+
+Hardening: two independent frozen voices, bounded cue admission (explicit rejection if full), bulk contiguous ring capture, write cursor without modulo, continuous smoothing of wet/duck gain, current-phrase manual suppression of auto replay, and peak-aware wet overlap normalization. Silence counters are now saturating for multi-hour sessions.
+
+**Realtime caveats:** No heap, locks, logging or file operations in `processStereo`, `throwNow`, or parameter application. Worst-case processing still includes two simultaneous 24-frame copy budgets, and an up-to-twelve-tap mix; on low-buffer ASIO that requires measured xrun and callback-duration evidence, not just source inspection. Extra frozen buffer memory is allocated only on channels with this effect. A full two-voice pool intentionally rejects a new cue, so polyphony and cue policies should be evaluated with vocalist/operator tests.
+
+**Next release gates:** exact-SHA MSVC CTest and native JUCE compile, 64/128-frame ASIO at 44.1/48/96 kHz, overnight stability and lifecycle/device-rate restart, phrase-ending listening sessions including breath/bleed/falsetto, bypass/re-enable and FX graph routing, and latency/xrun baseline comparisons versus bypass. Beat tracking from an isolated backing/music bus (confidence, phase and half/double-time hysteresis) remains a separate architecture milestone, not an already delivered feature.
diff --git a/engine/builtin_fx/BuiltInFxCatalog.h b/engine/builtin_fx/BuiltInFxCatalog.h
index bbc6b83d3..67db030e2 100644
--- a/engine/builtin_fx/BuiltInFxCatalog.h
+++ b/engine/builtin_fx/BuiltInFxCatalog.h
@@ -11,6 +11,7 @@
namespace armix::builtin_fx {
inline constexpr std::string_view channelEqId = "armix.builtin.channel-eq.v1";
inline constexpr std::string_view channelCompressorId = "armix.builtin.channel-compressor.v1";
+inline constexpr std::string_view vocalThrowId = "armix.builtin.vocal-throw.v1";
enum class FilterKind : std::uint8_t { highPass, lowShelf, bell, highShelf, lowPass };
enum class Slope : std::uint8_t { db12 = 12, db24 = 24 };
diff --git a/engine/builtin_fx/VocalThrow.h b/engine/builtin_fx/VocalThrow.h
new file mode 100644
index 000000000..aa3cfbd1b
--- /dev/null
+++ b/engine/builtin_fx/VocalThrow.h
@@ -0,0 +1,370 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+#pragma once
+#include
+#include
+#include
+#include
+#include
+#include
+
+// ArSon Vocal Throw. One audio-thread owner; preparation allocates on CONTROL.
+// The microphone's dry PCM is never buffered or delayed. A rolling history
+// freezes the last word/phrase for tempo-spaced stereo echoes. All samples and
+// triggers run on the existing native ChannelId PCM callback, never WebView.
+namespace armix::builtin_fx {
+struct VocalThrowSettings final {
+ int mode=2; // 0 manual, 1 automatic, 2 hybrid
+ float bpm=120.f; // explicit/host or tap BPM (not claimed auto-detected)
+ int division=0; // 0 quarter, 1 eighth, 2 dotted eighth, 3 half
+ int repeats=3;
+ float captureMs=460.f;
+ float silenceMs=220.f;
+ float thresholdDb=-35.f;
+ float wet=.42f;
+ float decay=.55f; // successive repeat amplitude multiplier
+ float ducking=.7f; // suppress echo while lead vocalist is active
+};
+class VocalThrow final {
+public:
+ static constexpr int addedLatencySamples=0;
+ static constexpr int maxRepeats=6;
+ static constexpr float maxCaptureMs=1500.f;
+ struct PreparedEdit {
+ VocalThrowSettings settings{};
+ double sampleRate=0.;
+ std::uint32_t intervalSamples=0, captureSamples=0, silenceSamples=0;
+ float gateLinear=0.f;
+ bool valid=false;
+ };
+ static bool validSettings(const VocalThrowSettings& s) noexcept {
+ return s.mode>=0&&s.mode<=2&&s.division>=0&&s.division<=3&&
+ s.repeats>=1&&s.repeats<=maxRepeats&&
+ std::isfinite(s.bpm)&&s.bpm>=60.f&&s.bpm<=200.f&&
+ std::isfinite(s.captureMs)&&s.captureMs>=80.f&&s.captureMs<=maxCaptureMs&&
+ std::isfinite(s.silenceMs)&&s.silenceMs>=80.f&&s.silenceMs<=900.f&&
+ std::isfinite(s.thresholdDb)&&s.thresholdDb>=-65.f&&s.thresholdDb<=-15.f&&
+ std::isfinite(s.wet)&&s.wet>=0.f&&s.wet<=1.f&&
+ std::isfinite(s.decay)&&s.decay>=.15f&&s.decay<=.9f&&
+ std::isfinite(s.ducking)&&s.ducking>=0.f&&s.ducking<=1.f;
+ }
+ static bool prepareEdit(const VocalThrowSettings& s,double sampleRate,PreparedEdit& out) noexcept {
+ if(!validSettings(s)||!std::isfinite(sampleRate)||
+ sampleRate<8000.||sampleRate>192000.)return false;
+ constexpr std::array beats{{1.,.5,.75,2.}};
+ PreparedEdit next{};
+ next.settings=s;next.sampleRate=sampleRate;
+ next.intervalSamples=std::max(1u,static_cast(
+ std::llround(60.*sampleRate*beats[static_cast(s.division)]/s.bpm)));
+ next.captureSamples=std::max(1u,static_cast(
+ std::llround(sampleRate*s.captureMs/1000.)));
+ next.silenceSamples=std::max(1u,static_cast(
+ std::llround(sampleRate*s.silenceMs/1000.)));
+ next.gateLinear=static_cast(std::pow(10.,s.thresholdDb/20.));
+ next.valid=next.gateLinear>0.f;
+ out=next;return true;
+ }
+ // CONTROL thread only, before publishing the insert. Maximum memory is
+ // bounded by the selected device rate and independent of song duration.
+ bool prepare(double rate) {
+ PreparedEdit packet{};
+ if(!prepareEdit(VocalThrowSettings{},rate,packet))return false;
+ const auto historyFrames=static_cast(std::ceil(rate*2.5))+4;
+ const auto freezeFrames=static_cast(std::ceil(rate*maxCaptureMs/1000.))+4;
+ if(historyFrames>500000||freezeFrames>300000)return false;
+ historyL_.assign(historyFrames,0.f);
+ historyR_.assign(historyFrames,0.f);
+ // Two independent tails: new phrases never overwrite an active echo.
+ for(auto& voice:voices_) {
+ voice.freezeL.assign(freezeFrames,0.f);
+ voice.freezeR.assign(freezeFrames,0.f);
+ }
+ rate_=rate;ready_=true;settings_=packet;reset();
+ return true;
+ }
+ // CONTROL, before publication. No vector resizing during state restore.
+ bool resetUnpublished(const VocalThrowSettings& settings) noexcept {
+ PreparedEdit next{};
+ if(!ready_||!prepareEdit(settings,rate_,next))return false;
+ settings_=next;reset();return true;
+ }
+ // AUDIO: trivially copied, completely validated, no heap/locks.
+ bool applyPrepared(const PreparedEdit& edit) noexcept {
+ if(!ready_||!edit.valid||edit.sampleRate!=rate_||
+ !validSettings(edit.settings)||edit.intervalSamples==0||
+ edit.captureSamples==0||edit.captureSamples>voices_[0].freezeL.size()||
+ edit.silenceSamples==0)return false;
+ settings_=edit;return true;
+ }
+ // AUDIO: incoming transport interval is already computed on CONTROL.
+ // A zero interval explicitly falls back to accepted song/TAP BPM. Each
+ // frozen tail keeps its interval when a backing track changes tempo.
+ void setMusicIntervalSamples(std::uint32_t samples) noexcept {
+ musicIntervalSamples_=samples;
+ gridValid_=false; // BPM-only mode never claims a measured beat grid.
+ }
+ // AUDIO: the JUCE insert reads the one accepted ChannelId block clock
+ // and control-prepared music onset anchor. Onsets are observed in 10ms
+ // windows, so beat-phase is approximate (not sample-perfect detection).
+ // The local->graph sample mapping is taken before every FX processing
+ // block; it works even when the insert was added after playback began.
+ void setMusicBeatGrid(std::uint32_t intervalSamples,
+ std::uint64_t anchorFrame,
+ std::uint64_t blockStartFrame,
+ bool locked) noexcept {
+ musicIntervalSamples_=locked?intervalSamples:0;
+ gridValid_=locked&&intervalSamples>0;
+ gridAnchorFrame_=anchorFrame;
+ gridBlockStartFrame_=blockStartFrame;
+ gridLocalStartFrame_=clock_;
+ }
+ // AUDIO: triggers the most recent word/phrase, preferring the latest
+ // vocal end if the singer stopped within the last 700 ms.
+ bool throwNow() noexcept {
+ if(!ready_||recorded_==0||lastSoundEnd_==0||clock_(rate_*.7);
+ if(clock_-lastSoundEnd_>recent)return false; // reject stale/silent cues
+ const bool ended=quiet_>0;
+ // Auto already threw this finished phrase. A late manual click must
+ // not produce a second identical echo in Hybrid mode.
+ if(ended && lastSoundEnd_==autoTriggeredPhraseEnd_)return false;
+ const bool accepted=freezeAt(ended?lastSoundEnd_:clock_);
+ if(accepted)manualInCurrentPhrase_=true;
+ return accepted;
+ }
+ void processStereo(float* left,float* right,std::size_t frames) noexcept {
+ if(!ready_||!left||!right)return;
+ const bool mono=left==right;
+ const std::uint32_t maxQuiet=static_cast(rate_);
+ const std::uint32_t phraseGap=static_cast(rate_*.06);
+ const std::uint32_t minVoice=static_cast(rate_*.08);
+ for(std::size_t i=0;ienvelope_?envAttack_:envRelease_;
+ envelope_=coeff*envelope_+(1.f-coeff)*peak;
+ if(envelope_<1.0e-20f)envelope_=0.f;
+ const bool singing=envelope_>=settings_.gateLinear;
+ if(singing) {
+ if(quiet_>phraseGap) {
+ voiced_=0;
+ manualInCurrentPhrase_=false; // genuinely new sung phrase
+ autoTriggeredPhraseEnd_=0;
+ }
+ quiet_=0;
+ voiced_=std::min(voiced_+1,maxQuiet);
+ lastSoundEnd_=clock_;
+ if(voiced_>=minVoice)armed_=true;
+ } else {
+ if(quiet_=settings_.silenceSamples) {
+ if(settings_.settings.mode!=0 && !manualInCurrentPhrase_
+ && clock_>=nextAutoEligible_) {
+ if(freezeAt(lastSoundEnd_)) {
+ autoTriggeredPhraseEnd_=lastSoundEnd_;
+ nextAutoEligible_=clock_+
+ static_cast(rate_*.4);
+ }
+ }
+ armed_=false;
+ }
+ }
+ float echoL=0.f,echoR=0.f,activeTapGain=0.f;
+ for(auto& voice:voices_) {
+ if(voice.copying)copyFrozenChunk(voice);
+ if(!voice.playing)continue;
+ // Fixed six-tap limit, constant time; voice owns its capture
+ // and scheduling packet even when BPM changes mid-tail.
+ for(int tap=0;tap(tap);
+ const std::uint64_t start=voice.repeatStarts[slot];
+ if(clock_<=start)continue;
+ const std::uint64_t offset=clock_-start-1;
+ if(offset>=voice.freezeCount)continue;
+ float ramp=1.f;
+ if(voice.edgeSamples>0) {
+ ramp=std::min(ramp,static_cast(offset)/
+ static_cast(voice.edgeSamples));
+ ramp=std::min(ramp,static_cast(voice.freezeCount-offset-1)/
+ static_cast(voice.edgeSamples));
+ }
+ const auto p=static_cast(offset);
+ const float gain=voice.repeatGains[slot]*std::max(0.f,ramp);
+ echoL+=voice.freezeL[p]*gain;echoR+=voice.freezeR[p]*gain;
+ activeTapGain+=gain;
+ }
+ const auto end=voice.repeatStarts[
+ static_cast(voice.active.settings.repeats-1)]
+ +voice.freezeCount;
+ if(clock_>end)voice.playing=false;
+ }
+ // Slew wet level and ducking independently to avoid zipper
+ // noise on rapid GUI edits and the next vocal entrance.
+ const float duckTarget=singing?1.f-settings_.settings.ducking:1.f;
+ duck_=duck_*duckCoeff_+duckTarget*(1.f-duckCoeff_);
+ wetSmoothed_=wetSmoothed_*duckCoeff_+
+ settings_.settings.wet*(1.f-duckCoeff_);
+ // Concert-safe overlap headroom: many closely spaced taps,
+ // including two phrases, must not multiply the wet peak by 6x.
+ // No attenuation for ordinary nonoverlapping delays.
+ const float echoGain=(wetSmoothed_*duck_)/
+ std::max(1.f,activeTapGain*wetSmoothed_);
+ left[i]=dryL+echoL*echoGain;
+ if(!mono)right[i]=dryR+echoR*echoGain;
+ }
+ }
+ // AUDIO only: discard historical vocalist PCM and pending echo tails
+ // when the FX finishes bypassing or is re-enabled. Do not clear vector
+ // storage here: 192kHz history could cost ~480,000 writes in one ASIO
+ // callback. recorded_=0 fences stale samples until truly overwritten.
+ // Retain the accepted settings, sample clock and completed cue counter.
+ void invalidateCaptureHistory() noexcept {
+ recorded_=0;
+ lastSoundEnd_=nextAutoEligible_=autoTriggeredPhraseEnd_=0;
+ voiced_=quiet_=0;
+ armed_=manualInCurrentPhrase_=false;
+ envelope_=0.f;
+ for(auto& voice:voices_) {
+ voice.copying=false;voice.playing=false;
+ voice.freezeCount=0;voice.copyIndex=0;
+ }
+ }
+ [[nodiscard]] bool ready() const noexcept{return ready_;}
+ [[nodiscard]] VocalThrowSettings settingsForTests() const noexcept{return settings_.settings;}
+ [[nodiscard]] bool echoActive() const noexcept{
+ for(const auto& voice:voices_)if(voice.playing)return true;
+ return false;
+ }
+ [[nodiscard]] unsigned throwCount() const noexcept{return throwCount_;}
+ [[nodiscard]] double sampleRate() const noexcept{return rate_;}
+private:
+ struct TailVoice final {
+ std::vector freezeL,freezeR;
+ std::array repeatStarts{};
+ std::array repeatGains{};
+ PreparedEdit active{};
+ std::uint64_t copyEnd=0,freezeCount=0;
+ std::size_t copyIndex=0,sourceIndex=0;
+ std::uint32_t edgeSamples=0;
+ std::uint64_t gridAnchorFrame=0,gridCueFrame=0,gridCueLocal=0;
+ bool gridValid=false;
+ bool copying=false,playing=false;
+ };
+ bool freezeAt(std::uint64_t end) noexcept {
+ if(end==0||end>clock_||historyL_.empty())return false;
+ // Bounded polyphony: do not cut or overwrite an existing phrase.
+ // A full pool rejects a cue (and reports this via native ACK).
+ TailVoice* slot=nullptr;
+ for(auto& voice:voices_) {
+ if(!voice.playing&&!voice.copying){slot=&voice;break;}
+ }
+ if(!slot)return false;
+ const auto available=std::min(end,recorded_);
+ const auto count=std::min(available,settings_.captureSamples);
+ if(count(rate_*.025))return false;
+ slot->copyEnd=end;
+ slot->freezeCount=count;
+ slot->copyIndex=0;
+ slot->sourceIndex=static_cast((end-count)%historyL_.size());
+ slot->edgeSamples=static_cast(rate_*.004);
+ slot->active=settings_;
+ if(musicIntervalSamples_)
+ slot->active.intervalSamples=musicIntervalSamples_;
+ // Freeze the same accepted beat grid as the captured phrase.
+ // Later tempo changes, stale epochs or an unplugged MUSIC WIRE do
+ // not re-time an already accepted echo tail.
+ slot->gridValid=gridValid_;
+ slot->gridAnchorFrame=gridAnchorFrame_;
+ slot->gridCueFrame=gridBlockStartFrame_+
+ (gridValid_?clock_-gridLocalStartFrame_:0);
+ slot->gridCueLocal=clock_;
+ slot->copying=true;
+ ++throwCount_;
+ return true;
+ }
+ void copyFrozenChunk(TailVoice& voice) noexcept {
+ // A fixed 24-frame budget each sample. Contiguous bulk copying
+ // replaces per-frame division/modulo in the former implementation.
+ const std::size_t left=static_cast(voice.freezeCount)-voice.copyIndex;
+ const std::size_t n=std::min({24,left,
+ historyL_.size()-voice.sourceIndex});
+ std::copy_n(historyL_.data()+voice.sourceIndex,n,
+ voice.freezeL.data()+voice.copyIndex);
+ std::copy_n(historyR_.data()+voice.sourceIndex,n,
+ voice.freezeR.data()+voice.copyIndex);
+ voice.copyIndex+=n;
+ voice.sourceIndex+=n;
+ if(voice.sourceIndex==historyL_.size())voice.sourceIndex=0;
+ if(voice.copyIndex!=voice.freezeCount)return;
+ voice.copying=false;
+ std::uint64_t first=std::max(
+ clock_,voice.copyEnd+voice.active.intervalSamples);
+ if(voice.gridValid && voice.active.intervalSamples &&
+ first>=voice.gridCueLocal) {
+ const auto interval=voice.active.intervalSamples;
+ const auto globalFirst=voice.gridCueFrame+
+ (first-voice.gridCueLocal);
+ // Quantize only the echo onset, never the singer's dry PCM.
+ // Use unsigned arithmetic and bound grid correction to one
+ // subdivision, protecting against a stale/future anchor.
+ if(globalFirst>=voice.gridAnchorFrame) {
+ const auto remainder=
+ (globalFirst-voice.gridAnchorFrame)%interval;
+ if(remainder)first+=interval-remainder;
+ } else if(voice.gridAnchorFrame-globalFirst<=interval) {
+ first+=voice.gridAnchorFrame-globalFirst;
+ }
+ }
+ float amplitude=1.f;
+ for(int tap=0;tap(tap);
+ voice.repeatStarts[slot]=first+
+ static_cast(tap)*voice.active.intervalSamples;
+ voice.repeatGains[slot]=amplitude;
+ amplitude*=voice.active.settings.decay;
+ }
+ voice.playing=true;
+ }
+ void reset() noexcept {
+ clock_=lastSoundEnd_=nextAutoEligible_=autoTriggeredPhraseEnd_=0;
+ recorded_=writeIndex_=0;
+ voiced_=quiet_=0;
+ armed_=manualInCurrentPhrase_=false;
+ envelope_=0.f;duck_=1.f;throwCount_=0;
+ wetSmoothed_=settings_.settings.wet;
+ if(rate_>0) {
+ envAttack_=static_cast(std::exp(-1./(rate_*.004)));
+ envRelease_=static_cast(std::exp(-1./(rate_*.018)));
+ duckCoeff_=static_cast(std::exp(-1./(rate_*.008)));
+ }
+ for(auto& voice:voices_) {
+ voice.copyEnd=voice.freezeCount=0;
+ voice.copyIndex=voice.sourceIndex=0;
+ voice.edgeSamples=0;
+ voice.copying=voice.playing=false;
+ voice.gridValid=false;
+ voice.gridAnchorFrame=voice.gridCueFrame=voice.gridCueLocal=0;
+ voice.repeatStarts.fill(0);voice.repeatGains.fill(0.f);
+ }
+ std::fill(historyL_.begin(),historyL_.end(),0.f);
+ std::fill(historyR_.begin(),historyR_.end(),0.f);
+ }
+ PreparedEdit settings_{};
+ std::vector historyL_,historyR_;
+ std::array voices_{};
+ std::uint64_t clock_=0,lastSoundEnd_=0,nextAutoEligible_=0,autoTriggeredPhraseEnd_=0;
+ std::size_t recorded_=0,writeIndex_=0;
+ std::uint32_t voiced_=0,quiet_=0;
+ float envelope_=0.f,envAttack_=0.f,envRelease_=0.f,duckCoeff_=0.f;
+ float duck_=1.f,wetSmoothed_=.42f;
+ double rate_=0.;
+ std::uint32_t musicIntervalSamples_=0;
+ std::uint64_t gridAnchorFrame_=0,gridBlockStartFrame_=0,gridLocalStartFrame_=0;
+ bool gridValid_=false;
+ unsigned throwCount_=0;
+ bool armed_=false,manualInCurrentPhrase_=false,ready_=false;
+};
+} // namespace armix::builtin_fx
diff --git a/engine/builtin_fx/VocalThrowProcessor.h b/engine/builtin_fx/VocalThrowProcessor.h
new file mode 100644
index 000000000..793d628cd
--- /dev/null
+++ b/engine/builtin_fx/VocalThrowProcessor.h
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+#pragma once
+#include "VocalThrow.h"
+#include "FxSpsc.h"
+#include "../core/RealtimeNativeFxControl.h"
+#include "../core/NativeBeatFrameContext.h"
+#include
+#include
+#include
+#include
+
+// JUCE adapter for the existing ChannelId FX rack. All setting/throw requests
+// are bound to an exact accepted graph instance by ConsoleWindow before they
+// enter the control->audio SPSC. Audio never posts a WebView event.
+namespace armix::builtin_fx {
+class VocalThrowProcessor final : public juce::AudioProcessor,
+ public armix::mixer::RealtimeNativeFxControl {
+public:
+ static constexpr const char* catalogIdentity="armix.builtin.vocal-throw.v1";
+ enum class CommandKind : std::uint8_t { settings, trigger };
+ struct Completion {
+ std::uint64_t requestId=0;
+ VocalThrowSettings settings{};
+ CommandKind kind=CommandKind::settings;
+ bool applied=false;
+ bool bypassed=false;
+ };
+ VocalThrowProcessor()
+ : juce::AudioProcessor(BusesProperties()
+ .withInput("Input",juce::AudioChannelSet::stereo(),true)
+ .withOutput("Output",juce::AudioChannelSet::stereo(),true)) {
+ setLatencySamples(VocalThrow::addedLatencySamples);
+ }
+ const juce::String getName() const override {return "ArSon Vocal Throw";}
+ bool acceptsMidi() const override{return false;}
+ bool producesMidi() const override{return false;}
+ bool isMidiEffect() const override{return false;}
+ double getTailLengthSeconds() const override{return 16.;}
+ int getNumPrograms() override{return 1;}
+ int getCurrentProgram() override{return 0;}
+ void setCurrentProgram(int) override{}
+ const juce::String getProgramName(int) override{return "Current";}
+ void changeProgramName(int,const juce::String&) override{}
+ bool hasEditor() const override{return false;}
+ juce::AudioProcessorEditor* createEditor() override{return nullptr;}
+ bool isBusesLayoutSupported(const BusesLayout& layout) const override {
+ return layout.getMainInputChannelSet()==juce::AudioChannelSet::stereo()&&
+ layout.getMainOutputChannelSet()==juce::AudioChannelSet::stereo();
+ }
+ void prepareToPlay(double sampleRate,int) override {
+ // CONTROL/device thread, only after the prior audio callback stops.
+ // The DSP may already have APPLIED an edit whose completion is still
+ // waiting in the AUDIO->CONTROL SPSC. Rebuilding from accepted_
+ // would silently undo that change on a buffer/device/rate restart.
+ // Preserve the actual last DSP target, just like Compressor does.
+ // Cold Show restore (not yet prepared) takes accepted_ instead.
+ const auto latest=core_.ready()?core_.settingsForTests():accepted_;
+ // Each device epoch gets a new frame clock. A previously accepted
+ // auto BPM interval is invalid if the hardware sample rate changed.
+ lastTempoBpm_=0.f;lastTempoDivision_=-1;
+ bypassed_=false;captureInvalidated_=false;
+ musicInterval_.store(0,std::memory_order_release);
+ ready_=core_.prepare(sampleRate)&&core_.resetUnpublished(latest);
+ if(ready_)rate_=sampleRate;
+ }
+ void releaseResources() override{
+ ready_=false;musicInterval_.store(0,std::memory_order_release);
+ }
+ void processBlock(juce::AudioBuffer& pcm,juce::MidiBuffer&) override {
+ juce::ScopedNoDenormals noDenormals;
+ if(!ready_||pcm.getNumChannels()<2||pcm.getNumSamples()<=0)return;
+ // consumeRealtimeEdits() snapshots the accepted tempo BEFORE any
+ // manual cue in the same block; bypassed inserts use the same path.
+ consumeRealtimeEdits();
+ core_.processStereo(pcm.getWritePointer(0),pcm.getWritePointer(1),
+ static_cast(pcm.getNumSamples()));
+ observedThrows_.store(core_.throwCount(),std::memory_order_relaxed);
+ observedTail_.store(core_.echoActive(),std::memory_order_relaxed);
+ }
+ void processBlock(juce::AudioBuffer&,juce::MidiBuffer&) override{}
+ void onRealtimeBypass(bool requested,bool fully) noexcept override {
+ // Called by the single native render owner before any FX edits or
+ // PCM in this block. Preserve a playing tail through fade-out; clear
+ // only after full bypass, or on any re-enable (including quick flips).
+ const bool clear=(requested&&fully&&!captureInvalidated_) ||
+ (!requested&&bypassed_);
+ if(clear&&ready_) {
+ core_.invalidateCaptureHistory();
+ observedTail_.store(false,std::memory_order_relaxed);
+ }
+ if(requested&&fully)captureInvalidated_=true;
+ if(!requested)captureInvalidated_=false;
+ bypassed_=requested;
+ }
+ void consumeRealtimeEdits() noexcept override {
+ if(!ready_)return;
+ // One bounded attempt, never spin in ASIO. The native PCM callback
+ // is the ONLY owner of a valid block sample clock. A stale epoch,
+ // graph revision, or torn control publication falls back to TAP.
+ const auto block=armix::mixer::NativeBeatFrameScope::current();
+ const auto v0=gridVersion_.load(std::memory_order_acquire);
+ bool valid=block.valid && (v0&1U)==0U;
+ std::uint64_t anchor=0;
+ std::uint32_t interval=0;
+ if(valid) {
+ const auto epoch=gridEpoch_.load(std::memory_order_relaxed);
+ const auto revision=gridRevision_.load(std::memory_order_relaxed);
+ anchor=gridAnchor_.load(std::memory_order_relaxed);
+ interval=musicInterval_.load(std::memory_order_relaxed);
+ const auto v1=gridVersion_.load(std::memory_order_acquire);
+ valid=v0==v1 && block.epoch==epoch &&
+ block.revision==revision && interval>0;
+ }
+ // Low-confidence music can provide a real BPM while its beat
+ // position is ambiguous. Keep that useful interval, but do NOT
+ // claim grid quantization. If the whole transport is stale/torn,
+ // fall all the way back to accepted Manual/TAP.
+ if(valid&&anchor>0&&anchor<=block.startFrame)
+ core_.setMusicBeatGrid(interval,anchor,block.startFrame,true);
+ else
+ core_.setMusicIntervalSamples(valid?interval:0);
+ Edit e{};
+ if(!done_.canPush()||!commands_.pop(e))return;
+ // CONTROL can reject an expired UI request while ASIO is stopped.
+ // A delayed callback must NEVER play its old vocal cue on resume.
+ // One acquire load and one fixed-size completion; no RT clock/heap.
+ // Multiple UI requests may time out while ASIO is suspended.
+ // A single last-cancelled ID is NOT sufficient: later timeouts
+ // would reactivate earlier queued cues. 32 cancellation slots
+ // cover the 32-entry command FIFO with fixed bounded RT reads.
+ bool expired=false;
+ for(const auto& cancelled:cancelledIds_)
+ expired=expired ||
+ cancelled.load(std::memory_order_acquire)==e.id;
+ const bool blockedTrigger=e.kind==CommandKind::trigger && bypassed_;
+ // Settings are remembered while OFF; performance cues are not
+ // scheduled into a stopped capture clock or revived on rack ON.
+ const bool applied=!expired&&!blockedTrigger &&
+ (e.kind==CommandKind::settings?
+ core_.applyPrepared(e.prepared):core_.throwNow());
+ (void)done_.push({e.id,e.prepared.settings,e.kind,applied,
+ blockedTrigger});
+ }
+ // CONTROL-thread song/auto BPM, deliberately independent of accepted
+ // serialized preset BPM. No queue ACK storm or GUI state overwrite.
+ void publishMusicBpm(float bpm) noexcept {
+ if(!ready_||!std::isfinite(bpm)||bpm<60.f||bpm>200.f) {
+ if(lastTempoBpm_!=0.f) {
+ lastTempoBpm_=0.f;lastTempoDivision_=-1;
+ musicInterval_.store(0,std::memory_order_release);
+ }
+ return;
+ }
+ // The 12Hz message timer may deliver the same accepted tempo many
+ // times. Never recompute power/division or publish redundant atomics.
+ if(lastTempoBpm_==bpm && lastTempoDivision_==accepted_.division)
+ return;
+ auto settings=accepted_;settings.bpm=bpm;
+ VocalThrow::PreparedEdit packet{};
+ const auto valid=VocalThrow::prepareEdit(settings,rate_,packet);
+ lastTempoBpm_=valid?bpm:0.f;
+ lastTempoDivision_=valid?accepted_.division:-1;
+ musicInterval_.store(valid?packet.intervalSamples:0,
+ std::memory_order_release);
+ }
+ // CONTROL ONLY: one source-derived BPM+phase packet is fenced by the
+ // accepted native PCM epoch/revision. The sample-grid anchor comes from
+ // onset timestamped INSIDE the same audio callback (10ms granularity).
+ // Writer is the existing serialized JUCE timer, not a second thread.
+ void publishMusicGrid(float bpm,std::uint64_t anchorFrame,
+ std::uint64_t epoch,
+ std::uint64_t revision) noexcept {
+ gridVersion_.fetch_add(1,std::memory_order_acq_rel); // odd, unstable
+ publishMusicBpm(bpm);
+ gridAnchor_.store(bpm>=60.f&&bpm<=200.f?anchorFrame:0,
+ std::memory_order_relaxed);
+ gridEpoch_.store(epoch,std::memory_order_relaxed);
+ gridRevision_.store(revision,std::memory_order_relaxed);
+ gridVersion_.fetch_add(1,std::memory_order_release); // even, ready
+ }
+ bool queueSettings(const VocalThrowSettings& settings,std::uint64_t id) noexcept {
+ if(!ready_||id==0)return false;
+ Edit e{};e.id=id;e.kind=CommandKind::settings;
+ if(!VocalThrow::prepareEdit(settings,rate_,e.prepared))return false;
+ return commands_.push(e);
+ }
+ bool queueTrigger(std::uint64_t id) noexcept {
+ if(!ready_||id==0)return false;
+ Edit e{};e.id=id;e.kind=CommandKind::trigger;
+ return commands_.push(e);
+ }
+ void cancelQueuedRequest(std::uint64_t id) noexcept {
+ if(id)cancelledIds_[cancelWrite_++ % cancelledIds_.size()].store(
+ id,std::memory_order_release); // CONTROL single writer
+ }
+ bool pollCompletion(Completion& out) noexcept {
+ if(!done_.pop(out))return false;
+ if(out.applied&&out.kind==CommandKind::settings)accepted_=out.settings;
+ return true;
+ }
+ VocalThrowSettings acceptedSettings() const noexcept{return accepted_;}
+ double acceptedSampleRate() const noexcept{return rate_;}
+ unsigned observedThrowCount() const noexcept {
+ return observedThrows_.load(std::memory_order_relaxed);
+ }
+ bool observedTailActive() const noexcept {
+ return observedTail_.load(std::memory_order_relaxed);
+ }
+ bool isReady() const noexcept{return ready_;}
+ void sealForRealtime() noexcept override{published_=true;}
+ bool stateSnapshotQuiescent() const noexcept override{
+ return commands_.empty()&&done_.empty();
+ }
+ void getStateInformation(juce::MemoryBlock& out) override {
+ juce::MemoryOutputStream writer(out,false);
+ writer.writeInt(0x41565448); // AVTH
+ writer.writeInt(1);
+ writer.writeInt(accepted_.mode);
+ writer.writeFloat(accepted_.bpm);
+ writer.writeInt(accepted_.division);
+ writer.writeInt(accepted_.repeats);
+ writer.writeFloat(accepted_.captureMs);
+ writer.writeFloat(accepted_.silenceMs);
+ writer.writeFloat(accepted_.thresholdDb);
+ writer.writeFloat(accepted_.wet);
+ writer.writeFloat(accepted_.decay);
+ writer.writeFloat(accepted_.ducking);
+ }
+ bool restoreUnpublishedState(const void* data,int bytes) {
+ if(published_||!data||bytes!=48||!commands_.empty()||!done_.empty())
+ return false;
+ juce::MemoryInputStream reader(data,static_cast(bytes),false);
+ if(reader.readInt()!=0x41565448||reader.readInt()!=1)return false;
+ VocalThrowSettings s{};
+ s.mode=reader.readInt();
+ s.bpm=reader.readFloat();
+ s.division=reader.readInt();
+ s.repeats=reader.readInt();
+ s.captureMs=reader.readFloat();
+ s.silenceMs=reader.readFloat();
+ s.thresholdDb=reader.readFloat();
+ s.wet=reader.readFloat();
+ s.decay=reader.readFloat();
+ s.ducking=reader.readFloat();
+ if(!reader.isExhausted()||!VocalThrow::validSettings(s))return false;
+ if(ready_&&!core_.resetUnpublished(s))return false;
+ accepted_=s;return true;
+ }
+ void setStateInformation(const void* data,int bytes) override{
+ (void)restoreUnpublishedState(data,bytes);
+ }
+private:
+ struct Edit {
+ std::uint64_t id=0;
+ CommandKind kind=CommandKind::settings;
+ VocalThrow::PreparedEdit prepared{};
+ };
+ VocalThrow core_{};
+ FxSpsc commands_{};
+ FxSpsc done_{};
+ VocalThrowSettings accepted_{};
+ std::atomic observedThrows_{0};
+ std::atomic musicInterval_{0};
+ std::atomic gridVersion_{0},gridAnchor_{0};
+ std::atomic gridEpoch_{0},gridRevision_{0};
+ std::array,32> cancelledIds_{};
+ std::uint32_t cancelWrite_=0; // CONTROL only
+ bool bypassed_=false,captureInvalidated_=false; // AUDIO only
+ std::atomic observedTail_{false};
+ double rate_=0.;
+ float lastTempoBpm_=0.f; // CONTROL only
+ int lastTempoDivision_=-1; // CONTROL only
+ bool ready_=false,published_=false;
+};
+} // namespace armix::builtin_fx
diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h
index f867130fa..18ef3d10c 100644
--- a/engine/core/DynamicNativeSessionPublisher.h
+++ b/engine/core/DynamicNativeSessionPublisher.h
@@ -2,6 +2,8 @@
#pragma once
#include "DynamicPreparedMixerBlock.h"
#include "DynamicConsoleRoutingView.h"
+#include "NativeMusicTempoMonitor.h"
+#include "NativeBeatFrameContext.h"
#include "RealtimeRoutePublisher.h"
#include "RealtimeRenderPermit.h"
#include
@@ -124,8 +126,23 @@ class DynamicNativeSessionPublisher final {
const auto status=publisher_.publish(std::move(next),
expectedRevision,activeDeviceEpoch);
switch(status) {
- case Publisher::Result::applied:
+ case Publisher::Result::applied: {
+ const auto source=musicTempo_.selectedSource();
+ if(source.value) {
+ const auto* published=publisher_.controlPrepared(
+ proposedDeviceEpoch,expectedRevision+1);
+ const auto* channel=published?
+ published->routing.find(source):nullptr;
+ const bool retained=published&&channel&&
+ (channel->role==ChannelRole::input||
+ channel->role==ChannelRole::group||
+ channel->role==ChannelRole::fxReturn)&&
+ published->graph.channelScheduled(source);
+ musicTempo_.onGraphCommitted(proposedDeviceEpoch,
+ expectedRevision,expectedRevision+1,retained);
+ }
report.revision=expectedRevision+1;return report;
+ }
case Publisher::Result::staleDevice:
report.fault=Fault::staleDevice;break;
case Publisher::Result::staleRevision:
@@ -187,11 +204,20 @@ class DynamicNativeSessionPublisher final {
if(!exclusive) {
clearOutputs();return false;
}
+ // One sample domain for all ChannelIds and their FX racks. This
+ // fixed-time callback-local scope also fences bypassed/stale inserts;
+ // no second transport thread, allocation or callback is introduced.
+ const auto startFrame=musicTempo_.beginAudioBlock(deviceEpoch,frames);
+ NativeBeatFrameScope frameScope{deviceEpoch,snap->graphRevision,startFrame};
// Prepared FX takes precedence over the legacy external callback.
// NEVER invoke both: that would double-compress or double-reverb.
// Snapshot ownership pins the M4 instance throughout this callback;
// only control-thread retirement releases the shared owner.
const auto dispatch=[&](ChannelId id,float* l,float* r,int n) noexcept {
+ // Analysis source is the installed ChannelId MUSIC PCM, before
+ // its VST rack; never microphone/echo/main unless explicitly
+ // selected and role-checked on CONTROL. No analysis on AUDIO.
+ musicTempo_.capture(id,l,r,n,snap->deviceEpoch,snap->graphRevision);
const auto& acceptedFx=snap->prepared->fx;
if(acceptedFx.render)
acceptedFx.render(acceptedFx.context,id,l,r,n);
@@ -204,6 +230,25 @@ class DynamicNativeSessionPublisher final {
return ok;
}
+ // CONTROL ONLY: choose an actual active backing input/GROUP/FX return.
+ // Preserve the one authoritative PCM graph and reject stale selectors.
+ bool setMusicTempoSource(std::uint64_t epoch,std::uint64_t revision,
+ ChannelId source,double sampleRate) noexcept {
+ const auto* p=publisher_.controlPrepared(epoch,revision);
+ if(!p)return false;
+ if(source.value) {
+ const auto* ch=p->routing.find(source);
+ if(!ch || (ch->role!=ChannelRole::input &&
+ ch->role!=ChannelRole::group &&
+ ch->role!=ChannelRole::fxReturn) ||
+ !p->graph.channelScheduled(source))return false;
+ }
+ return musicTempo_.select(source,epoch,revision,sampleRate);
+ }
+ NativeMusicTempoMonitor::State pollMusicTempo(std::uint64_t epoch,
+ std::uint64_t revision) noexcept {
+ return musicTempo_.poll(epoch,revision);
+ }
// CONTROL ONLY; pointer is valid until the next structural commit.
// The caller must COPY needed fields before yielding the writer thread.
// Future WebView event serializes this only after native ACK, never draft.
@@ -290,6 +335,7 @@ class DynamicNativeSessionPublisher final {
}
private:
Publisher publisher_;
+ NativeMusicTempoMonitor musicTempo_{};
std::atomic_flag rendering_=ATOMIC_FLAG_INIT;
};
} // namespace armix::mixer
diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h
index 769bc927a..5fd5529ad 100644
--- a/engine/core/LiveChannelFxGraph.h
+++ b/engine/core/LiveChannelFxGraph.h
@@ -116,14 +116,19 @@ class LiveChannelFxGraph final {
}
// G5C: atomic request from control; fade and scratch RT-owned.
// Master rack bypass affects the WET/DRY envelope, never the remembered insert preference.
- bypassFade.request(rackBypassed || bypassRequested.load(std::memory_order_relaxed));
+ const bool requestedBypass=rackBypassed ||
+ bypassRequested.load(std::memory_order_relaxed);
+ bypassFade.request(requestedBypass);
if(samples<=0 || static_cast(samples)>dryLeft.size()) {
juce::FloatVectorOperations::clear(left,std::max(0,samples));
juce::FloatVectorOperations::clear(right,std::max(0,samples));
processing.clear(std::memory_order_release);
return;
}
- // Drain at most one native EQ control edit even while bypassed.
+ if(nativeControl)
+ nativeControl->onRealtimeBypass(requestedBypass,
+ bypassFade.fullyBypassed());
+ // Drain at most one native FX control edit even while bypassed.
// Fully bypassed plugins otherwise never call processBlock, which
// would strand pending GUI commands until users turned them ON.
if(nativeControl && bypassFade.fullyBypassed())
diff --git a/engine/core/NativeBeatFrameContext.h b/engine/core/NativeBeatFrameContext.h
new file mode 100644
index 000000000..c77f79b08
--- /dev/null
+++ b/engine/core/NativeBeatFrameContext.h
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+#pragma once
+#include
+
+// A tiny callback-local sample-clock context, NOT a transport or second
+// callback. The native ChannelId publisher owns the authoritative frame
+// counter. JUCE's built-in VocalThrow reads the same context only while
+// it is rendering as an insert on that callback thread. No heap or locks.
+namespace armix::mixer {
+struct NativeBeatFrameContext final {
+ std::uint64_t epoch=0,revision=0,startFrame=0;
+ bool valid=false;
+};
+inline thread_local NativeBeatFrameContext currentNativeBeatFrame{};
+
+class NativeBeatFrameScope final {
+public:
+ explicit NativeBeatFrameScope(std::uint64_t epoch,std::uint64_t revision,
+ std::uint64_t startFrame) noexcept
+ : previous_(currentNativeBeatFrame) {
+ currentNativeBeatFrame={epoch,revision,startFrame,epoch!=0&&revision!=0};
+ }
+ ~NativeBeatFrameScope() noexcept {currentNativeBeatFrame=previous_;}
+ NativeBeatFrameScope(const NativeBeatFrameScope&)=delete;
+ NativeBeatFrameScope& operator=(const NativeBeatFrameScope&)=delete;
+ static NativeBeatFrameContext current() noexcept {
+ return currentNativeBeatFrame;
+ }
+private:
+ NativeBeatFrameContext previous_{};
+};
+} // namespace armix::mixer
diff --git a/engine/core/NativeMusicTempoMonitor.h b/engine/core/NativeMusicTempoMonitor.h
new file mode 100644
index 000000000..90c8a73ad
--- /dev/null
+++ b/engine/core/NativeMusicTempoMonitor.h
@@ -0,0 +1,436 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+#pragma once
+#include "../builtin_fx/FxSpsc.h"
+#include "DynamicChannelRoster.h"
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+// ArSon M2: source-specific music tempo observation inside the ONE installed
+// ChannelId renderer. AUDIO only summarizes its explicitly selected music
+// channel into 10ms energy frames and pushes a bounded SPSC. CONTROL owns all
+// onset, pulse-correlation and tempo work. This is NOT a second audio engine.
+namespace armix::mixer {
+class MusicTempoEstimator final {
+public:
+ struct Result final {
+ float bpm=0.f,confidence=0.f,phaseConfidence=0.f;
+ bool phaseLocked=false;
+ std::uint64_t beatAnchorTick=0,observationTick=0;
+ // Both are authoritative native callback sample-frame positions.
+ // Onset is quantized by the 10ms summary window; not sample-perfect
+ // transient detection or DAW-wide delay compensation.
+ std::uint64_t beatAnchorFrame=0,observationFrame=0;
+ bool locked=false;
+ // Last CONTROL-only scan's actual tempo-bin comparisons. Enables
+ // deterministic worst-case budget regression without wall-clock
+ // timing or instrumentation on the ASIO callback.
+ std::uint32_t scoringComparisons=0;
+ };
+ void reset() noexcept {
+ previous_=floor_=0.f;count_=write_=0;
+ lastHit_=lastScan_=lastTick_=0;
+ stableCount_=0;candidateBpm_=0;result_={};
+ }
+ void ingest(float energy,std::uint64_t tick,
+ std::uint64_t endingFrame=0) noexcept {
+ if(!std::isfinite(energy)||energy<0.f)energy=0.f;
+ if(lastTick_ && (tick<=lastTick_ || tick-lastTick_>4))reset();
+ lastTick_=tick;
+ floor_+=.005f*(energy-floor_);
+ const float rise=energy-previous_;
+ // Attack transient only; sustained pads/bleed cannot retrigger
+ // every 10ms. 80ms refractory rejects the same drum's ringing.
+ if(tick>=lastHit_+8 && energy>.003f &&
+ rise>std::max(.005f,floor_*.45f)) {
+ hits_[write_]={tick,std::min(1.f,rise),endingFrame};
+ write_=(write_+1)%hits_.size();
+ count_=std::min(count_+1,hits_.size());
+ lastHit_=tick;
+ }
+ previous_=energy;
+ if(endingFrame)result_.observationFrame=endingFrame;
+ if(result_.locked && tick>lastHit_+320) {
+ result_.locked=false;result_.confidence=0.f;
+ result_.phaseLocked=false;result_.phaseConfidence=0.f;
+ candidateBpm_=stableCount_=0;
+ }
+ if(tick>=lastScan_+50) {
+ lastScan_=tick;
+ evaluate();
+ }
+ }
+ Result result() const noexcept {return result_;}
+private:
+ struct Hit {
+ std::uint64_t tick=0;
+ float strength=0.f;
+ std::uint64_t frame=0;
+ };
+ std::array hits_{};
+ std::size_t count_=0,write_=0;
+ std::uint64_t lastHit_=0,lastScan_=0,lastTick_=0;
+ float previous_=0.f,floor_=0.f;
+ int stableCount_=0,candidateBpm_=0;
+ Result result_{};
+
+ void evaluate() noexcept {
+ if(count_<7 || lastTick_<300 || lastTick_>lastHit_+320)return;
+ const auto at=[&](std::size_t i) noexcept ->const Hit& {
+ return hits_[(write_+hits_.size()-count_+i)%hits_.size()];
+ };
+ if(at(count_-1).tick-at(0).tick<300)return;
+ int bestBpm=0;
+ float bestScore=0.f;
+ // CONTROL-owned fixed stack scratch; no heap or unbounded history.
+ // Retain the incumbent candidate's score so a transient half/double
+ // time accent cannot steal an already convincing song clock.
+ std::array candidates{};
+ // CONTROL ONLY, exact-score-preserving sparse candidate search.
+ // The former 121-BPM outer loop re-traversed the complete onset
+ // history for every candidate, adding unpredictable GUI timer work.
+ // Each onset pair can support only nearby BPM bins (<=3 periods).
+ // Enumerate each pair ONCE, derive the mathematically eligible BPM
+ // neighborhood, then use the original round/error/weight formula.
+ // Memory is the same 121-float fixed stack array; no heap, worker,
+ // allocations, callback scheduling or changed confidence threshold.
+ constexpr int minBpm=60,maxBpm=180;
+ constexpr float maxPairTicks=(6000.f/minBpm)*3.08f;
+ std::uint32_t compared=0;
+ for(std::size_t j=1;j1100)continue;
+ for(std::size_t i=j;i-->0;) {
+ const auto& earlier=at(i);
+ const float dt=static_cast(later.tick-earlier.tick);
+ if(dt>maxPairTicks)break;
+ const float strength=std::sqrt(earlier.strength*later.strength);
+ for(int cycles=1;cycles<=3;++cycles) {
+ const float targetBpm=6000.f*cycles/dt;
+ // The original tolerance is max(1.4 ticks, 2.2% of
+ // a multi-beat period). Within 60–180 BPM, its largest
+ // possible candidate separation is <10 BPM. +/-12
+ // therefore cannot discard an original valid score.
+ const int near=static_cast(std::lround(targetBpm));
+ const int lo=std::max(minBpm,near-12);
+ const int hi=std::min(maxBpm,near+12);
+ for(int bpm=lo;bpm<=hi;++bpm) {
+ ++compared;
+ const float period=6000.f/static_cast(bpm);
+ if(dt>period*3.08f)continue;
+ if(static_cast(std::lround(dt/period))!=cycles)continue;
+ const float tolerance=std::max(1.4f,.022f*period*cycles);
+ const float error=std::abs(dt-period*cycles);
+ if(error>=tolerance)continue;
+ candidates[static_cast(bpm-minBpm)]+=
+ strength*(1.f-error/tolerance)/
+ (cycles==1?1.f:cycles==2?1.6f:2.25f);
+ }
+ }
+ }
+ }
+ result_.scoringComparisons=compared;
+ // Preserve deterministic ascending-BPM tie-breaking and the old
+ // half/double-time decision semantics exactly.
+ for(int bpm=minBpm;bpm<=maxBpm;++bpm) {
+ const float score=candidates[static_cast(bpm-minBpm)];
+ if(score>bestScore){bestScore=score;bestBpm=bpm;}
+ }
+ if(bestBpm==0 || bestScore<2.0f)return;
+ if(result_.locked) {
+ const int previous=static_cast(std::lround(result_.bpm));
+ const bool octave=std::abs(2*previous-bestBpm)<=3 ||
+ std::abs(previous-2*bestBpm)<=3;
+ if(octave && previous>=60 && previous<=180 &&
+ candidates[static_cast(previous-60)]>=
+ bestScore*.70f) {
+ // A wrong half/double-time incumbent can otherwise become
+ // PERMANENT: an exact 120 BPM pulse also supports 60 BPM
+ // through two-beat intervals. Detect strong, consecutive
+ // DIRECT onsets on the proposed new pulse, not just scored
+ // multiples of an older rhythm. Retain the incumbent when
+ // direct cadence is ambiguous (syncopated/off-beat music).
+ float strongest=0.f;
+ for(std::size_t i=0;i(candidate);
+ const float tolerance=std::max(1.5f,period*.045f);
+ const Hit* lastStrong=nullptr;
+ int matches=0;
+ for(std::size_t i=0;i600||hit.strength(hit.tick-lastStrong->tick)
+ -period)<=tolerance)
+ ++matches;
+ lastStrong=&hit;
+ }
+ return matches;
+ };
+ const auto incumbentScore=
+ candidates[static_cast(previous-60)];
+ const bool clearNewPulse=
+ bestScore>incumbentScore*1.005f &&
+ directStrongMatches(bestBpm)>=6 &&
+ directStrongMatches(bestBpm)>=
+ directStrongMatches(previous)+4;
+ if(!clearNewPulse)
+ bestBpm=previous;
+ }
+ }
+ if(std::abs(bestBpm-candidateBpm_)<=2)++stableCount_;
+ else {candidateBpm_=bestBpm;stableCount_=1;}
+ // A proven lock resists transient alternate half/double-time peaks.
+ if(result_.locked && std::abs(bestBpm-result_.bpm)>5.f &&
+ stableCount_<6)return;
+ if(stableCount_<3)return;
+ // Octave hysteresis can deliberately select a weaker incumbent.
+ // Confidence MUST describe that selected BPM, not an alternate
+ // double/half-time peak that we explicitly rejected.
+ const float acceptedScore=
+ candidates[static_cast(bestBpm-60)];
+ // Only the same LIVE 11-second onset window contributes to the
+ // candidate score. The ring may still contain many old weak hat
+ // attacks from a previous passage. Dividing by all 128 archival
+ // hits permanently depresses confidence even after a convincing
+ // quarter-note pulse returns (observed Windows CTest regression).
+ // Keep numerator and denominator on the identical time horizon.
+ std::size_t recentCount=0;
+ for(std::size_t i=0;i(std::max(7,recentCount))*.9f,0.f,1.f);
+ if(confidence<.28f) {
+ // A busy but low-confidence groove is NOT a stable beat. The
+ // previous code kept locked=true (and old beat-phase) while
+ // overwriting BPM, which could shift the next singer echo on an
+ // untrusted grid. Fail closed to accepted Manual/TAP, then demand
+ // three fresh good estimates before reacquiring Auto.
+ result_.confidence=confidence;
+ result_.locked=false;
+ result_.phaseLocked=false;
+ result_.phaseConfidence=0.f;
+ result_.beatAnchorFrame=0;
+ result_.beatAnchorTick=0;
+ stableCount_=candidateBpm_=0;
+ return;
+ }
+ result_.bpm=static_cast(bestBpm);
+ result_.confidence=confidence;
+ // CONTROL: phase is a separate decision from the BPM estimate.
+ // Search the bounded onset set for the strongest coherent pulse
+ // lattice, not simply the most recent loud snare / clap.
+ const float period=6000.f/result_.bpm;
+ const float tolerance=std::max(1.6f,period*.075f);
+ const auto matches=[&](std::uint64_t a,std::uint64_t b) noexcept {
+ const float elapsed=static_cast(a>b?a-b:b-a);
+ const float cycles=std::round(elapsed/period);
+ const float difference=std::abs(elapsed-cycles*period);
+ return std::max(0.f,1.f-difference/tolerance);
+ };
+ float total=0.f;
+ for(std::size_t i=0;i0.f)for(std::size_t candidate=0;candidate1100)continue;
+ float coherence=0.f;
+ for(std::size_t i=0;ileading+.0001f ||
+ (std::abs(coherence-leading)<=.0001f &&
+ center.tick>anchor)) {
+ leading=coherence;
+ anchor=center.tick;
+ anchorFrame=center.frame;
+ }
+ }
+ // Competing off-beat cohorts mean the quarter-note phase is not
+ // established, even when interval BPM itself is reliable.
+ float competing=0.f;
+ if(anchor)for(std::size_t candidate=0;candidate1100 ||
+ matches(center.tick,anchor)>.15f)continue;
+ float coherence=0.f;
+ for(std::size_t i=0;i0.f?
+ std::clamp(leading/total,0.f,1.f):0.f;
+ result_.phaseLocked=anchorFrame>0 &&
+ result_.phaseConfidence>=.52f &&
+ competing192000.))return false;
+ source_.store(id.value,std::memory_order_relaxed);
+ epoch_.store(epoch,std::memory_order_relaxed);
+ revision_.store(revision,std::memory_order_relaxed);
+ window_.store(id.value?
+ static_cast(std::lround(sampleRate*.01)):0,
+ std::memory_order_relaxed);
+ config_.fetch_add(1,std::memory_order_release);
+ return true;
+ }
+ // CONTROL: harmless structural WIRE/FX commits should preserve a valid
+ // music source. If the selected channel disappears, fall back to manual
+ // immediately rather than capturing stale processor/graph PCM.
+ ChannelId selectedSource() const noexcept {
+ return ChannelId{source_.load(std::memory_order_relaxed)};
+ }
+ void onGraphCommitted(std::uint64_t epoch,std::uint64_t previousRevision,
+ std::uint64_t revision,bool retained) noexcept {
+ if(!selectedSource().value)return;
+ if(!retained || epoch_.load(std::memory_order_relaxed)!=epoch ||
+ revision_.load(std::memory_order_relaxed)!=previousRevision) {
+ (void)select(ChannelId{},epoch,revision,0);
+ return;
+ }
+ revision_.store(revision,std::memory_order_relaxed);
+ config_.fetch_add(1,std::memory_order_release);
+ }
+ // AUDIO ONLY: the accepted publisher calls this ONCE per successfully
+ // admitted render block before traversing its ChannelId lanes. Revisions
+ // do not reset this clock; a physical epoch change always does.
+ std::uint64_t beginAudioBlock(std::uint64_t epoch,int frames) noexcept {
+ if(audioEpoch_!=epoch) {
+ audioEpoch_=epoch;
+ audioFrameClock_=0;
+ }
+ const auto start=audioFrameClock_;
+ if(frames>0)audioFrameClock_+=static_cast(frames);
+ blockStartFrame_=start;
+ return start;
+ }
+ // AUDIO: invoked once for every scheduled source channel by the existing
+ // renderer's pre-FX dispatch. Only the selected ID costs per-sample work.
+ void capture(ChannelId id,const float* left,const float* right,int frames,
+ std::uint64_t epoch,std::uint64_t revision) noexcept {
+ const auto generation=config_.load(std::memory_order_acquire);
+ if(audioGeneration_!=generation) {
+ audioGeneration_=generation;
+ bucketSamples_=0;energySum_=0.f;audioTick_=0;
+ }
+ if(!id.value||id.value!=source_.load(std::memory_order_relaxed)||
+ epoch!=epoch_.load(std::memory_order_relaxed)||
+ revision!=revision_.load(std::memory_order_relaxed)||
+ !left||!right||frames<=0)return;
+ const auto window=window_.load(std::memory_order_relaxed);
+ if(window==0)return;
+ for(int i=0;i(i)+1};
+ if(!frames_.push(f))
+ dropped_.fetch_add(1,std::memory_order_relaxed);
+ bucketSamples_=0;energySum_=0.f;
+ }
+ }
+ }
+ // CONTROL: limited work per timer tick, never called from ASIO callback.
+ State poll(std::uint64_t liveEpoch,std::uint64_t liveRevision,
+ std::uint64_t nowMs=0) noexcept {
+ // CONTROL only. The former tick-only timeout could hold the last
+ // beat/grid indefinitely when an ASIO callback stopped completely:
+ // no new 10ms frames meant the estimator clock could not expire.
+ // Monotonic wall time is never read from the realtime callback.
+ if(nowMs==0)
+ nowMs=static_cast(
+ std::chrono::duration_cast(
+ std::chrono::steady_clock::now().time_since_epoch()).count());
+ const auto generation=config_.load(std::memory_order_acquire);
+ if(controlGeneration_!=generation) {
+ controlGeneration_=generation;estimator_.reset();
+ lastReceivedControlMs_=0;
+ }
+ Frame f{};
+ bool sawCurrentFrame=false;
+ for(int i=0;i<512 && frames_.pop(f);++i)
+ if(f.generation==generation) {
+ estimator_.ingest(f.energy,f.tick,f.frameEnd);
+ sawCurrentFrame=true;
+ }
+ if(sawCurrentFrame)lastReceivedControlMs_=nowMs;
+ else if(lastReceivedControlMs_ && nowMs>=lastReceivedControlMs_ &&
+ nowMs-lastReceivedControlMs_>3500) {
+ // Keep the selected ChannelId, but never publish an obsolete
+ // BPM/phase lock after the audio stream freezes or is suspended.
+ // On resumed PCM the same source reacquires from fresh onsets.
+ estimator_.reset();
+ lastReceivedControlMs_=0;
+ }
+ State out{};
+ out.source.value=source_.load(std::memory_order_relaxed);
+ out.epoch=epoch_.load(std::memory_order_relaxed);
+ out.revision=revision_.load(std::memory_order_relaxed);
+ out.dropped=dropped_.load(std::memory_order_relaxed);
+ out.active=out.source.value && out.epoch==liveEpoch &&
+ out.revision==liveRevision;
+ if(out.active)out.tempo=estimator_.result();
+ return out;
+ }
+private:
+ struct Frame {
+ std::uint32_t generation=0;
+ std::uint64_t tick=0;
+ float energy=0.f;
+ std::uint64_t frameEnd=0;
+ };
+ armix::builtin_fx::FxSpsc frames_{};
+ MusicTempoEstimator estimator_{}; // CONTROL owner only
+ std::atomic source_{0},epoch_{0},revision_{0};
+ std::atomic config_{0},window_{0},dropped_{0};
+ // The following fields are AUDIO-thread exclusive.
+ std::uint32_t audioGeneration_=0,bucketSamples_=0;
+ float energySum_=0.f;
+ std::uint64_t audioTick_=0;
+ std::uint64_t audioEpoch_=0,audioFrameClock_=0,blockStartFrame_=0;
+ std::uint32_t controlGeneration_=0; // CONTROL only
+ std::uint64_t lastReceivedControlMs_=0; // CONTROL-only callback stall watchdog
+};
+} // namespace armix::mixer
diff --git a/engine/core/RealtimeNativeFxControl.h b/engine/core/RealtimeNativeFxControl.h
index b15eab95d..50287f960 100644
--- a/engine/core/RealtimeNativeFxControl.h
+++ b/engine/core/RealtimeNativeFxControl.h
@@ -9,6 +9,11 @@ namespace armix::mixer {
struct RealtimeNativeFxControl {
virtual ~RealtimeNativeFxControl() = default;
virtual void consumeRealtimeEdits() noexcept = 0;
+ // AUDIO callback only. A native performer cue can be dangerous when
+ // the rack is OFF: while fully bypassed its capture clock stops.
+ // Default no-op preserves Compressor/EQ/Harmony and vendor FX behavior.
+ virtual void onRealtimeBypass(bool /*requested*/,bool /*fully*/) noexcept {}
+
// CONTROL-only lifecycle: after FxInstance accepts this processor, a
// vendor-state restore must not mutate published audio-owned filters.
virtual void sealForRealtime() noexcept {}
diff --git a/scripts/compose_native_peq.py b/scripts/compose_native_peq.py
index a44984f58..4962371d1 100644
--- a/scripts/compose_native_peq.py
+++ b/scripts/compose_native_peq.py
@@ -6,6 +6,7 @@
SCRIPT=''
COMP_SCRIPT=''
HARMONY_SCRIPT=''
+THROW_SCRIPT=''
PICKER_HEAD="function renderFastPicker(){"
PICKER_FN="""function insertChosenNativeEq(){
const t=tracks.concat(master).find(x=>x.id===activeFxTarget?.channelId);
@@ -73,6 +74,25 @@
say('ArSon Harmony · browser preview ONLY · no DSP');
return true;
}
+function insertChosenNativeThrow(){
+ const t=tracks.concat(master).find(x=>x.id===activeFxTarget?.channelId);
+ const slot=Number(activeFxTarget?.slot);
+ if(!t||!Number.isInteger(slot)||slot<0||slot>=8){
+ say('Vocal Throw · choose an empty FX insert');return false;
+ }
+ if(window.__JUCE__?.backend?.emitEvent){
+ const host=window.ArSonMixNativeVocalThrow;
+ if(!host?.insert){say('Native Vocal Throw host unavailable');return false;}
+ host.insert(activeFxTarget);return true;
+ }
+ if(t.fx[slot]!=='None'){
+ say('FX slot already occupied · choose an empty insert');return false;
+ }
+ t.fx[slot]='ArSon Vocal Throw';t.slotBypass[slot]=false;
+ t.fxInsertIds[slot]={id:'visual-throw-'+t.id+'-'+slot,name:'ArSon Vocal Throw'};
+ refreshStrip(t);setFastPicker(false);
+ say('Vocal Throw · browser preview ONLY · no audio DSP');return true;
+}
function renderFastPicker(){"""
PICKER_RENDER="plugEl('fastResults').innerHTML=list.length?list.map(p=>"
PICKER_RENDER_NEW="""const eqBuiltin=!q||['parametric eq','peq','channel eq','built-in fx'].some(n=>n.includes(q))?
@@ -81,7 +101,9 @@
'':'';
const harmonyBuiltin=!q||['arson harmony','harmony','vocal harmony','built-in fx'].some(n=>n.includes(q))?
'':'';
- const builtin=(eqBuiltin||compBuiltin||harmonyBuiltin?'BUILT-IN FX
':'')+eqBuiltin+compBuiltin+harmonyBuiltin;
+ const throwBuiltin=!q||['vocal throw','throw','delay','echo','phrase','concert','built-in fx'].some(n=>n.includes(q))?
+ '':'';
+ const builtin=(eqBuiltin||compBuiltin||harmonyBuiltin||throwBuiltin?'BUILT-IN FX
':'')+eqBuiltin+compBuiltin+harmonyBuiltin+throwBuiltin;
plugEl('fastResults').innerHTML=builtin+'VST3 PLUGINS
'+(list.length?list.map(p=>"""
PICKER_END=""").join(''):'No matching effects
';"""
PICKER_END_NEW=""").join(''):'No matching effects
');"""
@@ -89,9 +111,10 @@
PICKER_CLICK_NEW=""" if(e.target.closest('[data-fast-native-harmony]')){insertChosenNativeHarmony();return;}
if(e.target.closest('[data-fast-native-eq]')){insertChosenNativeEq();return;}
if(e.target.closest('[data-fast-native-comp]')){insertChosenNativeCompressor();return;}
+ if(e.target.closest('[data-fast-native-throw]')){insertChosenNativeThrow();return;}
const btn=e.target.closest('[data-fast-id]');if(btn)insertCatalogPlugin(btn.dataset.fastId);"""
PICKER_ENTER="if(b){e.preventDefault();insertCatalogPlugin(b.dataset.fastId);}"
-PICKER_ENTER_NEW="if(b){e.preventDefault();if(b.hasAttribute('data-fast-native-harmony'))insertChosenNativeHarmony();else if(b.hasAttribute('data-fast-native-eq'))insertChosenNativeEq();else if(b.hasAttribute('data-fast-native-comp'))insertChosenNativeCompressor();else insertCatalogPlugin(b.dataset.fastId);}"
+PICKER_ENTER_NEW="if(b){e.preventDefault();if(b.hasAttribute('data-fast-native-harmony'))insertChosenNativeHarmony();else if(b.hasAttribute('data-fast-native-throw'))insertChosenNativeThrow();else if(b.hasAttribute('data-fast-native-eq'))insertChosenNativeEq();else if(b.hasAttribute('data-fast-native-comp'))insertChosenNativeCompressor();else insertCatalogPlugin(b.dataset.fastId);}"
OPEN=" if(a==='openPlugin'){openFastPicker(t,Number(btn.dataset.slot),btn);return;}"
OPEN_NEW=""" if(a==='openPlugin'){
const index=Number(btn.dataset.slot);
@@ -104,6 +127,9 @@
if(t.fx[index]==='ArSon Harmony'){
window.ArSonMixNativeHarmony?.open(t,index);return;
}
+ if(t.fx[index]==='ArSon Vocal Throw'){
+ window.ArSonMixNativeVocalThrow?.open(t,index);return;
+ }
openFastPicker(t,index,btn);return;
}"""
def apply_native_peq(html: str)->str:
@@ -114,11 +140,11 @@ def apply_native_peq(html: str)->str:
(PICKER_ENTER,PICKER_ENTER_NEW),
(OPEN,OPEN_NEW))
if html.count('')!=1 or html.count('