diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml
index 257a1396c..2d30113e8 100644
--- a/.github/workflows/ui-smoke.yml
+++ b/.github/workflows/ui-smoke.yml
@@ -107,6 +107,7 @@ jobs:
node --check site/preview-v2/assets/gui-perf-probe.js
node --check site/preview-v2/assets/mixer-native-peq.js
node --check site/preview-v2/assets/mixer-native-compressor.js
+ 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
@@ -126,6 +127,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-') }}
+ 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 f1af6ea30..af792fd07 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -379,6 +379,18 @@ if(BUILD_TESTING)
add_test(NAME NativeCompressorZeroLatencyAndLinkedStereoPCM COMMAND ARMixNativeCompressorTests)
add_dependencies(ARMixMixerRoutingTests ARMixNativeCompressorTests)
+ 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)
+ 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_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..0b0aaaee8
--- /dev/null
+++ b/engine/builtin_fx/VocalThrow.h
@@ -0,0 +1,307 @@
+// 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;
+ }
+ // 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;
+ }
+ }
+ [[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;
+ 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_;
+ 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;
+ const auto first=std::max(clock_,voice.copyEnd+voice.active.intervalSamples);
+ 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.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;
+ 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..a7573b0a1
--- /dev/null
+++ b/engine/builtin_fx/VocalThrowProcessor.h
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+#pragma once
+#include "VocalThrow.h"
+#include "FxSpsc.h"
+#include "../core/RealtimeNativeFxControl.h"
+#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;
+ };
+ 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 {
+ // 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;
+ musicInterval_.store(0,std::memory_order_release);
+ ready_=core_.prepare(sampleRate)&&core_.resetUnpublished(accepted_);
+ 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 consumeRealtimeEdits() noexcept override {
+ if(!ready_)return;
+ // One atomic acquire per callback, before queueing the newest throw.
+ // A source change and button click cannot freeze the previous BPM.
+ core_.setMusicIntervalSamples(
+ musicInterval_.load(std::memory_order_acquire));
+ Edit e{};
+ if(!done_.canPush()||!commands_.pop(e))return;
+ const bool applied=e.kind==CommandKind::settings?
+ core_.applyPrepared(e.prepared):core_.throwNow();
+ (void)done_.push({e.id,e.prepared.settings,e.kind,applied});
+ }
+ // 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);
+ }
+ 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);
+ }
+ 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 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 a4f3d6ac8..a2246c308 100644
--- a/engine/core/DynamicNativeSessionPublisher.h
+++ b/engine/core/DynamicNativeSessionPublisher.h
@@ -2,6 +2,7 @@
#pragma once
#include "DynamicPreparedMixerBlock.h"
#include "DynamicConsoleRoutingView.h"
+#include "NativeMusicTempoMonitor.h"
#include "RealtimeRoutePublisher.h"
#include "RealtimeRenderPermit.h"
#include
@@ -124,8 +125,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:
@@ -191,6 +207,10 @@ class DynamicNativeSessionPublisher final {
// 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);
@@ -203,6 +223,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.
@@ -289,6 +328,7 @@ class DynamicNativeSessionPublisher final {
}
private:
Publisher publisher_;
+ NativeMusicTempoMonitor musicTempo_{};
std::atomic_flag rendering_=ATOMIC_FLAG_INIT;
};
} // namespace armix::mixer
diff --git a/engine/core/NativeMusicTempoMonitor.h b/engine/core/NativeMusicTempoMonitor.h
new file mode 100644
index 000000000..81560fa3d
--- /dev/null
+++ b/engine/core/NativeMusicTempoMonitor.h
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+#pragma once
+#include "../builtin_fx/FxSpsc.h"
+#include "DynamicChannelRoster.h"
+#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;
+ std::uint64_t beatAnchorTick=0,observationTick=0;
+ bool locked=false;
+ };
+ 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) 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)};
+ write_=(write_+1)%hits_.size();
+ count_=std::min(count_+1,hits_.size());
+ lastHit_=tick;
+ }
+ previous_=energy;
+ if(result_.locked && tick>lastHit_+320) {
+ result_.locked=false;result_.confidence=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::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 ONLY: bounded 121 candidates x 128 onsets. Emphasize
+ // one-beat matches; harmonics, half- and double-time are penalized.
+ for(int bpm=60;bpm<=180;++bpm) {
+ const float period=6000.f/static_cast(bpm);
+ float score=0.f;
+ 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>period*3.08f)break;
+ const int cycles=static_cast(std::lround(dt/period));
+ if(cycles<1||cycles>3)continue;
+ const float tolerance=std::max(1.4f,.022f*period*cycles);
+ const float error=std::abs(dt-period*cycles);
+ if(error>=tolerance)continue;
+ const float strength=std::sqrt(earlier.strength*later.strength);
+ score+=strength*(1.f-error/tolerance)/
+ (cycles==1?1.f:cycles==2?1.6f:2.25f);
+ }
+ }
+ if(score>bestScore) {bestScore=score;bestBpm=bpm;}
+ }
+ if(bestBpm==0 || bestScore<2.0f)return;
+ 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;
+ result_.bpm=static_cast(candidateBpm_);
+ result_.confidence=std::clamp(bestScore/
+ static_cast(std::max(7,count_))*.9f,0.f,1.f);
+ if(result_.confidence<.28f)return;
+ // The strongest recent transient is a practical pulse anchor;
+ // explicit "beat-phase certified" remains a separate field FAT.
+ float strength=0.f;
+ std::uint64_t anchor=0;
+ const auto period=6000.f/result_.bpm;
+ for(std::size_t i=0;iperiod*1.8f)continue;
+ if(h.strength>=strength) {strength=h.strength;anchor=h.tick;}
+ }
+ result_.beatAnchorTick=anchor;
+ result_.observationTick=lastTick_;
+ result_.locked=true;
+ }
+};
+
+class NativeMusicTempoMonitor final {
+public:
+ struct State final {
+ ChannelId source{};
+ std::uint64_t epoch=0,revision=0;
+ MusicTempoEstimator::Result tempo{};
+ std::uint32_t dropped=0;
+ bool active=false;
+ };
+ // CONTROL, only after checking this exact ChannelId exists in the
+ // accepted PCM graph and does not point at vocals, MAIN or MONITOR.
+ bool select(ChannelId id,std::uint64_t epoch,std::uint64_t revision,
+ double sampleRate) noexcept {
+ if(id.value && (!epoch||!revision||!std::isfinite(sampleRate)||
+ sampleRate<8000.||sampleRate>192000.))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: 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 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::uint32_t controlGeneration_=0; // CONTROL only
+};
+} // namespace armix::mixer
diff --git a/scripts/compose_native_peq.py b/scripts/compose_native_peq.py
index 1a61cf2e5..b697a4349 100644
--- a/scripts/compose_native_peq.py
+++ b/scripts/compose_native_peq.py
@@ -5,6 +5,7 @@
CATALOG="armix.builtin.channel-eq.v1"
SCRIPT=''
COMP_SCRIPT=''
+THROW_SCRIPT=''
PICKER_HEAD="function renderFastPicker(){"
PICKER_FN="""function insertChosenNativeEq(){
const t=tracks.concat(master).find(x=>x.id===activeFxTarget?.channelId);
@@ -50,22 +51,44 @@
refreshStrip(t);setFastPicker(false);
say('Compressor · browser preview ONLY · no audio 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))?
'':'';
const compBuiltin=!q||['compressor','comp','dynamics','built-in fx'].some(n=>n.includes(q))?
'':'';
- const builtin=(eqBuiltin||compBuiltin?'BUILT-IN FX
':'')+eqBuiltin+compBuiltin;
+ const throwBuiltin=!q||['vocal throw','throw','delay','echo','phrase','concert','built-in fx'].some(n=>n.includes(q))?
+ '':'';
+ const builtin=(eqBuiltin||compBuiltin||throwBuiltin?'BUILT-IN FX
':'')+eqBuiltin+compBuiltin+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
');"""
PICKER_CLICK=" const btn=e.target.closest('[data-fast-id]');if(btn)insertCatalogPlugin(btn.dataset.fastId);"
PICKER_CLICK_NEW=""" 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-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-eq'))insertChosenNativeEq();else if(b.hasAttribute('data-fast-native-comp'))insertChosenNativeCompressor();else if(b.hasAttribute('data-fast-native-throw'))insertChosenNativeThrow();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);
@@ -75,6 +98,9 @@
if(t.fx[index]==='Compressor'){
window.ArSonMixNativeCompressor?.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:
@@ -85,11 +111,11 @@ def apply_native_peq(html: str)->str:
(PICKER_ENTER,PICKER_ENTER_NEW),
(OPEN,OPEN_NEW))
if html.count('')!=1 or html.count('