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('')!=1 or \ - SCRIPT in html or COMP_SCRIPT in html or 'insertChosenNativeEq' in html: + SCRIPT in html or COMP_SCRIPT in html or HARMONY_SCRIPT in html or THROW_SCRIPT in html or 'insertChosenNativeEq' in html: raise ValueError("Parametric EQ requires one pristine approved compiled GUI") for before,after in anchors: if html.count(before)!=1: raise ValueError('Ambiguous approved picker/editor anchor: '+before[:90]) html=html.replace(before,after,1) - html=html.replace('',SCRIPT+'\n'+COMP_SCRIPT+'\n'+HARMONY_SCRIPT+'\n',1) + html=html.replace('',SCRIPT+'\n'+COMP_SCRIPT+'\n'+HARMONY_SCRIPT+'\n'+THROW_SCRIPT+'\n',1) return html diff --git a/site/preview-v2/assets/arson-vocal-hardware-encoder.svg b/site/preview-v2/assets/arson-vocal-hardware-encoder.svg new file mode 100644 index 000000000..2cb7d175f --- /dev/null +++ b/site/preview-v2/assets/arson-vocal-hardware-encoder.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/site/preview-v2/assets/arson-vocal-hardware-push.svg b/site/preview-v2/assets/arson-vocal-hardware-push.svg new file mode 100644 index 000000000..1b9970a96 --- /dev/null +++ b/site/preview-v2/assets/arson-vocal-hardware-push.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/site/preview-v2/assets/arson-vocal-hardware-rotor.svg b/site/preview-v2/assets/arson-vocal-hardware-rotor.svg new file mode 100644 index 000000000..e8c72a55e --- /dev/null +++ b/site/preview-v2/assets/arson-vocal-hardware-rotor.svg @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/site/preview-v2/assets/arson-vocal-hardware-toggle.svg b/site/preview-v2/assets/arson-vocal-hardware-toggle.svg new file mode 100644 index 000000000..d3aad9aa7 --- /dev/null +++ b/site/preview-v2/assets/arson-vocal-hardware-toggle.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/site/preview-v2/assets/arson-vocal-throw-performance.svg b/site/preview-v2/assets/arson-vocal-throw-performance.svg new file mode 100644 index 000000000..38305d831 --- /dev/null +++ b/site/preview-v2/assets/arson-vocal-throw-performance.svg @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/site/preview-v2/assets/mixer-contextual-buttons.css b/site/preview-v2/assets/mixer-contextual-buttons.css index 84f8b2ef8..315b58b3e 100644 --- a/site/preview-v2/assets/mixer-contextual-buttons.css +++ b/site/preview-v2/assets/mixer-contextual-buttons.css @@ -197,22 +197,24 @@ } /* Single authoritative modal Close + built-in FX Power chrome. + The semantic .armix-builtin-fx-power / -close classes are mandatory on + every built-in editor, while legacy EQ/Compressor names remain compatible. All cards: same 24px hit box, same icon, same pressed-red interaction. Green ON, muted red insert bypass, amber rack bypass, grey unavailable. FX state is assigned exclusively from accepted DSP graph readback. */ -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close){display:inline-flex!important;align-items:center!important;justify-content:center!important;position:relative!important;box-sizing:border-box!important;flex:0 0 24px!important;width:24px!important;min-width:24px!important;max-width:24px!important;height:24px!important;min-height:24px!important;max-height:24px!important;padding:0!important;margin:0!important;font-size:0!important;line-height:1!important;color:#e0edf2!important;cursor:pointer!important;border:1px solid #607d8c!important;border-radius:4px!important;background:linear-gradient(#3e5866,#293e4b)!important;box-shadow:inset 0 1px #ffffff22,0 1px 2px #06131f75!important;transform:none!important;text-shadow:none!important;transition:background-color .10s,border-color .10s,color .10s!important} -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close) svg{display:none!important} -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close)::before{content:none!important;display:none!important} -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close)::after,:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close):active::after{content:""!important;display:block!important;position:relative!important;flex:0 0 12px!important;inset:auto!important;width:12px!important;height:12px!important;opacity:1!important;border:0!important;border-radius:0!important;transform:none!important;box-shadow:none!important;pointer-events:none!important;background:linear-gradient(45deg,transparent 43%,currentColor 43% 57%,transparent 57%),linear-gradient(-45deg,transparent 43%,currentColor 43% 57%,transparent 57%)!important} -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close):hover:not(:disabled){color:#fff!important;border-color:#b27078!important;background:linear-gradient(#64424f,#4d343f)!important} -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close):active:not(:disabled){color:#fff!important;border-color:#ee8b93!important;background:linear-gradient(#cc4753,#982a36)!important;box-shadow:inset 0 2px 4px #4c0c1790,0 0 0 1px #ef698069!important;transition:none!important} -:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close):focus-visible{outline:2px solid #a2dce9!important;outline-offset:2px!important} -body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power){display:inline-flex!important;align-items:center!important;justify-content:center!important;box-sizing:border-box!important;flex:0 0 26px!important;width:26px!important;height:24px!important;opacity:1!important;padding:0!important;border:1px solid #4b6572!important;border-radius:4px!important;background:linear-gradient(#384b56,#243846)!important;box-shadow:inset 0 1px #ffffff20!important;font-size:18px!important;transition:none!important} -body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power)[data-fx-state="on"]{color:#76f0b9!important;border-color:#428969!important;background:linear-gradient(#335c51,#204539)!important;text-shadow:0 0 5px #7df0b85c!important} -body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power)[data-fx-state="off"]{color:#e99b9f!important;border-color:#83525a!important;background:linear-gradient(#533b42,#3a3039)!important;text-shadow:none!important} -body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power)[data-fx-state="rack-off"]{color:#f0c483!important;border-color:#846948!important;background:linear-gradient(#544737,#41382d)!important;text-shadow:none!important;cursor:not-allowed!important} -body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power)[data-fx-state="unknown"]{color:#8498a4!important;border-color:#4b5d66!important;background:linear-gradient(#3a4751,#2b3941)!important;text-shadow:none!important;cursor:not-allowed!important} -body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power):focus-visible{outline:2px solid #9cdbe7!important;outline-offset:2px!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close){display:inline-flex!important;align-items:center!important;justify-content:center!important;position:relative!important;box-sizing:border-box!important;flex:0 0 24px!important;width:24px!important;min-width:24px!important;max-width:24px!important;height:24px!important;min-height:24px!important;max-height:24px!important;padding:0!important;margin:0!important;font-size:0!important;line-height:1!important;color:#e0edf2!important;cursor:pointer!important;border:1px solid #607d8c!important;border-radius:4px!important;background:linear-gradient(#3e5866,#293e4b)!important;box-shadow:inset 0 1px #ffffff22,0 1px 2px #06131f75!important;transform:none!important;text-shadow:none!important;transition:background-color .10s,border-color .10s,color .10s!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close) svg{display:none!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close)::before{content:none!important;display:none!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close)::after,:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close):active::after{content:""!important;display:block!important;position:relative!important;flex:0 0 12px!important;inset:auto!important;width:12px!important;height:12px!important;opacity:1!important;border:0!important;border-radius:0!important;transform:none!important;box-shadow:none!important;pointer-events:none!important;background:linear-gradient(45deg,transparent 43%,currentColor 43% 57%,transparent 57%),linear-gradient(-45deg,transparent 43%,currentColor 43% 57%,transparent 57%)!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close):hover:not(:disabled){color:#fff!important;border-color:#b27078!important;background:linear-gradient(#64424f,#4d343f)!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close):active:not(:disabled){color:#fff!important;border-color:#ee8b93!important;background:linear-gradient(#cc4753,#982a36)!important;box-shadow:inset 0 2px 4px #4c0c1790,0 0 0 1px #ef698069!important;transition:none!important} +:is(.app,body) :is(#identityClose,#pluginClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose,.armix-floating-close,.mx-peq-close,.mx-comp-close,.mx-harm-close,.armix-builtin-fx-close):focus-visible{outline:2px solid #a2dce9!important;outline-offset:2px!important} +body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power){display:inline-flex!important;align-items:center!important;justify-content:center!important;box-sizing:border-box!important;flex:0 0 26px!important;width:26px!important;height:24px!important;opacity:1!important;padding:0!important;border:1px solid #4b6572!important;border-radius:4px!important;background:linear-gradient(#384b56,#243846)!important;box-shadow:inset 0 1px #ffffff20!important;font-size:18px!important;transition:none!important} +body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power)[data-fx-state="on"]{color:#76f0b9!important;border-color:#428969!important;background:linear-gradient(#335c51,#204539)!important;text-shadow:0 0 5px #7df0b85c!important} +body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power)[data-fx-state="off"]{color:#e99b9f!important;border-color:#83525a!important;background:linear-gradient(#533b42,#3a3039)!important;text-shadow:none!important} +body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power)[data-fx-state="rack-off"]{color:#f0c483!important;border-color:#846948!important;background:linear-gradient(#544737,#41382d)!important;text-shadow:none!important;cursor:not-allowed!important} +body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power)[data-fx-state="unknown"]{color:#8498a4!important;border-color:#4b5d66!important;background:linear-gradient(#3a4751,#2b3941)!important;text-shadow:none!important;cursor:not-allowed!important} +body :is(.mx-peq-global,.mx-comp-power,.mx-harm-power,.armix-builtin-fx-power):focus-visible{outline:2px solid #9cdbe7!important;outline-offset:2px!important} /* ArSon Player: compact stage-first drawer inside the ONE approved mixer GUI. */ #playerToggle{min-width:86px;letter-spacing:.01em} diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index b5f8376f9..b81b2024e 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -748,3 +748,242 @@ @media(prefers-reduced-motion:reduce){ .mx-harm *{transition:none!important;animation:none!important} } + +/* Vocal Throw M4 — aligned studio-hardware faceplate. + One spacing grid, one encoder body, one fixed 260deg rounded level arc. + Close/Power remain the same approved EQ/Compressor shared controls. */ +.mx-vthrow{position:fixed;z-index:15001;top:clamp(7px,7vh,66px);left:clamp(7px,9vw,175px); + width:min(778px,calc(100vw - 14px));max-height:calc(100dvh - 14px);display:flex;flex-direction:column; + box-sizing:border-box;overflow:hidden;border:1px solid #505763;border-radius:9px;color:#d5dce5; + background:linear-gradient(155deg,#323740,#242931 60%,#20252d); + box-shadow:inset 0 1px #ffffff21,inset 0 -1px #090c1199,0 18px 50px #000c; + font:400 11px/1.35 Inter,'Segoe UI',sans-serif} +.mx-vthrow[hidden]{display:none}.mx-vthrow *{box-sizing:border-box} +.mx-vthrow button{font:inherit;cursor:pointer} +.mx-vthrow :is(button,select,input):focus-visible{outline:2px solid #b6e8e3;outline-offset:3px} +.mx-vthrow .vt-face-header{height:42px;flex:0 0 42px;display:flex;align-items:center;gap:8px; + min-width:0;padding:0 11px 0 15px;cursor:move;touch-action:none;user-select:none; + background:linear-gradient(#3d444e,#292f38);border-bottom:1px solid #141922; + box-shadow:inset 0 1px #ffffff29,inset 0 -1px #ffffff09} +.mx-vthrow .brand{display:flex;align-items:baseline;gap:7px;white-space:nowrap;flex:0 0 auto} +.mx-vthrow .brand-mark{font-size:9px;font-weight:660;color:#c885e7;letter-spacing:.12em} +.mx-vthrow .brand-name{font-size:12px;font-weight:580;color:#f0eef4;letter-spacing:.055em} +.mx-vthrow .channel{min-width:0;max-width:136px;flex:1;overflow:hidden;text-overflow:ellipsis; + white-space:nowrap;font-size:9px;color:#aeb1ba} +.mx-vthrow .vt-preset{display:flex;align-items:center;gap:4px;margin-left:auto;min-width:0} +.mx-vthrow .vt-preset select{width:112px;height:25px;min-width:0;max-width:112px;padding:0 7px; + border:1px solid #525c68;border-radius:4px;background:linear-gradient(#2a3039,#1f252e); + color:#dce1e9;font:500 10px Inter,'Segoe UI',sans-serif} +.mx-vthrow option{color:#e8eaf1;background:#272b34} +.mx-vthrow .vt-hardware{min-height:0;overflow:auto;overscroll-behavior:contain;display:grid; + padding:0;scrollbar-width:thin;scrollbar-color:#565563 #22272e} +.mx-vthrow .vt-console{padding:13px 16px 12px;border-bottom:1px solid #515660; + background:linear-gradient(135deg,#31363e,#262b34 65%,#2b2f38); + box-shadow:inset 0 1px #ffffff13} +.mx-vthrow .vt-instrument{display:grid;grid-template-columns:minmax(0,1fr) 212px minmax(0,1fr); + align-items:center;column-gap:12px;min-width:0} +.mx-vthrow .vt-encoder-bank{display:grid;grid-template-columns:repeat(3,minmax(0,1fr)); + justify-items:stretch;align-items:stretch;min-width:0;gap:5px} +.mx-vthrow .vt-encoder{display:grid;grid-template-rows:16px 70px 18px; + justify-items:center;align-items:center;align-content:center;row-gap:3px; + min-width:0;width:100%;padding:2px 0} +.mx-vthrow .vt-encoder-name{height:auto;max-width:100%;line-height:15px;color:#b4beca; + font-size:10px;font-weight:540;letter-spacing:.067em;text-align:center;white-space:nowrap} +.mx-vthrow .vt-encoder-face{position:relative;display:block;flex:0 0 auto;width:70px;height:70px; + padding:0;border:0;border-radius:50%;touch-action:none;cursor:ns-resize; + background:transparent url("arson-vocal-hardware-encoder.svg") center/77% 77% no-repeat; + filter:drop-shadow(0 4px 5px #060a10a8)} +.mx-vthrow .vt-knob-meter{position:absolute;inset:0;width:100%;height:100%;overflow:visible; + fill:none;pointer-events:none} +.mx-vthrow .vt-meter-track,.mx-vthrow .vt-meter-fill{fill:none;stroke-width:3.3; + stroke-linecap:round;stroke-linejoin:round} +.mx-vthrow .vt-meter-track{stroke:#52616c;stroke-opacity:.8} +.mx-vthrow .vt-meter-fill{stroke:#79d4c7;stroke-width:3.8; + stroke-dasharray:100 100;stroke-dashoffset:var(--arc-offset,100); + filter:drop-shadow(0 0 1.3px #6ad8c788)} +.mx-vthrow .vt-encoder-needle{position:absolute;inset:0;transform:rotate(var(--turn,-130deg)); + pointer-events:none} +.mx-vthrow .vt-encoder-needle::after{content:"";position:absolute;left:calc(50% - 1.25px); + top:23%;height:12px;width:2.5px;border-radius:3px;background:#aee9e2; + box-shadow:0 0 3px #73cfce94} +.mx-vthrow .vt-encoder-value{font:500 12px/17px Inter,'Segoe UI',sans-serif; + color:#e1e4eb;font-variant-numeric:tabular-nums;white-space:nowrap;text-align:center} +.mx-vthrow .vt-center{min-width:0;display:flex;align-items:center; + justify-content:center;flex-direction:column;gap:0} +.mx-vthrow .vt-throw-button{position:relative;display:block;width:212px;height:212px;flex:0 0 auto; + border:0;padding:0;border-radius:50%;overflow:visible;touch-action:manipulation;cursor:pointer; + background:transparent url("arson-vocal-throw-performance.svg") center/contain no-repeat; + filter:drop-shadow(0 8px 9px #090d15af);transform:translateZ(0); + transition:filter 150ms ease,transform 100ms ease} +.mx-vthrow .vt-throw-aura{position:absolute;inset:10%;border-radius:50%;pointer-events:none; + box-shadow:inset 0 0 0 1px #b267c821,0 0 0 1px #11141b; + transition:box-shadow 150ms ease} +.mx-vthrow .vt-throw-button:hover:not(:disabled){filter:brightness(1.19) drop-shadow(0 8px 10px #080c13ca)} +.mx-vthrow .vt-throw-button:hover:not(:disabled) .vt-throw-aura{box-shadow:0 0 22px #bc36df3b,inset 0 0 0 1px #c17fdd3a} +.mx-vthrow .vt-throw-button:active:not(:disabled){transform:scale(.958) translateY(2px); + filter:brightness(1.32) drop-shadow(0 1px 2px #000b)} +.mx-vthrow .vt-throw-button[data-tail=true]:not(:disabled) .vt-throw-aura{ + box-shadow:0 0 29px #bb29e73f,inset 0 0 0 1px #e7a7f783} +.mx-vthrow .vt-throw-button:disabled{opacity:.53;filter:grayscale(.72) brightness(.8)} +.mx-vthrow .vt-throw-engraving{margin-top:-3px;color:#bca0cc; + font-size:9px;letter-spacing:.24em;font-weight:560;user-select:none; + transform:translateY(6px);pointer-events:none} +.mx-vthrow .vt-performance{display:grid;grid-template-columns:88px minmax(0,1fr) 302px; + align-items:center;column-gap:15px;margin-top:8px;min-height:110px} +.mx-vthrow .vt-wet-module{padding:0;justify-self:center;width:88px} +.mx-vthrow .vt-wet-module .vt-encoder-face{width:70px;height:70px} +.mx-vthrow .vt-trigger{min-width:0;height:100%;display:flex;align-items:center;justify-content:center} +.mx-vthrow .vt-mode-buttons{width:min(210px,100%);min-height:38px} +.mx-vthrow .vt-mode-buttons,.mx-vthrow .vt-division-buttons{display:flex;align-items:center; + gap:2px;padding:3px;border:1px solid #171c23;border-radius:7px; + background:linear-gradient(#131820,#242a32); + box-shadow:inset 0 2px 4px #060b11b8,0 1px #56606a3d} +.mx-vthrow :is(.vt-mode-buttons,.vt-division-buttons) button{flex:1;min-width:0; + min-height:31px;padding:3px 7px;border:1px solid transparent;border-radius:4px; + background:linear-gradient(#3b424b,#2d343d);box-shadow:inset 0 1px #ffffff15; + color:#b8c0cb;font-size:10.5px;font-weight:560;letter-spacing:.025em} +.mx-vthrow :is(.vt-mode-buttons,.vt-division-buttons) button[aria-pressed=true]{ + color:#f5e4ff;border-color:#784f8b;background:linear-gradient(#6a4c78,#3f344a); + box-shadow:inset 0 1px #efbaff2b,0 0 7px #b66bd327} +.mx-vthrow .vt-virtual-input,.mx-vthrow .vt-screen-reader{position:absolute!important; + width:1px!important;height:1px!important;padding:0!important;border:0!important; + opacity:0!important;overflow:hidden!important;pointer-events:none!important} +.mx-vthrow .vt-clock-tap{display:grid;grid-template-columns:minmax(145px,1fr) 83px; + align-items:center;gap:10px;min-width:0} +.mx-vthrow .vt-tempo{min-width:0;display:flex;flex-direction:column;align-items:center;gap:3px} +.mx-vthrow .vt-clock-screen{position:relative;width:100%;height:79px;min-width:0;display:flex;flex-direction:column; + justify-content:center;align-items:stretch;gap:1px;padding:7px 11px 5px; + border:1px solid #42616a;border-radius:6px;color:#cbf8e9; + background:radial-gradient(ellipse at 50% 15%,#173b40b5,transparent 80%), + linear-gradient(155deg,#071c22,#092831 70%,#061a20); + box-shadow:inset 0 2px 11px #000b,inset 0 0 0 1px #092a32,0 1px #53667233} +.mx-vthrow .vt-lcd-top{display:flex;align-items:center;justify-content:space-between; + font-size:9px;letter-spacing:.15em;color:#77aead} +.mx-vthrow #vtClockLabel{color:#a9dec5;font-size:9px;font-weight:550;letter-spacing:.1em} +.mx-vthrow .vt-lcd-digits{display:flex;align-items:baseline;gap:8px} +.mx-vthrow #vtDisplayBpm{padding:0;margin:0;border:0;background:none;appearance:none; + font:500 44px/1.04 'Segoe UI',Inter,sans-serif; + color:#d8fff2;letter-spacing:-.05em;font-variant-numeric:tabular-nums; + text-shadow:0 0 15px #61b7a533;cursor:text;text-align:left} +.mx-vthrow #vtDisplayBpm:hover{color:#e8fff7} +.mx-vthrow .vt-clock-screen[data-editing=true] #vtDisplayBpm{opacity:0;pointer-events:none} +.mx-vthrow .vt-lcd-digits>span{font-size:10px;color:#7fbeb2;letter-spacing:.07em} +.mx-vthrow .vt-manual-bpm{display:none;position:absolute;left:11px;right:10px; + top:25px;height:49px;align-items:center;z-index:1} +.mx-vthrow .vt-clock-screen[data-editing=true] .vt-manual-bpm{display:flex} +.mx-vthrow .vt-manual-bpm input{width:100%;max-width:148px;height:49px;margin:0; + padding:0;border:0;border-bottom:1px solid #75d5c58f;border-radius:0; + outline:0;background:#0b252d;color:#d8fff2; + font:500 44px/1.04 'Segoe UI',sans-serif;text-align:left; + letter-spacing:-.05em;font-variant-numeric:tabular-nums; + appearance:textfield} +.mx-vthrow .vt-manual-bpm input::-webkit-inner-spin-button, +.mx-vthrow .vt-manual-bpm input::-webkit-outer-spin-button{appearance:none;margin:0} +.mx-vthrow .vt-tap-button{height:79px;display:flex;flex-direction:column; + align-items:center;justify-content:center;gap:1px;color:#c8d0d9; + background:linear-gradient(#414852,#262c35);border:1px solid #4c5661;border-radius:9px; + box-shadow:inset 0 1px #ffffff21,0 3px 6px #0008} +.mx-vthrow .vt-tap-button span{font-size:15px;font-weight:640;letter-spacing:.12em} +.mx-vthrow .vt-tap-button small{font-size:9px;letter-spacing:.12em;color:#a5b0bc} +.mx-vthrow .vt-tap-button:active{background:linear-gradient(#242931,#353b45); + box-shadow:inset 0 2px 5px #000a} +.mx-vthrow .vt-transport{min-width:0;display:grid; + grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:17px; + padding:12px 17px 12px;background:linear-gradient(#232a33,#20252d); + border-top:1px solid #0f141b;border-bottom:1px solid #4b525c} +.mx-vthrow .vt-pulse,.mx-vthrow .vt-music-source{min-width:0; + display:flex;flex-direction:column;align-items:stretch;gap:6px} +.mx-vthrow .vt-small-label{font-size:10px;line-height:14px;font-weight:540;letter-spacing:.09em; + color:#b4bac5;white-space:nowrap} +.mx-vthrow .vt-division-buttons{height:40px} +.mx-vthrow .vt-division-buttons button{height:32px;padding:3px 5px;white-space:nowrap} +.mx-vthrow .vt-repeat-leds{display:flex;align-items:center;gap:5px; + white-space:nowrap;height:14px} +.mx-vthrow .vt-repeat-leds i{display:block;width:16px;height:3px; + border-radius:3px;background:#3d4550} +.mx-vthrow .vt-repeat-leds i[data-on=true]{background:#7bd4c7;box-shadow:0 0 4px #7bd4c755} +.mx-vthrow .vt-repeat-leds[data-playing=true] i[data-on=true]{background:#ade6d4} +.mx-vthrow .vt-music-source select{height:40px;width:100%;min-width:0;padding:0 11px; + border:1px solid #46515e;border-radius:5px;background:linear-gradient(#333a45,#252c36); + color:#e1e7ee;font:500 11px Inter,'Segoe UI',sans-serif} +.mx-vthrow .music-status{height:14px;line-height:14px;overflow:hidden;text-overflow:ellipsis; + white-space:nowrap;font-size:10px;color:#a2cfc6} +.mx-vthrow .vt-status-rail{height:30px;min-width:0;display:flex;align-items:center; + justify-content:space-between;gap:12px;padding:0 16px; + border-top:1px solid #090d13;background:linear-gradient(#272d36,#232831); + font-size:10px;letter-spacing:.02em;color:#a0adb9} +.mx-vthrow .vt-device{flex:0 0 auto;white-space:nowrap} +.mx-vthrow .dot{display:inline-block;width:6px;height:6px;margin-right:6px; + border-radius:50%;background:#6f7781;box-shadow:0 0 0 1px #10141a} +.mx-vthrow .dot.active{background:#79cbb8;box-shadow:0 0 5px #79cbb855} +.mx-vthrow .vt-hint{min-width:0;flex:1;text-align:center;overflow:hidden; + text-overflow:ellipsis;white-space:nowrap} +.mx-vthrow #vtCount{flex:0 0 auto;white-space:nowrap} +.mx-vthrow[data-fx-state=off] :is(.vt-encoder-face,.vt-throw-button), +.mx-vthrow[data-fx-state=rack-off] :is(.vt-encoder-face,.vt-throw-button){ + opacity:.55;filter:grayscale(.55) brightness(.77)} +@media(max-width:740px){ + .mx-vthrow{top:7px;left:7px} + .mx-vthrow .vt-console{padding:10px 12px 12px} + .mx-vthrow .vt-instrument{grid-template-columns:minmax(0,1fr) 184px minmax(0,1fr);gap:8px} + .mx-vthrow .vt-throw-button{width:184px;height:184px} + .mx-vthrow .vt-encoder{grid-template-rows:15px 60px 18px;row-gap:2px} + .mx-vthrow .vt-encoder-face{width:60px;height:60px} + .mx-vthrow .vt-encoder-name{font-size:9px} + .mx-vthrow .vt-encoder-needle::after{height:10px} + .mx-vthrow .vt-performance{grid-template-columns:75px minmax(0,1fr) 284px;column-gap:9px} + .mx-vthrow .vt-wet-module{width:75px} + .mx-vthrow .vt-wet-module .vt-encoder-face{width:60px;height:60px} + .mx-vthrow .vt-transport{gap:14px;padding:11px 12px} +} +@media(max-width:600px){ + .mx-vthrow{width:calc(100vw - 10px);max-height:calc(100dvh - 10px);left:5px;top:5px} + .mx-vthrow .vt-face-header{height:40px;flex-basis:40px;gap:6px;padding:0 9px} + .mx-vthrow .brand{gap:5px}.mx-vthrow .brand-mark{font-size:8px} + .mx-vthrow .brand-name{font-size:10.5px} + .mx-vthrow .channel{max-width:80px;font-size:9px} + .mx-vthrow .vt-preset select{width:83px;max-width:83px;font-size:10px} + .mx-vthrow .vt-console{padding:9px 11px 11px} + .mx-vthrow .vt-instrument{display:flex;flex-direction:column;gap:0} + .mx-vthrow .vt-center{order:0;margin-bottom:2px} + .mx-vthrow #vtEncodersLeft{order:1} + .mx-vthrow #vtEncodersRight{order:2} + .mx-vthrow .vt-throw-button{width:160px;height:160px} + .mx-vthrow .vt-throw-engraving{font-size:9px;margin-top:-4px} + .mx-vthrow .vt-encoder-bank{width:100%;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px} + .mx-vthrow .vt-encoder{grid-template-rows:14px 60px 16px;row-gap:2px;padding:1px 0} + .mx-vthrow .vt-encoder-face{width:60px;height:60px} + .mx-vthrow .vt-encoder-name{font-size:9.5px;line-height:14px} + .mx-vthrow .vt-encoder-value{font-size:11px;line-height:16px} + .mx-vthrow .vt-performance{grid-template-columns:minmax(78px,1fr) minmax(0,2fr); + column-gap:10px;row-gap:4px;min-height:0;margin-top:5px} + .mx-vthrow .vt-wet-module{width:100%;grid-template-rows:14px 60px 16px;row-gap:2px} + .mx-vthrow .vt-wet-module .vt-encoder-face{width:60px;height:60px} + .mx-vthrow .vt-clock-tap{grid-column:1/-1;grid-template-columns:minmax(0,1fr) 86px; + align-items:center;gap:10px;margin-top:2px} + .mx-vthrow .vt-clock-screen{height:83px} + .mx-vthrow #vtDisplayBpm{font-size:47px} + .mx-vthrow .vt-tap-button{height:83px} + .mx-vthrow .vt-mode-buttons{width:min(212px,100%);max-width:100%} + .mx-vthrow .vt-mode-buttons button{font-size:10px;min-height:31px;padding:3px 7px} + .mx-vthrow .vt-transport{grid-template-columns:1fr;gap:8px;padding:9px 11px} + .mx-vthrow .vt-division-buttons{height:38px} + .mx-vthrow .vt-division-buttons button{font-size:10px;height:30px} + .mx-vthrow .vt-music-source select{height:36px} + .mx-vthrow .vt-status-rail{gap:8px;padding:0 10px} +} +@media(max-width:350px){ + .mx-vthrow .channel{display:none} + .mx-vthrow .brand-name{font-size:9.5px} + .mx-vthrow .vt-preset select{width:74px} + .mx-vthrow .vt-mode-buttons button{padding:3px 5px} +} +@media(max-height:590px) and (min-width:601px){ + .mx-vthrow{top:4px;max-height:calc(100dvh - 8px)} + .mx-vthrow .vt-console{padding-top:6px;padding-bottom:7px} + .mx-vthrow .vt-throw-button{height:172px;width:172px} + .mx-vthrow .vt-instrument{grid-template-columns:minmax(0,1fr) 176px minmax(0,1fr)} +} +@media(prefers-reduced-motion:reduce){ + .mx-vthrow .vt-throw-button,.mx-vthrow .vt-throw-aura{transition:none} +} diff --git a/site/preview-v2/assets/mixer-native-compressor.js b/site/preview-v2/assets/mixer-native-compressor.js index 57bd82293..c9599c2ef 100644 --- a/site/preview-v2/assets/mixer-native-compressor.js +++ b/site/preview-v2/assets/mixer-native-compressor.js @@ -61,6 +61,7 @@ power.title="FX STATE UNAVAILABLE";power.dataset.fxState="unknown"; power.disabled=true;power.setAttribute("aria-pressed","false"); power.setAttribute("aria-label","Compressor state unavailable"); close.setAttribute("aria-label","Close Compressor"); +power.classList.add("armix-builtin-fx-power");close.classList.add("armix-builtin-fx-close"); header.append(brand,channel,presetSelect,stateDot,power,close); const controls=dom("div","mx-comp-controls"); const left=dom("div","mx-comp-left"); diff --git a/site/preview-v2/assets/mixer-native-peq.js b/site/preview-v2/assets/mixer-native-peq.js index e0b2e990e..270ec25b0 100644 --- a/site/preview-v2/assets/mixer-native-peq.js +++ b/site/preview-v2/assets/mixer-native-peq.js @@ -76,7 +76,8 @@ close.innerHTML=' { +"use strict"; +const ID="armix.builtin.vocal-throw.v1"; +const defaults=()=>({mode:2,bpm:120,division:0,repeats:3,captureMs:460, + silenceMs:220,thresholdDb:-35,wet:.42,decay:.55,ducking:.7}); +const presets={ + Concert:defaults(), + Fast:{...defaults(),division:1,repeats:4,captureMs:330,decay:.6}, + Ballad:{...defaults(),bpm:72,captureMs:650,wet:.48}, + Word:{...defaults(),mode:0,captureMs:280,silenceMs:180} +}; +const ranges={bpm:[60,200],repeats:[1,6],captureMs:[80,1500],silenceMs:[80,900], + thresholdDb:[-65,-15],wet:[0,1],decay:[.15,.9],ducking:[0,1]}; +const valid=s=>s&&[0,1,2].includes(s.mode)&&[0,1,2,3].includes(s.division)&& + Object.entries(ranges).every(([k,[min,max]])=> + Number.isFinite(s[k])&&s[k]>=min&&s[k]<=max); +const same=(a,b)=>Object.keys(defaults()).every(k=>a[k]===b[k]); +const clamp=(v,min,max)=>Math.max(min,Math.min(max,v)); +const backend=()=>window.__JUCE__?.backend; +const native=()=>typeof backend()?.emitEvent==="function"; +const snapshot=()=>window.__ARMIX_NATIVE_M2__?.state?.()?.current; + +const panel=document.createElement("section"); +panel.className="mx-vthrow";panel.id="mxNativeVocalThrow";panel.hidden=true; +panel.setAttribute("role","dialog");panel.setAttribute("aria-modal","false"); +panel.setAttribute("aria-label","ArSon Vocal Throw"); +// One universal 260-degree rounded level arc for EVERY hardware encoder. +// The face itself stays stationary; only the pointer and stroke advance. +const rotaryArc=''; +panel.innerHTML=[ + '
ARSONVOCAL THROW
', + '', + '', + '
', + '
', + '
', + '
', + '
MIX42%
', + '
', + '
TEMPOMAN
BPM
', + '
', + '
RHYTHM
1/4 · HYBRID
', + '
TAP
', + '
LIVE0
' +].join(""); +document.body.append(panel); +const $=id=>panel.querySelector("#"+id); +const encoderMeta={ + captureMs:["CAPTURE","ms",5,"vtEncodersLeft"], + silenceMs:["END","ms",10,"vtEncodersLeft"], + thresholdDb:["GATE","dB",1,"vtEncodersLeft"], + decay:["DECAY","%",.01,"vtEncodersRight"], + ducking:["DUCK","%",.01,"vtEncodersRight"], + repeats:["REPEATS","x",1,"vtEncodersRight"] +}; +for(const [key,[title,unit,,bank]] of Object.entries(encoderMeta)){ + const node=document.createElement("div"); + node.className="vt-encoder";node.dataset.key=key; + node.innerHTML=''+title+''+ + ''+ + ''; + node.querySelector("output").dataset.unit=unit; + $(bank).append(node); +} +let current=null,accepted=defaults(),draft=defaults(),pending=null, + readId="",readSent=0,seq=1,taps=[],windowDrag=null; +let tempoPending=null,musicSource="0",musicReadback=null; +const context=()=>{ + const state=snapshot(),id=current&&window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(current.track); + const fx=state?.graph?.channels?.find(ch=>ch.id===id)?.inserts?.[current?.slot]; + if(!state?.admitted||!id||fx?.catalogId!==ID||fx?.id!==current?.instanceId)return null; + return {channelId:id,slot:current.slot,instanceId:fx.id, + deviceEpoch:state.device.epoch,graphRevision:state.graph.revision}; +}; +const hint=text=>{$("vtHint").textContent=text;}; +function refreshMusicChannels(){ + const state=snapshot(),ctx=context(),selector=$("vtMusicSource"); + const selected=tempoPending?.source||musicSource; + const candidates=(state?.graph?.channels||[]).filter(ch=> + ch&&ch.id&&String(ch.id)!==String(ctx?.channelId)&& + ["INPUT","GROUP","FX_RETURN","FXRETURN"].includes( + String(ch.role||"").toUpperCase().replaceAll("-","_"))); + selector.replaceChildren(new Option("Manual / TAP","0")); + for(const ch of candidates)selector.add(new Option( + String(ch.name||ch.id).slice(0,45),String(ch.id))); + if([...selector.options].some(x=>x.value===String(selected))) + selector.value=String(selected); + else selector.value="0"; + selector.disabled=!ctx||!native()||Boolean(tempoPending); +} +function renderMusicStatus(tempo){ + if(tempo)musicReadback=tempo; + const label=$("vtMusicStatus"),clock=$("vtClockLabel"),number=$("vtDisplayBpm"); + const fallback=()=>{number.textContent=String(Math.round(accepted.bpm));clock.textContent="MAN";}; + if(tempoPending){label.textContent="CONNECT";label.title="Validating music channel";clock.textContent="CHECK";return;} + if(musicSource==="0"){label.textContent="TAP";label.title="Manual BPM / TAP";fallback();return;} + if(!musicReadback?.musicSourceActive){label.textContent="NO SIGNAL";label.title="Music source unavailable · manual BPM fallback";fallback();return;} + if(!musicReadback.musicLocked){label.textContent="LISTEN";label.title="Listening for beat · manual BPM fallback";fallback();return;} + const confidence=Math.round(Math.max(0,Math.min(1,Number(musicReadback.musicConfidence)||0))*100); + const beatGrid=musicReadback.musicGridAvailable===true; + const bpm=Math.round(Number(musicReadback.musicBpm)); + label.textContent=beatGrid?bpm+" · GRID":bpm+" · BPM"; + label.title="Auto tempo "+bpm+" BPM · "+confidence+"% confidence · "+(beatGrid?"beat grid":"BPM only"); + clock.textContent=beatGrid?"LOCK":"AUTO"; + number.textContent=String(bpm); +} +function syncPower(){ + const state=snapshot(),id=current&&window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(current.track); + const lane=state?.graph?.channels?.find(ch=>ch.id===id),fx=lane?.inserts?.[current?.slot]; + const value=!context()?"unknown":lane.fxRackBypassed?"rack-off":fx.bypassed?"off":"on"; + panel.dataset.fxState=value; + const btn=$("vtPower");btn.dataset.fxState=value; + btn.disabled=value==="unknown"||value==="rack-off"; + btn.title=value==="on"?"Active · click to bypass":value==="off"?"Bypassed · click to enable": + value==="rack-off"?"FX rack bypassed":"Native FX unavailable"; + btn.setAttribute("aria-pressed",String(value==="on")); + btn.setAttribute("aria-label",btn.title); + $("vtThrow").disabled=value!=="on"||!!pending; + $("vtStatus").textContent=value==="on"? + ($("vtThrow").dataset.tail==="true"?"TAIL":"LIVE"): + value==="off"?"BYPASS":value==="rack-off"?"RACK OFF":"OFFLINE"; +} +function paint(){ + $("vtMode").value=String(draft.mode); + if(panel.querySelector(".vt-clock-screen").dataset.editing!=="true") + $("vtBpm").value=String(draft.bpm); + $("vtDivision").value=String(draft.division);$("vtRepeats").value=String(draft.repeats); + for(const [key,[,unit]] of Object.entries(encoderMeta)){ + const node=panel.querySelector('.vt-encoder[data-key="'+key+'"]'); + const min=ranges[key][0],max=ranges[key][1]; + const pct=(draft[key]-min)/(max-min); + const turn=-130+260*pct; + node.style.setProperty("--turn",turn.toFixed(2)+"deg"); + // pathLength=100 guarantees a linearly advancing, rounded 260-degree arc. + // Never rotate the knob chassis with the pointer. + node.style.setProperty("--arc-offset",(100-pct*100).toFixed(3)); + node.querySelector(".vt-encoder-value").textContent= + (unit==="%"?Math.round(draft[key]*100):Math.round(draft[key]))+unit; + const dial=node.querySelector(".vt-encoder-face"); + dial.setAttribute("aria-valuemin",String(min)); + dial.setAttribute("aria-valuemax",String(max)); + dial.setAttribute("aria-valuenow",String(draft[key])); + dial.setAttribute("aria-valuetext",node.querySelector(".vt-encoder-value").textContent); + } + const wetPct=Math.round(draft.wet*100); + $("vtWetValue").textContent=wetPct+"%"; + $("vtWetDial").style.setProperty("--turn",(-130+260*draft.wet).toFixed(2)+"deg"); + $("vtWetDial").style.setProperty("--arc-offset",(100-draft.wet*100).toFixed(3)); + $("vtWetDial").setAttribute("aria-valuenow",String(wetPct)); + $("vtWetDial").setAttribute("aria-valuetext",wetPct+" percent"); + for(const b of panel.querySelectorAll(".vt-mode-buttons button")) + b.setAttribute("aria-pressed",String(Number(b.dataset.mode)===draft.mode)); + for(const b of panel.querySelectorAll(".vt-division-buttons button")) + b.setAttribute("aria-pressed",String(Number(b.dataset.division)===draft.division)); + $("vtPreset").value=Object.entries(presets).find(([,v])=>same(v,draft))?.[0]||"Custom"; + const rhythmic=["1/4","1/8","DOTTED 1/8","1/2"][accepted.division]; + const modes=["MANUAL","AUTO","HYBRID"]; + $("vtRhythm").textContent=rhythmic+" · "+modes[accepted.mode]; + for(const [index,led] of [...$("vtBeatRail").querySelectorAll("i")].entries()) + led.dataset.on=String(index{ + if(!current||pending)return; + bpmScreen.dataset.editing="true"; + $("vtBpm").value=String(draft.bpm); + $("vtBpm").focus();$("vtBpm").select(); +}); +$("vtBpm").addEventListener("keydown",e=>{ + if(e.key==="Escape"){ + e.preventDefault();e.stopPropagation(); + $("vtBpm").value=String(accepted.bpm); + $("vtBpm").blur(); + }else if(e.key==="Enter"){ + e.preventDefault();$("vtBpm").blur(); + } +}); +$("vtBpm").addEventListener("blur",()=>{bpmScreen.dataset.editing="false";}); +for(const [key,id] of [["mode","vtMode"],["bpm","vtBpm"], + ["division","vtDivision"],["repeats","vtRepeats"]]){ + $(id).addEventListener("change",()=>{ + draft={...draft,[key]:Number($(id).value)};paint();send("nativeThrowSet"); + }); +} +// Physical rotary control: vertical pointer drag, mouse wheel and keyboard. +// Update visual locally during movement; issue exactly ONE accepted native +// settings intent at drag release. No DOM/audio DSP loops are introduced. +function bindRotary(face,key,step){ + const [min,max]=ranges[key]; + const quantize=v=>clamp(Math.round(v/step)*step,min,max); + let gesture=null; + const update=v=>{if(pending)return;draft={...draft,[key]:quantize(v)};paint();}; + face.addEventListener("pointerdown",e=>{ + if(e.button!==0||pending)return; + gesture={id:e.pointerId,y:e.clientY,initial:draft[key],changed:false}; + face.setPointerCapture(e.pointerId);e.preventDefault(); + }); + face.addEventListener("pointermove",e=>{ + if(!gesture||gesture.id!==e.pointerId)return; + const next=quantize(gesture.initial+(gesture.y-e.clientY)*(max-min)/168); + if(next!==draft[key]){gesture.changed=true;update(next);} + e.preventDefault(); + }); + const finish=e=>{ + if(!gesture||e.pointerId!==gesture.id)return; + const changed=gesture.changed;gesture=null; + if(face.hasPointerCapture?.(e.pointerId))face.releasePointerCapture(e.pointerId); + if(changed)send("nativeThrowSet"); + }; + face.addEventListener("pointerup",finish); + face.addEventListener("pointercancel",()=>{gesture=null;paint();}); + face.addEventListener("wheel",e=>{ + if(pending)return; + e.preventDefault();update(draft[key]+(e.deltaY<0?step:-step)); + send("nativeThrowSet"); + },{passive:false}); + face.addEventListener("keydown",e=>{ + const delta={ArrowUp:1,ArrowRight:1,ArrowDown:-1,ArrowLeft:-1,PageUp:5,PageDown:-5}[e.key]; + if(delta===undefined&&e.key!=="Home"&&e.key!=="End")return; + e.preventDefault(); + update(e.key==="Home"?min:e.key==="End"?max:draft[key]+delta*step); + send("nativeThrowSet"); + }); + face.addEventListener("dblclick",()=>{ + if(pending)return; + update(defaults()[key]);send("nativeThrowSet"); + }); +} +for(const [key,[,,step]] of Object.entries(encoderMeta)) + bindRotary(panel.querySelector('.vt-encoder[data-key="'+key+'"] .vt-encoder-face'),key,step); +bindRotary($("vtWetDial"),"wet",.01); +for(const button of panel.querySelectorAll(".vt-mode-buttons button")){ + button.addEventListener("click",()=>{ + $("vtMode").value=button.dataset.mode; + $("vtMode").dispatchEvent(new Event("change",{bubbles:true})); + }); +} +for(const button of panel.querySelectorAll(".vt-division-buttons button")){ + button.addEventListener("click",()=>{ + $("vtDivision").value=button.dataset.division; + $("vtDivision").dispatchEvent(new Event("change",{bubbles:true})); + }); +} +$("vtMusicSource").addEventListener("change",()=>{ + const ctx=context(),source=String($("vtMusicSource").value); + if(!ctx||!native()||tempoPending){refreshMusicChannels();return;} + const requestId="tempo-"+Date.now()+"-"+(++seq); + tempoPending={requestId,source,created:Date.now()}; + backend().emitEvent("arMixAction",{ + action:"nativeThrowTempoSource",requestId,sourceChannelId:source,...ctx}); + renderMusicStatus();refreshMusicChannels(); +}); +$("vtPreset").addEventListener("change",()=>{ + const p=presets[$("vtPreset").value];if(!p)return; + draft={...p};paint();send("nativeThrowSet"); +}); +$("vtThrow").addEventListener("click",()=>send("nativeThrowTrigger")); +$("vtTap").addEventListener("click",()=>{ + const now=performance.now(); + if(taps.length&&now-taps[taps.length-1]>2500)taps=[]; + taps.push(now);if(taps.length>6)taps.shift(); + if(taps.length<3){hint("Tap at least three beats");return;} + const deltas=taps.slice(1).map((time,i)=>time-taps[i]).filter(v=>v>=280&&v<=1200); + if(deltas.length<2){hint("Tap a steady beat");return;} + const ordered=[...deltas].sort((a,b)=>a-b); + const median=ordered[Math.floor(ordered.length/2)]; + draft={...draft,bpm:clamp(Math.round(60000/median),60,200)}; + paint();send("nativeThrowSet"); +}); +$("vtPower").addEventListener("click",()=>{ + if(current&&context())window.__ARMIX_NATIVE_M2__?.consumeAction?.( + current.track,"slotPower",{dataset:{slot:String(current.slot)}}); +}); +$("vtClose").addEventListener("click",()=>{panel.hidden=true;pending=null;tempoPending=null;readId="";}); +window.addEventListener("keydown",e=>{ + if(e.key==="Escape"&&!panel.hidden){panel.hidden=true;pending=null;readId="";} +}); +const head=panel.querySelector("header"); +head.addEventListener("pointerdown",e=>{ + if(e.button||e.target.closest("button,select"))return; + const box=panel.getBoundingClientRect(); + windowDrag={id:e.pointerId,dx:e.clientX-box.left,dy:e.clientY-box.top}; + head.setPointerCapture(e.pointerId);e.preventDefault(); +}); +head.addEventListener("pointermove",e=>{ + if(!windowDrag||e.pointerId!==windowDrag.id)return; + panel.style.left=clamp(e.clientX-windowDrag.dx,0,Math.max(0,innerWidth-panel.offsetWidth))+"px"; + panel.style.top=clamp(e.clientY-windowDrag.dy,0,Math.max(0,innerHeight-panel.offsetHeight))+"px"; +}); +head.addEventListener("pointerup",e=>{windowDrag=null;head.releasePointerCapture?.(e.pointerId);}); +window.ArSonMixNativeVocalThrow=Object.freeze({ + id:ID, + insert(target){return Boolean(window.__ARMIX_NATIVE_M2__?.insertPlugin?.(ID,target));}, + open(track,slot){ + current={track,slot,instanceId:null};pending=null;tempoPending=null;musicSource="0";musicReadback=null;readId=""; + const state=snapshot(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); + const insert=state?.graph?.channels?.find(ch=>ch.id===id)?.inserts?.[slot]; + if(native()&&state?.admitted&&insert?.catalogId===ID&&insert.id){ + current.instanceId=insert.id;draft=defaults();accepted=defaults(); + hint(""); + }else if(!native()){draft=defaults();accepted=defaults(); + hint("Browser preview only · no PCM");} + else hint("Native FX instance unavailable"); + $("vtChannel").textContent=track.name||"CH"; + panel.hidden=false;paint();refreshMusicChannels();requestSnapshot(true); + }, + close(){panel.hidden=true;} +}); +backend()?.addEventListener?.("arMixBuiltinThrowTempoAck",reply=>{ + if(!tempoPending||reply?.requestId!==tempoPending.requestId)return; + if(reply.status==="APPLIED"){ + musicSource=tempoPending.source; + hint(""); + }else hint("Tempo source rejected · "+(reply.errorCode||"STALE")); + tempoPending=null;refreshMusicChannels();renderMusicStatus(); + requestSnapshot(true); +}); +backend()?.addEventListener?.("arMixBuiltinThrowQueue",reply=>{ + if(!pending||reply?.requestId!==pending.requestId)return; + if(reply.status==="REJECTED"){hint("DSP rejected · "+(reply.errorCode||"STALE")); + pending=null;requestSnapshot(true);syncPower();} +}); +backend()?.addEventListener?.("arMixBuiltinThrowAck",reply=>{ + if(!pending||reply?.requestId!==pending.requestId)return; + if(reply.status!=="APPLIED"){hint("DSP rejected · "+(reply.errorCode||"UNKNOWN")); + pending=null;requestSnapshot(true);syncPower();return;} + if(pending.command==="nativeThrowTrigger"){hint(""); + pending=null;requestSnapshot(true);syncPower();} + else{pending.ack=true;requestSnapshot(true);} +}); +backend()?.addEventListener?.("arMixBuiltinThrowSnapshot",reply=>{ + if(panel.hidden||reply?.requestId!==readId)return; + readId="";readSent=0; + const ctx=context(); + if(!ctx||reply.status!=="ACCEPTED"||reply.channelId!==ctx.channelId|| + reply.instanceId!==ctx.instanceId||reply.deviceEpoch!==ctx.deviceEpoch|| + reply.graphRevision!==ctx.graphRevision||!valid(reply.settings)|| + reply.addedLatencySamples!==0){hint("Stale FX graph · reopen editor");return;} + if(reply.musicSourceChannelId!==undefined) { + musicSource=String(reply.musicSourceChannelId||"0"); + refreshMusicChannels();renderMusicStatus(reply); + } + $("vtCount").textContent=String(reply.throwCount||0); + $("vtCount").setAttribute("aria-label",String(reply.throwCount||0)+" completed throws"); + $("vtDot").classList.toggle("active",reply.tailActive===true); + $("vtBeatRail").dataset.playing=String(reply.tailActive===true); + $("vtThrow").dataset.tail=String(reply.tailActive===true); + $("vtStatus").textContent=reply.tailActive?"TAIL":"LIVE"; + if(pending){ + if(!pending.ack||reply.appliedRequestId!==pending.requestId)return; + accepted={...reply.settings};draft={...accepted};pending=null; + hint(""); + }else{accepted={...reply.settings};draft={...accepted};} + paint(); +}); +backend()?.addEventListener?.("arMixConsoleSnapshot",()=>{ + if(panel.hidden)return; + if(native()&&!context()){ + pending=null;tempoPending=null; + hint("FX graph changed · reopen"); + } + refreshMusicChannels();syncPower(); +}); +window.setInterval(()=>{ + if(panel.hidden)return; + if(pending&&Date.now()-pending.created>3500){hint("DSP ACK timeout");pending=null;} + if(tempoPending&&Date.now()-tempoPending.created>3500){ + hint("Tempo source ACK timeout");tempoPending=null;refreshMusicChannels(); + } + if(native())requestSnapshot(); + syncPower(); +},250); +})(); diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 77cc2b4c5..58575dc32 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -14,6 +14,7 @@ #include "../engine/builtin_fx/ChannelEqProcessor.h" #include "../engine/builtin_fx/ChannelCompressorProcessor.h" #include "../engine/builtin_fx/ChannelHarmonyProcessor.h" +#include "../engine/builtin_fx/VocalThrowProcessor.h" #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/LiveSecondaryOutputDevice.h" @@ -1923,6 +1924,65 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } } + // ArSon Vocal Throw: single native PCM graph, same insert leases, bypass, + // ChannelId topology and dry monitoring as EQ/Compressor. + LiveDryRoutingLab::NativeBusResult installNativeBuiltInVocalThrow( + std::uint64_t ep,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId id) { + LiveDryRoutingLab::NativeBusResult fail{}; + fail.error="NATIVE_THROW_HOST_UNAVAILABLE"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(independent_.active()||!attached_||!device|| + !directFence_.permitted()||secondaryOutput_.armed()|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return fail; + if(ep!=dryRoutingLab_.epoch()){ + fail.error="NATIVE_THROW_DEVICE_CHANGED";return fail; + } + const auto rate=device->getCurrentSampleRate(); + const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + if(!(rate>=8000.&&rate<=192000.)|| + frames>LiveDryRoutingLab::Block::hardFrameLimit) { + fail.error="NATIVE_THROW_UNSUPPORTED_AUDIO_FORMAT";return fail; + } + try { + auto processor=std::make_unique(); + processor->prepareToPlay(rate,frames); + if(!processor->isReady()){ + fail.error="NATIVE_THROW_PREPARE_REJECTED";return fail; + } + auto lease=std::make_shared< + armix::mixer::LiveChannelFxGraph::FxInstance>( + std::move(processor), + juce::String(armix::builtin_fx::VocalThrowProcessor::catalogIdentity), + "ArSon Vocal Throw",LiveDryRoutingLab::Block::hardFrameLimit); + return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, + rosterRevision,id, + armix::builtin_fx::VocalThrowProcessor::catalogIdentity, + std::move(lease),true); + } catch(...) { + fail.error="NATIVE_THROW_PREPARE_EXCEPTION";return fail; + } + } + + bool selectNativeMusicTempoSource(std::uint64_t epoch,std::uint64_t revision, + armix::mixer::ChannelId musicChannel) noexcept { + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device||independent_.active()||!attached_||!directFence_.permitted()) + return false; + return dryRoutingLab_.selectMusicTempoSource(epoch,revision, + musicChannel,device->getCurrentSampleRate()); + } + armix::mixer::NativeMusicTempoMonitor::State pollNativeMusicTempo() noexcept { + return dryRoutingLab_.pollMusicTempo(); + } + template + void forEachNativeProcessor(Callback&& visit) const { + dryRoutingLab_.forEachNativeProcessor(std::forward(visit)); + } + // User-owned VST3 on a true dynamic ChannelId. Instantiation/scan/layout // work is CONTROL only; the callback receives an immutable fx lease. LiveDryRoutingLab::NativeBusResult installNativeVst3( diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index f404be1a4..08a706816 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -5,6 +5,7 @@ #include "../engine/core/MasterOutputMonoPolicy.h" #include "../engine/core/LiveChannelFxGraph.h" #include "../engine/core/DynamicChannelFxLeaseBank.h" +#include "../engine/core/NativeMusicTempoMonitor.h" #include "../engine/device/DeviceSessionTransitionPolicy.h" #include "../engine/core/NativeFxRackTransaction.h" #include "../engine/core/UnifiedLegacyProductionAdmission.h" @@ -1389,6 +1390,32 @@ class LiveDryRoutingLab final { return nativeAccepted_.setFxBypass(nativePublisher_,epochAtEdit, pcmRevision,target,slot,token,bypass); } + // Native music onset analysis has no secondary audio callback. A source + // selector is admitted only against the ACTIVE epoch/revision graph. + bool selectMusicTempoSource(std::uint64_t ep,std::uint64_t rev, + armix::mixer::ChannelId source,double sampleRate) noexcept { + if(!channelIdPhysicalPcmActive()||ep!=epoch()|| + rev!=nativeAccepted_.pcmRevision)return false; + return nativePublisher_.setMusicTempoSource(ep,rev,source,sampleRate); + } + armix::mixer::NativeMusicTempoMonitor::State pollMusicTempo() noexcept { + const auto ep=channelIdPhysicalPcmActive()?epoch():0; + return nativePublisher_.pollMusicTempo(ep,nativeAccepted_.pcmRevision); + } + // CONTROL traversal of the *published* insert owners. No audio-thread + // graph search or raw unmanaged pointers survive this synchronous call. + template + void forEachNativeProcessor(Callback&& visit) const { + if(!channelIdPhysicalPcmActive()||!nativeAccepted_.fxOwners)return; + for(const auto& ch:nativeAccepted_.graph.roster.channels()) { + const auto count=nativeAccepted_.fxOwners->insertCount(ch.id); + for(std::size_t slot=0;slotownerForControl(ch.id,slot); + if(owner && *owner && (*owner)->processor) + visit(ch.id,(*owner)->processor.get()); + } + } + } bool nativeChannelIsOriginalCh1(armix::mixer::ChannelId target) const noexcept { return nativeAccepted_.fxOwners && nativeAccepted_.fxOwners->externalChannel()==target && diff --git a/src/Main.cpp b/src/Main.cpp index d6391cc08..3b0aeed04 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -411,6 +411,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } pendingNativeHarmony_; juce::String lastNativeHarmonyRequest_,lastNativeHarmonyInstance_; juce::String lastNativeHarmonyEpoch_,lastNativeHarmonyRevision_; + struct PendingNativeThrow { + armix::mixer::LiveChannelFxGraph::InstanceLease owner; + juce::String request,channelId,deviceEpoch,revision,instanceId; + juce::uint32 started=0; + bool trigger=false; + } pendingNativeThrow_; + juce::String lastNativeThrowRequest_,lastNativeThrowInstance_; + juce::String lastNativeThrowEpoch_,lastNativeThrowRevision_; + armix::mixer::NativeMusicTempoMonitor::State lastMusicTempo_{}; std::unique_ptr editorWindow_; std::unique_ptr audioSetupWindow_; juce::String startupError_, lastAudioXml_; @@ -1094,9 +1103,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity; const bool builtInHarmony=catalogId== armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity; - const auto* plugin=(builtInEq||builtInComp||builtInHarmony)?nullptr:catalog_.find(catalogId); + const bool builtInThrow=catalogId== + armix::builtin_fx::VocalThrowProcessor::catalogIdentity; + const auto* plugin=(builtInEq||builtInComp||builtInHarmony||builtInThrow)?nullptr:catalog_.find(catalogId); std::uint64_t ep=0,rev=0,roster=0,target=0; - if((!builtInEq&&!builtInComp&&!builtInHarmony&&!plugin)||catalog_.busy()||nativeShowBusy_|| + if((!builtInEq&&!builtInComp&&!builtInHarmony&&!builtInThrow&&!plugin)||catalog_.busy()||nativeShowBusy_|| studioBackupBusy_||engine_.isGraphSwitchPending()) { nativeError="NATIVE_VST3_CATALOG_OR_HOST_BUSY"; } else if(!armix::console::approvedNativeId( @@ -1118,6 +1129,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr builtInHarmony? engine_.installNativeBuiltInHarmony( ep,rev,roster,armix::mixer::ChannelId{target}): + builtInThrow? + engine_.installNativeBuiltInVocalThrow( + ep,rev,roster,armix::mixer::ChannelId{target}): engine_.installNativeVst3( ep,rev,roster,armix::mixer::ChannelId{target}, plugin->path,plugin->uid,plugin->key()); @@ -2131,6 +2145,160 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixBuiltinHarmonyAck",juce::var(ack.release())); } + // CONTROL ONLY: drain at most 512 ten-ms music summary frames per 12Hz + // host tick. The actual music audio was tapped inside the existing PCM + // graph; BPM/onset analysis never touches the ASIO callback. All live + // vocal inserts consume a precomputed atomic interval, not a WebView BPM. + void serviceNativeMusicTempo() { + lastMusicTempo_=engine_.pollNativeMusicTempo(); + const bool bpmLocked=lastMusicTempo_.active&& + lastMusicTempo_.tempo.locked; + const bool phaseLocked=bpmLocked&& + lastMusicTempo_.tempo.phaseLocked&& + lastMusicTempo_.tempo.beatAnchorFrame>0; + const float bpm=bpmLocked?lastMusicTempo_.tempo.bpm:0.f; + const std::uint64_t anchor=phaseLocked? + lastMusicTempo_.tempo.beatAnchorFrame:0; + const auto epoch=lastMusicTempo_.epoch; + const auto revision=lastMusicTempo_.revision; + engine_.forEachNativeProcessor([bpm,anchor,epoch,revision]( + armix::mixer::ChannelId,juce::AudioProcessor* p) { + if(auto* vocal=dynamic_cast(p)) + vocal->publishMusicGrid(bpm,anchor,epoch,revision); + }); + } + + // Native Vocal Throw settings, manual cue and auto-trigger readback. + // Settings and triggers are not accepted until the AUDIO-owned SPSC + // completion is drained on JUCE's message thread. + void emitNativeThrowSnapshot(const juce::String& request, + const juce::String& channelId,const juce::String& epoch, + const juce::String& revision,const juce::String& instanceId, + armix::builtin_fx::VocalThrowProcessor* processor) { + auto reply=std::make_unique(); + reply->setProperty("requestId",request); + reply->setProperty("channelId",channelId); + reply->setProperty("deviceEpoch",epoch); + reply->setProperty("graphRevision",revision); + reply->setProperty("instanceId",instanceId); + reply->setProperty("schemaVersion",1); + reply->setProperty("status",processor?"ACCEPTED":"REJECTED"); + if(processor) { + auto settings=std::make_unique(); + const auto s=processor->acceptedSettings(); + settings->setProperty("mode",s.mode); + settings->setProperty("bpm",s.bpm); + settings->setProperty("division",s.division); + settings->setProperty("repeats",s.repeats); + settings->setProperty("captureMs",s.captureMs); + settings->setProperty("silenceMs",s.silenceMs); + settings->setProperty("thresholdDb",s.thresholdDb); + settings->setProperty("wet",s.wet); + settings->setProperty("decay",s.decay); + settings->setProperty("ducking",s.ducking); + reply->setProperty("settings",juce::var(settings.release())); + reply->setProperty("sampleRate",processor->acceptedSampleRate()); + // MUSIC tempo belongs to Vocal Throw, not to the unrelated EQ. + // Fence every displayed source/beat to THIS accepted graph. + // A retired device may leave a last control-timer snapshot; it + // must never appear as a locked beat on a newly opened device. + const bool currentMusicGraph=lastMusicTempo_.active&& + epoch==juce::String(std::to_string(lastMusicTempo_.epoch))&& + revision==juce::String(std::to_string(lastMusicTempo_.revision)); + reply->setProperty("musicSourceChannelId", + currentMusicGraph? + juce::String(std::to_string(lastMusicTempo_.source.value)): + juce::String("0")); + reply->setProperty("musicSourceActive",currentMusicGraph); + reply->setProperty("musicLocked",currentMusicGraph&& + lastMusicTempo_.tempo.locked); + reply->setProperty("musicBpm", + currentMusicGraph&&lastMusicTempo_.tempo.locked? + lastMusicTempo_.tempo.bpm:0.f); + reply->setProperty("musicConfidence", + currentMusicGraph?lastMusicTempo_.tempo.confidence:0.f); + reply->setProperty("musicGridAvailable",currentMusicGraph&& + lastMusicTempo_.tempo.locked&& + lastMusicTempo_.tempo.phaseLocked); + reply->setProperty("musicPhaseConfidence", + currentMusicGraph?lastMusicTempo_.tempo.phaseConfidence:0.f); + reply->setProperty("musicBeatAnchorFrame",juce::String( + std::to_string(currentMusicGraph? + lastMusicTempo_.tempo.beatAnchorFrame:0))); + reply->setProperty("musicDroppedFrames",currentMusicGraph? + static_cast(lastMusicTempo_.dropped):0); + + reply->setProperty("throwCount",static_cast(processor->observedThrowCount())); + reply->setProperty("tailActive",processor->observedTailActive()); + reply->setProperty("addedLatencySamples",processor->getLatencySamples()); + if(instanceId==lastNativeThrowInstance_&& + epoch==lastNativeThrowEpoch_&&revision==lastNativeThrowRevision_) + reply->setProperty("appliedRequestId",lastNativeThrowRequest_); + } else reply->setProperty("error","NATIVE_THROW_INSTANCE_OR_REVISION_UNAVAILABLE"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinThrowSnapshot",juce::var(reply.release())); + } + + void servicePendingNativeThrow() { + if(!pendingNativeThrow_.owner)return; + auto* processor=dynamic_cast( + pendingNativeThrow_.owner->processor.get()); + if(!processor){pendingNativeThrow_={};return;} + const auto request=pendingNativeThrow_.request; + const auto wire=request.startsWith("throw-")? + request.substring(6).toStdString():std::string(); + std::uint64_t requestId=0; + if(!wire.empty()&&wire.size()<=19&& + wire.find_first_not_of("0123456789")==std::string::npos) { + try{requestId=std::stoull(wire);}catch(...){requestId=0;} + } + // Old completions can arrive after a rejected timeout. Drain at + // most the bounded SPSC depth and ONLY ACK our exact request. + armix::builtin_fx::VocalThrowProcessor::Completion completion{},item{}; + bool matched=false; + for(int i=0;i<32 && processor->pollCompletion(item);++i) { + if(requestId && item.requestId==requestId) { + completion=item;matched=true;break; + } + } + if(!matched && + juce::Time::getMillisecondCounter()-pendingNativeThrow_.started<3000u) + return; + if(!matched)processor->cancelQueuedRequest(requestId); + bool applied=matched&&completion.applied&&requestId!=0; + const auto snap=approvedNativeSnapshot(); + const auto device=snap.getProperty("device",{}); + const auto graph=snap.getProperty("graph",{}); + applied=applied&&pendingNativeThrow_.deviceEpoch== + device.getProperty("epoch","").toString()&& + pendingNativeThrow_.revision== + graph.getProperty("revision","").toString(); + if(applied) { + lastNativeThrowRequest_=request; + lastNativeThrowInstance_=pendingNativeThrow_.instanceId; + lastNativeThrowEpoch_=pendingNativeThrow_.deviceEpoch; + lastNativeThrowRevision_=pendingNativeThrow_.revision; + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",pendingNativeThrow_.channelId); + ack->setProperty("deviceEpoch",pendingNativeThrow_.deviceEpoch); + ack->setProperty("graphRevision",pendingNativeThrow_.revision); + ack->setProperty("instanceId",pendingNativeThrow_.instanceId); + ack->setProperty("status",applied?"APPLIED":"REJECTED"); + ack->setProperty("command",pendingNativeThrow_.trigger? + "TRIGGER":"SETTINGS"); + ack->setProperty("errorCode",applied?"NONE":!matched? + "DSP_ACK_TIMEOUT_CANCELLED": + (pendingNativeThrow_.trigger&&completion.bypassed)? + "FX_BYPASSED_THROW_DISABLED": + pendingNativeThrow_.trigger? + "NO_CAPTURE_OR_STALE_GRAPH":"DSP_EDIT_NOT_APPLIED_OR_STALE"); + pendingNativeThrow_={}; + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinThrowAck",juce::var(ack.release())); + } + // Never confuse durable logical ChannelId state with a physical device // authorization. This message-thread report is status only, not PCM. void emitMixerSessionAck(const juce::String& operation, @@ -2151,7 +2319,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr for(auto& insert:doc.inserts) { if(insert.catalogId==armix::builtin_fx::ChannelEqProcessor::catalogIdentity || insert.catalogId==armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity || - insert.catalogId==armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity) { + insert.catalogId==armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity || + insert.catalogId==armix::builtin_fx::VocalThrowProcessor::catalogIdentity) { if(insert.path.isNotEmpty() || insert.uid!=0) return "Saved built-in FX identity was modified"; continue; @@ -2652,7 +2821,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "routingNativeFxRackBypass" || action == "routingNativeFxInsertBypass" || action == "routingFxRackBypass" || - action == "nativeEqSetBand" || action == "nativeCompSet")) + action == "nativeEqSetBand" || action == "nativeCompSet" || + action == "nativeThrowSet" || action == "nativeThrowTrigger" || + action == "nativeThrowTempoSource")) { const auto reason=juce::String( "Studio backup in progress. Finish backup before editing saved FX or VST library."); @@ -2989,6 +3160,116 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return; } + // ArSon Vocal Throw: all UI commands reference one exact installed + // ChannelId + device epoch + graph revision + insert instance. + if(action=="nativeThrowSnapshot"||action=="nativeThrowSet"|| + action=="nativeThrowTrigger"||action=="nativeThrowTempoSource") { + const auto rawChannel=args.getProperty("channelId",{}); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("graphRevision",{}); + const auto rawInstance=args.getProperty("instanceId",{}); + const auto request=args.getProperty("requestId",{}).toString(); + const int throwSlot=static_cast(args.getProperty("slot",-1)); + std::uint64_t ch=0,ep=0,rev=0; + const bool valid=armix::console::approvedNativeId(rawChannel,ch)&& + armix::console::approvedNativeId(rawEpoch,ep)&& + armix::console::approvedNativeId(rawRevision,rev)&& + rawInstance.isString()&&rawInstance.toString().isNotEmpty()&& + throwSlot>=0&&throwSlot(throwSlot), + rawInstance.toString()): + armix::mixer::LiveChannelFxGraph::InstanceLease{}; + auto* processor=owner?dynamic_cast( + owner->processor.get()):nullptr; + if(action=="nativeThrowSnapshot") { + emitNativeThrowSnapshot(request,rawChannel.toString(), + rawEpoch.toString(),rawRevision.toString(), + rawInstance.toString(),processor); + return; + } + if(action=="nativeThrowTempoSource") { + // A single shared song clock is selected by stable ChannelId; + // the source cannot be this vocal channel, MAIN or MONITOR. + const auto rawSource=args.getProperty("sourceChannelId",{}); + const auto sourceText=rawSource.toString(); + std::uint64_t source=0; + const bool parsed=sourceText=="0" || + armix::console::approvedNativeId(rawSource,source); + const bool chosen=processor && parsed && (!source||source!=ch) && + !nativeShowBusy_&&!studioBackupBusy_ && + engine_.selectNativeMusicTempoSource( + ep,rev,armix::mixer::ChannelId{source}); + if(chosen)serviceNativeMusicTempo(); + auto reply=std::make_unique(); + reply->setProperty("requestId",request); + reply->setProperty("status",chosen?"APPLIED":"REJECTED"); + reply->setProperty("sourceChannelId",sourceText); + reply->setProperty("errorCode",chosen?"NONE": + "INVALID_OR_STALE_MUSIC_CHANNEL"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinThrowTempoAck",juce::var(reply.release())); + return; + } + const auto wire=request.startsWith("throw-")? + request.substring(6).toStdString():std::string(); + std::uint64_t numeric=0; + if(!wire.empty()&&wire.size()<=19&& + wire.find_first_not_of("0123456789")==std::string::npos) { + try{numeric=std::stoull(wire);}catch(...){numeric=0;} + } + const bool isSettings=action=="nativeThrowSet"; + const auto values=args.getProperty("settings",{}); + armix::builtin_fx::VocalThrowSettings settings{}; + auto read=[&values](const char* key,float& out) { + const auto value=values.getProperty(key,{}); + if(!value.isInt()&&!value.isDouble())return false; + const auto v=static_cast(value); + if(!std::isfinite(v))return false; + out=static_cast(v); + return std::isfinite(out); + }; + auto integer=[&read](const char* key,int& out) { + float candidate=0.f; + if(!read(key,candidate)||candidate!=std::floor(candidate)|| + candidate<0.f||candidate>1000.f)return false; + out=static_cast(candidate);return true; + }; + const bool settingsValid=!isSettings || (values.isObject()&& + integer("mode",settings.mode)&&read("bpm",settings.bpm)&& + integer("division",settings.division)&&integer("repeats",settings.repeats)&& + read("captureMs",settings.captureMs)&&read("silenceMs",settings.silenceMs)&& + read("thresholdDb",settings.thresholdDb)&&read("wet",settings.wet)&& + read("decay",settings.decay)&&read("ducking",settings.ducking)&& + armix::builtin_fx::VocalThrow::validSettings(settings)); + bool queued=false; + if(processor&&numeric>0&&settingsValid&&!pendingNativeThrow_.owner&& + !nativeShowBusy_&&!studioBackupBusy_&&!engine_.independentClockActive()) { + queued=isSettings?processor->queueSettings(settings,numeric): + processor->queueTrigger(numeric); + if(queued) { + pendingNativeThrow_.owner=owner; + pendingNativeThrow_.request=request; + pendingNativeThrow_.channelId=rawChannel.toString(); + pendingNativeThrow_.deviceEpoch=rawEpoch.toString(); + pendingNativeThrow_.revision=rawRevision.toString(); + pendingNativeThrow_.instanceId=rawInstance.toString(); + pendingNativeThrow_.started=juce::Time::getMillisecondCounter(); + pendingNativeThrow_.trigger=!isSettings; + } + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("status",queued?"QUEUED":"REJECTED"); + ack->setProperty("errorCode",queued?"NONE": + pendingNativeThrow_.owner?"THROW_CONTROL_BUSY": + "INVALID_OR_STALE_NATIVE_THROW"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinThrowQueue",juce::var(ack.release())); + return; + } + // Route the approved channel FX picker to the SAME prepared M4 // graph as physical IN/OUT. ID resolves exclusively in the JUCE // catalog; browser paths/names are never trusted as plugin identity. @@ -4882,9 +5163,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr guiPerf_.prevTickMs = tickStart; } ++timerTicks_; + serviceNativeMusicTempo(); servicePendingNativeEq(); servicePendingNativeComp(); servicePendingNativeHarmony(); + servicePendingNativeThrow(); // A hidden JUCE/WebView2 peer may defer first navigation. Expose the // compositor behind the opaque startup splash after the first tick; // the user sees the completed mixer only after the ready handshake. diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h index 6fccac16f..c86211b53 100644 --- a/src/NativeMixerSessionFxRestore.h +++ b/src/NativeMixerSessionFxRestore.h @@ -6,6 +6,7 @@ #include "../engine/builtin_fx/ChannelEqProcessor.h" #include "../engine/builtin_fx/ChannelCompressorProcessor.h" #include "../engine/builtin_fx/ChannelHarmonyProcessor.h" +#include "../engine/builtin_fx/VocalThrowProcessor.h" #include #include #include @@ -95,6 +96,16 @@ class NativeMixerSessionFxRestore final { state.bytes.getData(),static_cast(state.bytes.getSize()))) return "Saved native Harmony state rejected; graph unchanged"; processor=std::move(harmony); + } else if(insert.catalogId== + armix::builtin_fx::VocalThrowProcessor::catalogIdentity) { + auto throwFx=std::make_unique(); + throwFx->prepareToPlay(sampleRate,frames); + if(!throwFx->isReady()|| + !throwFx->restoreUnpublishedState( + state.bytes.getData(), + static_cast(state.bytes.getSize()))) + return "Saved native Vocal Throw state rejected; graph unchanged"; + processor=std::move(throwFx); } else { if(!format|| !format->fileMightContainThisPluginType(insert.path)) @@ -116,7 +127,9 @@ class NativeMixerSessionFxRestore final { insert.catalogId!= armix::builtin_fx::ChannelCompressorProcessor::catalogIdentity && insert.catalogId!= - armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity) + armix::builtin_fx::ChannelHarmonyProcessor::catalogIdentity && + insert.catalogId!= + armix::builtin_fx::VocalThrowProcessor::catalogIdentity) processor->setStateInformation(state.bytes.getData(), static_cast(state.bytes.getSize())); const int latency=processor->getLatencySamples(); diff --git a/tests/approved_native_vocal_throw_smoke.py b/tests/approved_native_vocal_throw_smoke.py new file mode 100644 index 000000000..47951ab16 --- /dev/null +++ b/tests/approved_native_vocal_throw_smoke.py @@ -0,0 +1,369 @@ +"""Real approved /preview/ bundle: ArSon Vocal Throw picker, insert, native ACK. +The JUCE event transport is emulated, NOT the native DSP nor singing quality. +DSP is independently tested in standalone CTest on Windows.""" +import base64 +import copy +import xml.etree.ElementTree as ET +import importlib.util +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot, emit, ack, SOURCE, RECEIVER + +ROOT=Path(__file__).resolve().parents[1] +ID="armix.builtin.vocal-throw.v1" +INSTANCE="vocal-throw-test-instance" +DEFAULTS={"mode":2,"bpm":120,"division":0,"repeats":3, + "captureMs":460,"silenceMs":220,"thresholdDb":-35, + "wet":.42,"decay":.55,"ducking":.7} + +def last(page,action): + records=page.evaluate("name=>window.__actions.filter(x=>x.action===name)",action) + assert records, "No "+action+" event" + return records[-1] + +def reply_snapshot(page,state,settings,applied=None,count=0,tail=False,music=None): + act=last(page,"nativeThrowSnapshot") + data={"requestId":act["requestId"],"channelId":SOURCE,"slot":0, + "instanceId":INSTANCE,"status":"ACCEPTED","schemaVersion":1, + "deviceEpoch":state["device"]["epoch"], + "graphRevision":state["graph"]["revision"],"sampleRate":48000, + "addedLatencySamples":0,"throwCount":count,"tailActive":tail, + "musicSourceChannelId":music["source"] if music else "0", + "musicSourceActive":bool(music), + "musicLocked":bool(music), + "musicBpm":music["bpm"] if music else 0, + "musicConfidence":music["confidence"] if music else 0, + "musicGridAvailable":music.get("grid",False) if music else False, + "musicPhaseConfidence":music["confidence"] if music and music.get("grid",False) else 0, + "settings":copy.deepcopy(settings)} + if applied:data["appliedRequestId"]=applied + emit(page,"arMixBuiltinThrowSnapshot",data) + +def main(): + spec=importlib.util.spec_from_file_location( + "bundle",ROOT/"scripts/build_approved_native_gui.py") + bundle=importlib.util.module_from_spec(spec);spec.loader.exec_module(bundle) + # Owner-provided purple illuminated hardware button (tombol_ungu.svg). + # Fail closed on a missing/rasterized asset or an unsafe remote image href. + source_svg=(ROOT/"site/preview-v2/assets/arson-vocal-throw-performance.svg").read_text() + assert 'viewBox="0 0 327 327"' in source_svg + assert '10000, "do not replace premium artwork with a low-detail icon" + assert not any(v.startswith(('http:', 'https:', 'file:')) + for el in root.iter() for k,v in el.attrib.items() if k.endswith('href')) + assert '_Linear6' in source_svg and '_Linear7' in source_svg + with tempfile.TemporaryDirectory(prefix="armix-throw-") as directory,sync_playwright() as pw: + out=Path(directory);bundle.stage(out) + browser=pw.chromium.launch(headless=True) + # Desktop, constrained desktop and portrait operator control panel. + for width,height in [(1366,768),(650,720),(390,844)]: + page=browser.new_page(viewport={"width":width,"height":height}) + errors=[] + page.on("pageerror",lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map(); + window.__nativeIntents=[];window.__actions=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){ + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload); + if(name==='arMixAction')window.__actions.push(payload);}, + addEventListener(name,callback){ + const old=window.__nativeListeners.get(name); + window.__nativeListeners.set(name,old? + payload=>{old(payload);callback(payload);}:callback);}}};""") + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled && window.ArSonMixNativeVocalThrow") + state=snapshot() + state["graph"]["capabilities"]["supportedOps"]+=["LOAD_INSERT","REMOVE_INSERT","MOVE_INSERT"] + emit(page,"arMixConsoleSnapshot",state) + if width<=500:page.locator("#bankSelect").select_option("0") + strip=page.locator('#tracks .strip[data-id="1"]') + strip.locator('.fx-pick.empty').first.click() + picker=page.locator("#fastResults [data-fast-native-throw]") + picker.wait_for(state="visible") + assert picker.count()==1,"exactly one Vocal Throw built-in picker option" + picker.click() + intents=page.evaluate("""()=>window.__nativeIntents.filter( + x=>x.operation==='LOAD_INSERT')""") + assert len(intents)==1,intents + assert intents[0]["payload"]["catalogId"]==ID + assert page.locator("#mxNativeVocalThrow").is_hidden(),"no editor before accepted insert" + state["graph"].update(revision="3",rosterRevision="3") + state["graph"]["channels"][0]["fxRackBypassed"]=False + state["graph"]["channels"][0]["inserts"].append({ + "id":INSTANCE,"catalogId":ID,"name":"ArSon Vocal Throw","bypassed":False}) + state["mixerSession"].update(routeRevision="3",rosterRevision="3", + channels=copy.deepcopy(state["graph"]["channels"])) + ack(page,state,intents[0]);emit(page,"arMixConsoleSnapshot",state) + row=strip.locator('.fxslot-row[data-insert-id="'+INSTANCE+'"]') + row.wait_for(state="visible") + page.keyboard.press("Escape") + row.locator('[data-action="openPlugin"]').click() + editor=page.locator("#mxNativeVocalThrow") + editor.wait_for(state="visible") + assert editor.locator("#vtPreset").count()==1 + assert editor.locator("#vtClose.mx-comp-close.armix-floating-close").count()==1 + assert editor.locator("#vtPower.mx-comp-power.armix-builtin-fx-power").count()==1 + assert editor.locator("#vtClose.armix-builtin-fx-close").count()==1 + assert page.locator("#mxNativePeq .armix-builtin-fx-power").count()==1 + assert page.locator("#mxNativePeq .armix-builtin-fx-close").count()==1 + assert page.locator("#mxNativeComp .armix-builtin-fx-power").count()==1 + assert page.locator("#mxNativeComp .armix-builtin-fx-close").count()==1 + assert editor.locator("#vtPower").get_attribute("data-fx-state")=="on" + assert editor.locator("#vtPower").get_attribute("aria-pressed")=="true" + # EQ and Compressor have ONE CSS owner for 24px Close and 26px + # Power hit boxes, the same as Vocal Throw (no local overrides). + close_box=editor.locator("#vtClose").bounding_box() + power_box=editor.locator("#vtPower").bounding_box() + assert close_box and power_box + assert abs(close_box["width"]-24)<.1 and abs(close_box["height"]-24)<.1 + assert abs(power_box["width"]-26)<.1 and abs(power_box["height"]-24)<.1 + assert power_box["x"]+power_box["width"]<=close_box["x"]+1 + assert editor.locator("#vtMode").input_value()=="2" + initial=last(page,"nativeThrowSnapshot") + page.wait_for_timeout(300) + assert last(page,"nativeThrowSnapshot")["requestId"]==initial["requestId"],\ + "snapshot polling overwrote outstanding request too early" + reply_snapshot(page,state,DEFAULTS) + assert editor.locator("#vtStatus").inner_text()=="LIVE" + assert editor.locator("#vtCount").inner_text()=="0" + box=editor.bounding_box() + assert box and box["width"]<=778 and box["width"]<=width and \ + box["x"]>=0 and box["x"]+box["width"]<=width+1,(width,box) + assert editor.evaluate("(el)=>el.scrollWidth<=el.clientWidth+1"),\ + "premium FX editor overflows horizontal viewport" + assert editor.locator("#vtDisplayBpm").inner_text()=="120" + assert editor.locator("#vtClockLabel").inner_text()=="MAN" + # BPM is one integrated LCD number, not a detached duplicate. + # Click the LCD to enter editing; Escape restores the accepted + # native setting without issuing a new DSP command. + assert editor.locator("#vtBpm").is_hidden() + editor.locator("#vtDisplayBpm").click() + assert editor.locator("#vtBpm").is_visible() + assert editor.locator("#vtBpm").input_value()=="120" + editor.locator("#vtBpm").fill("133") + editor.locator("#vtBpm").press("Escape") + assert editor.locator("#vtBpm").is_hidden() + assert editor.locator("#vtDisplayBpm").inner_text()=="120" + assert editor.locator("#vtBeatRail i[data-on='true']").count()==3 + assert editor.locator(".vt-encoder-bank .vt-encoder-face").count()==6 + assert editor.locator("#vtWetDial[role='slider']").count()==1 + assert editor.locator(".vt-throw-button").count()==1 + trigger=editor.locator("#vtThrow") + assert trigger.get_attribute("aria-label")=="Throw captured vocal phrase" + assert trigger.inner_text().strip()=="","Singer cue has no noisy visible words" + tb=trigger.bounding_box() + assert tb and tb["width"]>=160 and tb["height"]>=160 + assert editor.locator(".vt-throw-engraving").inner_text()=="THROW" + assert editor.locator("#vtTap").is_visible() + assert editor.locator("#vtMusicStatus").inner_text()=="TAP" + assert "FIRE PHRASE" not in editor.inner_text() + assert "SMART PHRASE / LIVE ENGINE" not in editor.inner_text() + assert "ZERO DRY LATENCY" not in editor.inner_text() + assert editor.locator(".vt-mode-buttons button").count()==3 + assert editor.locator(".vt-division-buttons button").count()==4 + # No browser form hiding of basic parameters: real accessible + # hardware rotary controls are displayed at desktop AND mobile. + assert editor.locator("#vtWetDial").is_visible() + assert editor.locator('.vt-encoder[data-key="captureMs"] button').is_visible() + # Every control, including MIX, has the exact SAME stationary + # knob body, pointer and rounded level arc geometry. + assert editor.locator(".vt-encoder-face").count()==7 + assert editor.locator(".vt-meter-fill").count()==7 + assert editor.locator(".vt-knob-meter").count()==7 + for dial in editor.locator(".vt-encoder-face").all(): + bg=dial.evaluate("(el)=>getComputedStyle(el).backgroundImage") + assert "arson-vocal-hardware-encoder.svg" in bg,bg + assert dial.locator(".vt-meter-fill").get_attribute("pathLength")=="100" + # Inspect the actual rendered SVG control backgrounds. WebView + # file:// disables fetch() for SVG files, not CSS backgrounds. + for selector,name in [("#vtWetDial","encoder"), + ('.vt-encoder-face',"encoder"), + ("#vtThrow","performance")]: + bg=editor.locator(selector).first.evaluate( + "(el)=>getComputedStyle(el).backgroundImage") + assert ("arson-vocal-throw-performance.svg" if name=="performance" + else "arson-vocal-hardware-"+name+".svg") in bg,(selector,bg) + # Bounded physical layout QA, not just a screenshot. The large + # singer switch must be centered, the two encoder banks in + # alignment, and tempo LCD and TAP must be physically adjacent. + throw=editor.locator("#vtThrow").bounding_box() + left=editor.locator("#vtEncodersLeft").bounding_box() + right=editor.locator("#vtEncodersRight").bounding_box() + lcd=editor.locator(".vt-clock-screen").bounding_box() + tap=editor.locator("#vtTap").bounding_box() + assert all([throw,left,right,lcd,tap]) + assert abs((throw["x"]+throw["width"]/2)-(box["x"]+box["width"]/2))<4, \ + ("THROW is off center",width,throw,box) + if width>600: + assert abs(left["y"]-right["y"])<3, ("uneven encoder rows",left,right) + assert left["x"]+left["width"]<=throw["x"]+1 and \ + throw["x"]+throw["width"]<=right["x"]+1, \ + ("encoders invade singer button",left,throw,right) + else: + assert throw["y"]+throw["height"]=145 and lcd["height"]>=70 + # Text must have a real cell, not be squeezed against a knob. + # Three columns in each bank share exact name/rotary/value + # baselines; this caught the original tiny asymmetric 8px text. + for bank in ("#vtEncodersLeft","#vtEncodersRight"): + names=editor.locator(bank+" .vt-encoder-name") + dials=editor.locator(bank+" .vt-encoder-face") + values=editor.locator(bank+" .vt-encoder-value") + assert names.count()==dials.count()==values.count()==3 + labels=[el.bounding_box() for el in names.all()] + knobs=[el.bounding_box() for el in dials.all()] + nums=[el.bounding_box() for el in values.all()] + assert max(x["y"] for x in labels)-min(x["y"] for x in labels)<1 + assert max(x["y"] for x in knobs)-min(x["y"] for x in knobs)<1 + assert max(x["y"] for x in nums)-min(x["y"] for x in nums)<1 + for n,k,v in zip(labels,knobs,nums): + center=lambda b:b["x"]+b["width"]/2 + assert abs(center(n)-center(k))<1.5 and \ + abs(center(v)-center(k))<1.5, \ + ("rotary name/value not centered",width,n,k,v) + assert n["y"]+n["height"]<=k["y"]+1 and \ + k["y"]+k["height"]<=v["y"]+1, \ + ("control text collides with rotary",width,n,k,v) + for name in names.all(): + assert name.evaluate("""el=> + parseFloat(getComputedStyle(el).fontSize)>=9 && + el.scrollWidth<=el.clientWidth+1"""), \ + ("encoder caption is too small or clipped",width, + name.inner_text()) + wet=editor.locator("#vtWetDial").bounding_box() + mode=editor.locator(".vt-mode-buttons").bounding_box() + assert wet and mode + assert abs((wet["y"]+wet["height"]/2)- + (mode["y"]+mode["height"]/2))<11, \ + ("MIX and trigger controls are vertically off-axis",width,wet,mode) + # Every song-source selector has a deliberate text space. + song=editor.locator("#vtMusicSource").bounding_box() + assert song and song["width"]>=180,("MUSIC selector too narrow",width,song) + assert editor.locator("#vtMusicSource").evaluate("""el=> + el.scrollWidth<=el.clientWidth+1""") + if width>600: + rhythm=editor.locator(".vt-pulse .vt-small-label").bounding_box() + music=editor.locator(".vt-music-source .vt-small-label").bounding_box() + assert rhythm and music and abs(rhythm["y"]-music["y"])<1, \ + ("RHYTHM and MUSIC section labels not aligned",width,rhythm,music) + rail=editor.locator(".vt-status-rail").bounding_box() + assert rail and rail["y"]+rail["height"]<=box["y"]+box["height"]+2, \ + ("footer clipped beneath mobile controls",width,rail,box) + # No control may draw past the horizontal plugin bounds. + for control in ["#vtThrow","#vtTap","#vtWetDial", + "#vtClockLabel","#vtDisplayBpm"]: + rect=editor.locator(control).bounding_box() + assert rect and rect["x"]>=box["x"]-1 and \ + rect["x"]+rect["width"]<=box["x"]+box["width"]+1,(control,rect,box) + page.screenshot(path="arsonmix-vocal-throw-"+str(width)+".png") + editor.screenshot(path="arsonmix-vocal-throw-editor-"+str(width)+".png") + if width==1366: + editor.locator('.vt-mode-buttons button[data-mode="0"]').click() + edit=last(page,"nativeThrowSet") + assert edit["settings"]["mode"]==0 and edit["instanceId"]==INSTANCE + assert edit["channelId"]==SOURCE + emit(page,"arMixBuiltinThrowQueue",{"requestId":edit["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinThrowAck",{"requestId":edit["requestId"],"status":"APPLIED"}) + reply_snapshot(page,state,{**DEFAULTS,"mode":0},applied=edit["requestId"]) + assert editor.locator("#vtMode").input_value()=="0" + assert editor.locator('.vt-mode-buttons button[data-mode="0"]').get_attribute("aria-pressed")=="true" + # Rotary wheel edits actually send settings through the native + # request/ACK/readback contract, not a CSS-only animation. + dial=editor.locator("#vtWetDial") + before=dial.evaluate("""el=>({ + offset:parseFloat(getComputedStyle(el.querySelector('.vt-meter-fill')).strokeDashoffset), + transform:getComputedStyle(el.querySelector('.vt-encoder-needle')).transform, + bg:getComputedStyle(el).backgroundImage + })""") + dial.hover() + page.mouse.wheel(0,-120) + after=dial.evaluate("""el=>({ + offset:parseFloat(getComputedStyle(el.querySelector('.vt-meter-fill')).strokeDashoffset), + transform:getComputedStyle(el.querySelector('.vt-encoder-needle')).transform, + bg:getComputedStyle(el).backgroundImage + })""") + assert float(after["offset"]).42 and rotary["settings"]["wet"]<=.44 + emit(page,"arMixBuiltinThrowQueue",{"requestId":rotary["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinThrowAck",{"requestId":rotary["requestId"],"status":"APPLIED"}) + updated={**DEFAULTS,"mode":0,"wet":rotary["settings"]["wet"]} + reply_snapshot(page,state,updated,applied=rotary["requestId"]) + assert "%" in editor.locator("#vtWetValue").inner_text() + editor.locator("#vtThrow").click() + assert editor.locator("#vtThrow").is_disabled(), "no repeated stage cue until native ACK" + cue=last(page,"nativeThrowTrigger") + assert cue["instanceId"]==INSTANCE and cue["channelId"]==SOURCE + assert cue["slot"]==0 + emit(page,"arMixBuiltinThrowQueue",{"requestId":cue["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinThrowAck",{"requestId":cue["requestId"],"status":"APPLIED"}) + reply_snapshot(page,state,{**DEFAULTS,"mode":0,"wet":rotary["settings"]["wet"]},count=1,tail=True) + assert editor.locator("#vtCount").inner_text()=="1" + assert editor.locator("#vtStatus").inner_text()=="TAIL" + assert editor.locator("#vtThrow").get_attribute("data-tail")=="true" + assert not editor.locator("#vtThrow").is_disabled() + # Real native tempo-source command (not a browser-only BPM guess). + source_menu=editor.locator("#vtMusicSource") + assert source_menu.locator('option[value="'+RECEIVER+'"]').count()==1 + source_menu.select_option(RECEIVER) + request=last(page,"nativeThrowTempoSource") + assert request["sourceChannelId"]==RECEIVER and request["channelId"]==SOURCE + assert editor.locator("#vtMusicStatus").inner_text()=="CONNECT" + emit(page,"arMixBuiltinThrowTempoAck",{ + "requestId":request["requestId"],"status":"APPLIED", + "sourceChannelId":RECEIVER}) + reply_snapshot(page,state, + {**DEFAULTS,"mode":0,"wet":rotary["settings"]["wet"]} if width==1366 else DEFAULTS, + count=1 if width==1366 else 0,tail=width==1366, + music={"source":RECEIVER,"bpm":120,"confidence":.85}) + assert editor.locator("#vtMusicStatus").inner_text()=="120 · BPM" + assert editor.locator("#vtClockLabel").inner_text()=="AUTO" + # Snapshot transport is request/response, not unsolicited push. + # Wait for a fresh native read request before testing a second + # DSP status update; a replay of the prior request is ignored. + previous=last(page,"nativeThrowSnapshot")["requestId"] + page.wait_for_function( + """old=>window.__actions.filter(x=>x.action==='nativeThrowSnapshot').at(-1)?.requestId!==old""", + arg=previous,timeout=4000) + # Confidence-approved grid is a separate native fact; the GUI + # must never fabricate it from BPM alone. + reply_snapshot(page,state, + {**DEFAULTS,"mode":0,"wet":rotary["settings"]["wet"]} if width==1366 else DEFAULTS, + count=1 if width==1366 else 0,tail=width==1366, + music={"source":RECEIVER,"bpm":120,"confidence":.85,"grid":True}) + assert editor.locator("#vtMusicStatus").inner_text()=="120 · GRID" + assert editor.locator("#vtClockLabel").inner_text()=="LOCK" + if width==1366: + # The next changed graph invalidates the old editor instance. + state["graph"]["channels"][0]["inserts"][0]["id"]="replaced-instance" + state["graph"].update(revision="4",rosterRevision="4") + state["mixerSession"].update(routeRevision="4",rosterRevision="4", + channels=copy.deepcopy(state["graph"]["channels"])) + emit(page,"arMixConsoleSnapshot",state) + page.wait_for_function("""()=>document.querySelector('#vtThrow')?.disabled""",timeout=2000) + editor.locator("#vtClose").click() + assert editor.is_hidden(),"standard close must dismiss editor" + assert not errors,(width,errors) + page.close() + browser.close() + print("PASS: ArSon Vocal Throw native picker/ACK/manual cue/compact editor in 2 viewports") + +if __name__=="__main__": + main() diff --git a/tests/builtin_vocal_throw_test.cpp b/tests/builtin_vocal_throw_test.cpp new file mode 100644 index 000000000..30f125715 --- /dev/null +++ b/tests/builtin_vocal_throw_test.cpp @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/builtin_fx/VocalThrow.h" +#include +#include +#include +#include +#include +#include +#include +#include +#define check(x) do {if(!(x)){std::fprintf(stderr,"FAIL:%s:%d %s\n",__FILE__,__LINE__,#x);std::abort();}}while(false) +// Catch allocations from inside the audio callback, not from preparation. +static std::atomic noHeap{false}; +void* operator new(std::size_t n) { + if(noHeap.load(std::memory_order_relaxed))std::abort(); + if(void* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + if(noHeap.load(std::memory_order_relaxed))std::abort(); + if(void* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept{std::free(p);} +void operator delete[](void* p) noexcept{std::free(p);} +void operator delete(void* p,std::size_t) noexcept{std::free(p);} +void operator delete[](void* p,std::size_t) noexcept{std::free(p);} + +using armix::builtin_fx::VocalThrow; +using armix::builtin_fx::VocalThrowSettings; +static void run(VocalThrow& fx,float l,float r,int frames,float& maxL,float& maxR) { + std::array left{},right{}; + for(int begin=0;begin(n)); + noHeap.store(false,std::memory_order_release); + for(int i=0;i::quiet_NaN(); + check(!VocalThrow::prepareEdit(settings,48000,packet)); + settings=VocalThrowSettings{};settings.mode=3; + check(!VocalThrow::prepareEdit(settings,48000,packet)); + settings=VocalThrowSettings{};settings.repeats=7; + check(!VocalThrow::prepareEdit(settings,48000,packet)); + settings=VocalThrowSettings{};settings.captureMs=1550; + check(!VocalThrow::prepareEdit(settings,48000,packet)); +} +static void manualAndDry(double rate) { + VocalThrow fx;check(fx.prepare(rate)); + auto s=fx.settingsForTests();s.mode=0;s.captureMs=300;s.silenceMs=150; + check(fx.resetUnpublished(s)); + float peakL=0,peakR=0; + // No trigger: the leading vocalist is bit-exact dry, even in an insert. + std::array left{},right{}; + left.fill(.35f);right.fill(-.20f); + noHeap.store(true); + fx.processStereo(left.data(),right.data(),left.size()); + noHeap.store(false); + for(std::size_t n=0;n(rate*.35),peakL,peakR); + run(fx,0,0,static_cast(rate*.06),peakL,peakR); + check(fx.throwCount()==0); + noHeap.store(true); + const bool fired=fx.throwNow(); + noHeap.store(false); + check(fired&&fx.throwCount()==1); + peakL=peakR=0; + run(fx,0,0,static_cast(rate*.10),peakL,peakR); + check(peakL==0&&peakR==0); // beat-scheduled, no immediate echo smear + run(fx,0,0,static_cast(rate*.75),peakL,peakR); + check(peakL>.01f&&peakR>.005f); + // Recorded stereo is preserved (same gain on both channels). + check(peakL>peakR*1.4f); + noHeap.store(true); + const bool staleCue=fx.throwNow(); + noHeap.store(false); + check(!staleCue); // 700ms after last vocal: never report an empty throw +} +static void automaticAndHybrid(double rate) { + VocalThrow fx;check(fx.prepare(rate)); + auto s=fx.settingsForTests(); + s.mode=1;s.captureMs=220;s.silenceMs=120;s.thresholdDb=-30; + check(fx.resetUnpublished(s)); + float l=0,r=0; + run(fx,.5f,.35f,static_cast(rate*.3),l,r); + run(fx,0,0,static_cast(rate*.23),l,r); + check(fx.throwCount()==1); + run(fx,0,0,static_cast(rate*1.0),l,r); + check(fx.throwCount()==1); // no retrigger on the echoed tail + run(fx,.5f,.35f,static_cast(rate*.28),l,r); + run(fx,0,0,static_cast(rate*.23),l,r); + check(fx.throwCount()==2); + +} +static void hybridEditAndNoHeap() { + VocalThrow fx;check(fx.prepare(48000)); + VocalThrowSettings s{};s.mode=2;s.bpm=95;s.division=1;s.repeats=6; + VocalThrow::PreparedEdit edit{};check(VocalThrow::prepareEdit(s,48000,edit)); + check(!fx.applyPrepared(VocalThrow::PreparedEdit{})); + auto stale=edit;stale.sampleRate=44100;check(!fx.applyPrepared(stale)); + noHeap.store(true);const bool ok=fx.applyPrepared(edit);noHeap.store(false); + check(ok); + float l=0,r=0; + run(fx,.4f,.2f,10000,l,r); + noHeap.store(true);const bool fired=fx.throwNow();noHeap.store(false); + check(fired); + run(fx,0,0,200000,l,r); + check(std::isfinite(l)&&std::isfinite(r)); +} +// Two separate frozen phrases must coexist. A new cue must not chop the +// already sounding repeat. All fixtures run as bounded PCM chunks without +// any callback allocations, including at the highest allowed device rate. +static void twoTailsStayLive(double rate) { + VocalThrow reference,overlap; + check(reference.prepare(rate)&&overlap.prepare(rate)); + auto s=reference.settingsForTests(); + s.mode=0;s.bpm=200;s.division=1;s.repeats=3; + s.captureMs=300;s.silenceMs=120; + check(reference.resetUnpublished(s)&&overlap.resetUnpublished(s)); + float l=0.f,r=0.f; + auto both=[&](float input,int frames) { + run(reference,input,input*.5f,frames,l,r); + run(overlap,input,input*.5f,frames,l,r); + }; + both(.5f,static_cast(rate*.20)); + both(0.f,static_cast(rate*.10)); + noHeap.store(true); + const bool firstA=reference.throwNow(),firstB=overlap.throwNow(); + noHeap.store(false); + check(firstA&&firstB); + both(.4f,static_cast(rate*.12)); + both(0.f,static_cast(rate*.03)); + noHeap.store(true); + const bool second=overlap.throwNow(); + const bool saturated=overlap.throwNow(); + noHeap.store(false); + check(second&&!saturated); + check(overlap.throwCount()==2); + // From 0.45 to 0.485 s the second voice is preparing, and its first + // scheduled echo is still in the future. Output must be IDENTICAL to + // the reference's first tail, not abruptly muted by the second cue. + std::array refL{},refR{},mixL{},mixR{}; + float maxReference=0.f,maxOverlap=0.f; + const int compareFrames=static_cast(rate*.035); + for(int done=0;done(std::min(128,compareFrames-done)); + refL.fill(0.f);refR.fill(0.f);mixL.fill(0.f);mixR.fill(0.f); + noHeap.store(true); + reference.processStereo(refL.data(),refR.data(),count); + overlap.processStereo(mixL.data(),mixR.data(),count); + noHeap.store(false); + for(std::size_t i=0;i.001f&&maxOverlap>.001f); + run(overlap,0.f,0.f,static_cast(rate*.8),l,r); + check(overlap.throwCount()==2); +} +static void autoThenManualMustNotDoubleEcho() { + VocalThrow fx;check(fx.prepare(48000)); + auto s=fx.settingsForTests(); + s.mode=2;s.silenceMs=120;s.captureMs=250; + check(fx.resetUnpublished(s)); + float l=0.f,r=0.f; + run(fx,.5f,.25f,14400,l,r); + run(fx,0.f,0.f,12000,l,r); + check(fx.throwCount()==1); + noHeap.store(true); + const bool duplicated=fx.throwNow(); + noHeap.store(false); + check(!duplicated&&fx.throwCount()==1); + // A fresh phrase re-arms the manual path: previous auto trigger must + // not poison legitimate new cues when the singer starts again. + run(fx,.5f,.25f,12000,l,r); + noHeap.store(true); + const bool newPhrase=fx.throwNow(); + noHeap.store(false); + check(newPhrase&&fx.throwCount()==2); +} +static void denseRepeatsStayBounded() { + VocalThrow fx;check(fx.prepare(48000)); + auto settings=fx.settingsForTests(); + settings.mode=0;settings.bpm=200;settings.division=1; + settings.repeats=6;settings.decay=.9f; + settings.captureMs=1200.f;settings.wet=1.f;settings.ducking=0.f; + check(fx.resetUnpublished(settings)); + float maxL=0.f,maxR=0.f; + run(fx,.75f,.6f,48000,maxL,maxR); + noHeap.store(true); + const bool fired=fx.throwNow(); + noHeap.store(false); + check(fired); + maxL=maxR=0.f; + run(fx,0.f,0.f,static_cast(48000*2.5),maxL,maxR); + check(maxL>.20f&&maxR>.10f); + // An exposed six-tap feedback-like burst must not produce >0dBFS + // solely because echo taps overlap (dry path is unchanged). + check(maxL<=.751f&&maxR<=.601f); +} +static void manualOverrideSuppressesAuto() { + VocalThrow fx;check(fx.prepare(48000)); + auto s=fx.settingsForTests(); + s.mode=2;s.silenceMs=160;s.captureMs=250; + check(fx.resetUnpublished(s)); + float l=0.f,r=0.f; + run(fx,.5f,.25f,12000,l,r); // phrase 1 + run(fx,0.f,0.f,2400,l,r); // manual cue before auto silence timeout + noHeap.store(true); + const bool fired=fx.throwNow(); + noHeap.store(false); + check(fired&&fx.throwCount()==1); + run(fx,0.f,0.f,12000,l,r); + check(fx.throwCount()==1); // same phrase must not double-fire + run(fx,.5f,.25f,12000,l,r); // genuinely new phrase + // The 18ms release envelope must fall below the voice gate BEFORE + // the 160ms silence threshold begins. 208ms total is insufficient + // with a sustained 0.5 peak and threshold -35dB. + run(fx,0.f,0.f,9000,l,r); + check(fx.throwCount()==1); // no premature false-positive throw + run(fx,0.f,0.f,5000,l,r); + check(fx.throwCount()==2); // new phrase, after full release + gate +} +// Accepted music BPM affects only new frozen tails, never retimes a tail +// already singing. An unlocked source must use persisted Manual/TAP BPM. +static void musicTempoChangesOnlyFutureTail() { + VocalThrow music,manual; + check(music.prepare(48000)&&manual.prepare(48000)); + auto s=music.settingsForTests(); + s.mode=0;s.bpm=120.f;s.division=0;s.repeats=1; + s.captureMs=120.f;s.wet=1.f;s.ducking=0.f; + check(music.resetUnpublished(s)&&manual.resetUnpublished(s)); + float a=0.f,b=0.f; + run(music,.6f,.4f,12000,a,b); + run(manual,.6f,.4f,12000,a,b); + run(music,0.f,0.f,2880,a,b); + run(manual,0.f,0.f,2880,a,b); + noHeap.store(true); + music.setMusicIntervalSamples(16000); // quarter-note at 180 BPM + const bool firedMusic=music.throwNow(); + const bool firedManual=manual.throwNow(); + // The selected backing bus can disappear immediately after the cue. + // Its already frozen tail must retain the accepted .25s repeat interval. + music.setMusicIntervalSamples(0); + noHeap.store(false); + check(firedMusic&&firedManual); + a=b=0.f; + run(music,0.f,0.f,12960,a,b); // 270 ms after cue + check(a==0.f&&b==0.f); + a=b=0.f; + run(music,0.f,0.f,8160,a,b); // repeat around 290-410 ms + check(a>.01f&&b>.01f); + a=b=0.f; + run(manual,0.f,0.f,17760,a,b); // manual .5s must still be silent + check(a==0.f&&b==0.f); + a=b=0.f; + run(manual,0.f,0.f,7680,a,b); + check(a>.01f&&b>.01f); +} +// M3 beat-phase regression. Vocal PCM remains zero-latency dry, while the +// first frozen echo is snapped to the accepted source beat lattice. Changing +// transport AFTER the cue never changes the frozen tail's scheduled onset. +static void nativeMusicBeatGridQuantization(int quantum) { + VocalThrow gridded,unquantized; + check(gridded.prepare(48000)&&unquantized.prepare(48000)); + auto settings=gridded.settingsForTests(); + settings.mode=0;settings.captureMs=120.f; + settings.repeats=1;settings.bpm=120.f; + settings.division=0;settings.wet=1.f;settings.ducking=0.f; + check(gridded.resetUnpublished(settings)); + check(unquantized.resetUnpublished(settings)); + float l=0.f,r=0.f; + run(gridded,.65f,.35f,12000,l,r); + run(unquantized,.65f,.35f,12000,l,r); + run(gridded,0.f,0.f,3000,l,r); + run(unquantized,0.f,0.f,3000,l,r); + // Both processors have local sample 15000. Music tempo is 180 BPM + // (16000 sample quarter) with an observed beat at graph frame 100. + gridded.setMusicBeatGrid(16000,100,15000,true); + noHeap.store(true,std::memory_order_release); + const auto snapped=gridded.throwNow(); + const auto plain=unquantized.throwNow(); + // Simulate late rejection of source / changed BPM immediately following + // the cue. The old grid snapshot must remain in this tail. + gridded.setMusicBeatGrid(10000,15000,15000,false); + noHeap.store(false,std::memory_order_release); + check(snapped&&plain); + const auto onset=[&](VocalThrow& fx) { + std::array ll{},rr{}; + for(int start=0;start<50000;start+=quantum) { + const int n=std::min(quantum,50000-start); + ll.fill(0.f);rr.fill(0.f); + noHeap.store(true,std::memory_order_release); + fx.processStereo(ll.data(),rr.data(),static_cast(n)); + noHeap.store(false,std::memory_order_release); + for(int k=0;k.0002f)return start+k; + } + } + return -1; + }; + // First native music grid point >= intended onset: frame 32100. + // Cue at graph frame 15000 => first wet sample around offset 17100. + const int quantized=onset(gridded); + const int fallback=onset(unquantized); + check(quantized>=17100&&quantized<17120); + check(fallback>=23980&&fallback<25000); // manual 120 BPM / quarter + check(quantized+5000 +#include +#include +#include +#include +#include +#include +#define check(x) do {if(!(x)){std::fprintf(stderr,"FAIL:%s:%d %s\n",__FILE__,__LINE__,#x);std::abort();}}while(false) +static std::atomic noHeap{false}; +void* operator new(std::size_t n) { + if(noHeap.load(std::memory_order_relaxed))std::abort(); + if(void* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + if(noHeap.load(std::memory_order_relaxed))std::abort(); + if(void* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept {std::free(p);} +void operator delete[](void* p) noexcept {std::free(p);} +void operator delete(void* p,std::size_t) noexcept {std::free(p);} +void operator delete[](void* p,std::size_t) noexcept {std::free(p);} +using armix::mixer::ChannelId; +using armix::mixer::NativeMusicTempoMonitor; +static void renderWindow(NativeMusicTempoMonitor& tap,int index,int period, + float beat=.7f,bool weakOffbeats=false, + std::uint64_t epoch=7,std::uint64_t revision=13, + std::uint64_t controlNowMs=0) { + std::array l{},r{}; + const int pos=index%period; + const float level=pos==0?beat: + weakOffbeats&&pos==period/2?.07f:0.f; + l.fill(level);r.fill(level); + // A 10ms bucket is split across 64+36 ASIO callback frames at 10kHz. + noHeap.store(true,std::memory_order_release); + (void)tap.beginAudioBlock(epoch,64); + tap.capture(ChannelId{301},l.data(),r.data(),64,epoch,revision); + (void)tap.beginAudioBlock(epoch,36); + tap.capture(ChannelId{301},l.data()+64,r.data()+64,36,epoch,revision); + noHeap.store(false,std::memory_order_release); + if(index%8==0)(void)tap.poll(epoch,revision,controlNowMs); // host timer, not RT +} +static void lockTempo(int bpm,bool hats=false) { + NativeMusicTempoMonitor tap; + check(!tap.select(ChannelId{301},7,13,0)); + check(tap.select(ChannelId{301},7,13,10000)); + auto state=tap.poll(7,13); + check(state.active&&state.source.value==301&&!state.tempo.locked); + const int period=static_cast(std::lround(6000.0/bpm)); + for(int n=0;n<1100;++n)renderWindow(tap,n,period,.75f,hats); + state=tap.poll(7,13); + check(state.tempo.locked); + check(std::abs(state.tempo.bpm-bpm)<=3.1f); + check(state.tempo.confidence>=.28f); + // Sparse pair scoring uses only qualifying BPM neighborhoods instead + // of 121 complete rescans. This is a deterministic, hardware-neutral + // CONTROL timer budget, NOT a wall-clock benchmark. + check(state.tempo.scoringComparisons>0); + check(state.tempo.scoringComparisons<120000); + check(state.tempo.phaseLocked && state.tempo.phaseConfidence>=.50f); + check(state.tempo.beatAnchorTick>0); + check(state.tempo.beatAnchorFrame>0); + check(state.tempo.observationFrame>state.tempo.beatAnchorFrame); + check(state.dropped==0); + // One second of no music must NOT produce spurious half/double BPM. + for(int n=1100;n<1200;++n)renderWindow(tap,n,6000); + state=tap.poll(7,13); + check(state.tempo.locked); + // The user must see manual/TAP fallback after >3.2s of silence. + for(int n=1200;n<1580;++n)renderWindow(tap,n,6000); + state=tap.poll(7,13); + check(!state.tempo.locked); +} +// A full backing groove can carry snare/hi-hat accents on the eighth-note +// offbeat. Its BPM may be correct while a quarter-note phase is ambiguous. +static void harmonicAndPhaseAmbiguity() { + NativeMusicTempoMonitor tap; + check(tap.select(ChannelId{301},7,13,10000)); + const auto groove=[&](int index,float offbeat) { + std::array left{},right{}; + const int p=index%50; // quarter note at 120 BPM + const float value=p==0?.78f:p==25?offbeat:0.f; + left.fill(value);right.fill(value); + noHeap.store(true,std::memory_order_release); + (void)tap.beginAudioBlock(7,64); + tap.capture(ChannelId{301},left.data(),right.data(),64,7,13); + (void)tap.beginAudioBlock(7,36); + tap.capture(ChannelId{301},left.data()+64,right.data()+64,36,7,13); + noHeap.store(false,std::memory_order_release); + if(index%8==0)(void)tap.poll(7,13); + }; + for(int i=0;i<1150;++i)groove(i,.035f); + auto baseline=tap.poll(7,13); + check(baseline.tempo.locked && std::abs(baseline.tempo.bpm-120.f)<=3.f); + check(baseline.tempo.phaseLocked); + // For 11s, the equal-strength offbeat pulse could be mistaken for a + // new beat lattice; do not switch to 60 BPM, or claim a phase lock. + for(int i=1150;i<2450;++i)groove(i,.78f); + auto ambiguous=tap.poll(7,13); + check(ambiguous.tempo.locked); + check(ambiguous.tempo.scoringComparisons>0); + check(ambiguous.tempo.scoringComparisons<120000); + check(std::abs(ambiguous.tempo.bpm-120.f)<=3.f); + check(!ambiguous.tempo.phaseLocked); + // The music clears; the true quarter-note lattice should recover. + for(int i=2450;i<3650;++i)groove(i,.035f); + auto recovered=tap.poll(7,13); + if(!recovered.tempo.locked || std::abs(recovered.tempo.bpm-120.f)>3.f) + std::fprintf(stderr, + "MUSIC_OFFBEAT_RECOVERY tick=3650 locked=%d bpm=%.3f confidence=%.3f phase=%d phaseConfidence=%.3f comparisons=%u dropped=%u\n", + static_cast(recovered.tempo.locked),recovered.tempo.bpm, + recovered.tempo.confidence,static_cast(recovered.tempo.phaseLocked), + recovered.tempo.phaseConfidence,recovered.tempo.scoringComparisons, + recovered.dropped); + check(recovered.tempo.locked); + check(recovered.tempo.scoringComparisons>0); + check(recovered.tempo.scoringComparisons<120000); + check(std::abs(recovered.tempo.bpm-120.f)<=3.f); + check(recovered.tempo.phaseLocked); + check(recovered.dropped==0); +} +// A formerly locked backing can switch to densely accented but weak +// percussion. This is enough rhythmic activity to score a candidate, yet +// NOT enough evidence to keep the old beat grid or invent a new one. +static void weakBusyGrooveMustReleaseBeatGrid() { + NativeMusicTempoMonitor tap; + check(tap.select(ChannelId{301},7,13,10000)); + for(int n=0;n<1100;++n)renderWindow(tap,n,50,.78f); + auto locked=tap.poll(7,13); + check(locked.tempo.locked&&locked.tempo.phaseLocked); + for(int n=1100;n<2350;++n)renderWindow(tap,n,8,.10f); + const auto ambiguous=tap.poll(7,13); + check(ambiguous.active); + check(!ambiguous.tempo.locked && !ambiguous.tempo.phaseLocked); + check(ambiguous.tempo.confidence<.28f); + check(ambiguous.dropped==0); + // Once clear music returns the phase can be acquired again. + for(int n=2350;n<3550;++n)renderWindow(tap,n,50,.78f); + const auto recovered=tap.poll(7,13); + if(!recovered.tempo.locked || std::abs(recovered.tempo.bpm-120.f)>3.f) + std::fprintf(stderr, + "MUSIC_WEAK_RECOVERY locked=%d bpm=%.3f confidence=%.3f phase=%d phaseConfidence=%.3f comparisons=%u dropped=%u\n", + static_cast(recovered.tempo.locked),recovered.tempo.bpm, + recovered.tempo.confidence,static_cast(recovered.tempo.phaseLocked), + recovered.tempo.phaseConfidence,recovered.tempo.scoringComparisons, + recovered.dropped); + check(recovered.tempo.locked && + std::abs(recovered.tempo.bpm-120.f)<=3.f); + check(recovered.tempo.phaseLocked); +} +// If the audio callback stops entirely (ASIO suspension/reconfiguration), + // tick-based expiry alone cannot advance: fail closed on CONTROL time. +static void stoppedAudioCallbackMustRevokeOldBeat() { + NativeMusicTempoMonitor tap; + check(tap.select(ChannelId{301},7,13,10000)); + for(int n=0;n<1100;++n) + renderWindow(tap,n,50,.75f,false,7,13,1000+static_cast(n)*10); + auto locked=tap.poll(7,13,12000); + check(locked.active && locked.tempo.locked && locked.tempo.phaseLocked); + // A short interruption must not cause a needless BPM reset. + const auto hold=tap.poll(7,13,14450); + check(hold.active && hold.tempo.locked); + // No render/capture calls at all for >3.5s: stale beat cannot survive. + const auto stale=tap.poll(7,13,15501); + check(stale.active && stale.source.value==301); + check(!stale.tempo.locked && !stale.tempo.phaseLocked); + check(stale.tempo.beatAnchorFrame==0 && stale.tempo.bpm==0.f); + // Resume the very same source; require fresh musical evidence. + for(int n=1100;n<2300;++n) + renderWindow(tap,n,50,.75f,false,7,13, + 15510+static_cast(n-1100)*10); + const auto recovered=tap.poll(7,13,27600); + check(recovered.active && recovered.tempo.locked); + check(recovered.tempo.phaseLocked && std::abs(recovered.tempo.bpm-120.f)<=3.f); +} +static void steadyPadIsNotAClock() { + NativeMusicTempoMonitor tap; + check(tap.select(ChannelId{301},7,13,10000)); + std::array pcm{};pcm.fill(.22f); + for(int index=0;index<1200;++index) { + noHeap.store(true); + (void)tap.beginAudioBlock(7,100); + tap.capture(ChannelId{301},pcm.data(),pcm.data(),100,7,13); + noHeap.store(false); + if(index%8==0)(void)tap.poll(7,13); + } + const auto state=tap.poll(7,13); + check(!state.tempo.locked); + // A sustained pad is not evidence of rhythm. It cannot trigger a + // high-cost candidate scan simply because PCM keeps arriving. + check(state.tempo.scoringComparisons==0); +} +static void failClosed() { + NativeMusicTempoMonitor tap; + check(tap.select(ChannelId{301},7,13,48000)); + std::array pcm{};pcm.fill(.8f); + noHeap.store(true); + for(int i=0;i<240;++i) { + // Wrong channel and wrong graph revision must not populate the FIFO. + tap.capture(ChannelId{302},pcm.data(),pcm.data(),128,7,13); + tap.capture(ChannelId{301},pcm.data(),pcm.data(),128,7,14); + } + noHeap.store(false); + auto stale=tap.poll(7,14); + check(!stale.active&&!stale.tempo.locked); + auto active=tap.poll(7,13); + check(active.active&&!active.tempo.locked); + check(tap.select(ChannelId{},7,13,0)); + check(!tap.poll(7,13).active); +} +static void actualGraphSourcePcm() { + using namespace armix::mixer; + DynamicChannelRoster roster; + ChannelEdit source,main; + source.kind=ChannelEdit::Kind::add;source.position=0; + source.role=ChannelRole::input;source.text="BACKING"; + main.kind=ChannelEdit::Kind::add;main.position=1; + main.role=ChannelRole::main;main.text="MAIN"; + main.format=ProcessingFormat::stereo; + const std::array adds{source,main}; + const auto created=roster.edit(0,adds); + check(created.ok()&&created.createdIds.size()==2); + const auto music=created.createdIds[0],master=created.createdIds[1]; + ChannelEdit output; + output.kind=ChannelEdit::Kind::setPrimaryOutput; + output.id=music;output.target=master; + const std::array links{output}; + check(roster.edit(1,links).ok()); + DynamicGraphRequest request; + request.physicalInputs=1;request.maxFrames=128; + request.sources={{music,0,-1,false}}; + DynamicNativeSessionPublisher graph; + constexpr std::uint64_t epoch=7; + const auto applied=graph.commit(roster,request,0,epoch,epoch,true); + check(applied.ok()&&applied.revision==1); + check(!graph.setMusicTempoSource(epoch,1,master,10000)); // MAIN forbidden + check(!graph.setMusicTempoSource(epoch-1,1,music,10000)); + check(graph.setMusicTempoSource(epoch,1,music,10000)); + std::array input{},outL{},outR{}; + const float* physical[]{input.data()}; + int expectedTick=0; + const auto dryFx=[&](ChannelId,float*,float*,int n) noexcept { + const auto current=NativeBeatFrameScope::current(); + check(current.valid && current.epoch==epoch && + current.revision==1 && n==100); + check(current.startFrame==static_cast(expectedTick)*100); + }; + for(int tick=0;tick<1000;++tick) { + input.fill((tick%50)==0?.65f:0.f); // 120 BPM from real graph + noHeap.store(true,std::memory_order_release); + expectedTick=tick; + const bool rendered=graph.render(epoch,physical,1, + outL.data(),outR.data(),100,false,dryFx); + noHeap.store(false,std::memory_order_release); + check(rendered); + if(tick%8==0)(void)graph.pollMusicTempo(epoch,1); + } + auto state=graph.pollMusicTempo(epoch,1); + check(state.active&&state.source==music); + check(state.tempo.locked&&std::abs(state.tempo.bpm-120.f)<=3.f); + check(state.tempo.phaseLocked&&state.tempo.phaseConfidence>=.50f); + check(state.tempo.beatAnchorFrame>0 && + state.tempo.beatAnchorFrame<=100000); + check(state.tempo.observationFrame>=state.tempo.beatAnchorFrame); + check(!NativeBeatFrameScope::current().valid); // callback scope restored + // The *same* music ChannelId survives a graph revision with no second + // callback or preserved stale PCM pointers. + const auto newer=graph.commit(roster,request,1,epoch,epoch,true); + check(newer.ok()&&newer.revision==2); + state=graph.pollMusicTempo(epoch,2); + check(state.active&&state.source==music); + check(!graph.pollMusicTempo(epoch,1).active); + const auto newGraphFx=[&](ChannelId,float*,float*,int n) noexcept { + const auto block=NativeBeatFrameScope::current(); + check(block.valid && block.epoch==epoch && + block.revision==2 && block.startFrame==100000 && n==100); + }; + noHeap.store(true,std::memory_order_release); + const bool next=graph.render(epoch,physical,1, + outL.data(),outR.data(),100,false,newGraphFx); + noHeap.store(false,std::memory_order_release); + check(next); + check(!NativeBeatFrameScope::current().valid); + graph.unpublish(); + graph.pollRetirement(); +} +static void callbackClockEpochAndNestedScope() { + using armix::mixer::NativeBeatFrameScope; + NativeMusicTempoMonitor tap; + check(!NativeBeatFrameScope::current().valid); + noHeap.store(true,std::memory_order_release); + check(tap.beginAudioBlock(82,64)==0); + check(tap.beginAudioBlock(82,128)==64); + { + NativeBeatFrameScope outer{82,7,192}; + const auto a=NativeBeatFrameScope::current(); + check(a.valid&&a.epoch==82&&a.revision==7&&a.startFrame==192); + { + NativeBeatFrameScope nested{82,8,320}; + const auto b=NativeBeatFrameScope::current(); + check(b.valid&&b.revision==8&&b.startFrame==320); + } + const auto restored=NativeBeatFrameScope::current(); + check(restored.valid&&restored.revision==7&&restored.startFrame==192); + } + check(!NativeBeatFrameScope::current().valid); + check(tap.beginAudioBlock(82,256)==192); + // Physical device restart must establish a NEW sample origin. This + // prevents a beat from the old ASIO epoch appearing on the new device. + check(tap.beginAudioBlock(83,64)==0); + check(tap.beginAudioBlock(83,128)==64); + noHeap.store(false,std::memory_order_release); +} +int main() { + lockTempo(72); + lockTempo(95); + lockTempo(120); + lockTempo(160); + lockTempo(120,true); + harmonicAndPhaseAmbiguity(); + weakBusyGrooveMustReleaseBeatGrid(); + stoppedAudioCallbackMustRevokeOldBeat(); + steadyPadIsNotAClock(); + failClosed(); + callbackClockEpochAndNestedScope(); + actualGraphSourcePcm(); + std::puts("PASS: native music-channel BPM 72/95/120/160, silence holdover, stale graph, no RT heap"); +} diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py index 890d798f1..069bd4889 100644 --- a/tests/native_peq_assembly_test.py +++ b/tests/native_peq_assembly_test.py @@ -24,6 +24,9 @@ def test_one_authoritative_mixer(self): self.assertEqual(self.assembled.count('src="assets/mixer-native-peq.js?v=eq-graph1"'),1) self.assertEqual(self.assembled.count('src="assets/mixer-native-compressor.js?v=comp-1"'),1) self.assertEqual(self.assembled.count("function insertChosenNativeCompressor(){"),1) + self.assertEqual(self.assembled.count("function insertChosenNativeThrow(){"),1) + self.assertEqual(self.assembled.count('src="assets/mixer-native-vocal-throw.js?v=throw-1"'),1) + self.assertEqual(self.assembled.count('data-fast-native-throw="1"'),1) def test_native_rack_uses_regular_insert_slot(self): self.assertIn("host.insert(activeFxTarget)",self.assembled) @@ -35,6 +38,7 @@ def test_native_rack_uses_regular_insert_slot(self): self.assertEqual(self.assembled.count('data-fast-native-eq="1"'),1) self.assertEqual(self.assembled.count('data-fast-native-comp="1"'),1) self.assertIn("if(t.fx[index]==='Compressor')",self.assembled) + self.assertIn("if(t.fx[index]==='ArSon Vocal Throw')",self.assembled) def test_single_style_owner(self): # The approved CSS compiler requires exactly 18 component-owner links. @@ -54,6 +58,50 @@ def test_single_style_owner(self): self.assertIn('addedLatencySamples!==0',compressor) self.assertNotIn("new AudioContext",compressor) self.assertIn(".mx-comp[hidden]{display:none}",css) + throw=(ROOT/"site/preview-v2/assets/mixer-native-vocal-throw.js").read_text("utf-8") + self.assertIn("arMixBuiltinThrowAck",throw) + self.assertIn("arMixBuiltinThrowSnapshot",throw) + self.assertIn("nativeThrowTrigger",throw) + self.assertIn('id="vtPreset"',throw) + self.assertIn("armix-floating-close",throw) + self.assertNotIn("new AudioContext",throw) + + def test_native_tempo_readback_belongs_to_vocal_throw_not_eq(self): + # The real C++ dispatcher must populate the exact VocalThrow + # snapshot, not an unrelated EQ response. Browser-only mocks cannot + # catch a payload sent on the wrong native event. + main=(ROOT/"src/Main.cpp").read_text("utf-8") + def body(start,finish): + self.assertEqual(main.count(start),1) + return main.split(start,1)[1].split(finish,1)[0] + eq=body("void emitNativeEqSnapshot(", + "void servicePendingNativeEq()") + vocal=body("void emitNativeThrowSnapshot(", + "void servicePendingNativeThrow()") + fields=("musicSourceChannelId","musicSourceActive", + "musicLocked","musicBpm","musicConfidence", + "musicGridAvailable","musicPhaseConfidence", + "musicBeatAnchorFrame","musicDroppedFrames") + for field in fields: + self.assertIn('reply->setProperty("'+field+'"',vocal, + "missing accepted Vocal Throw BPM field: "+field) + self.assertNotIn('reply->setProperty("'+field+'"',eq, + "cross-FX snapshot pollution: "+field) + # After device restart or graph change the last control snapshot + # is stale. No stale source/phase can be advertised as locked. + self.assertIn("const bool currentMusicGraph=lastMusicTempo_.active",vocal) + self.assertIn("lastMusicTempo_.epoch",vocal) + self.assertIn("lastMusicTempo_.revision",vocal) + self.assertIn("currentMusicGraph&&",vocal) + self.assertIn("musicBpm",vocal) + self.assertIn('juce::String("0")',vocal) + self.assertIn('"arMixBuiltinThrowSnapshot"',vocal) + self.assertNotIn('"arMixBuiltinThrowSnapshot"',eq) + throw_js=(ROOT/"site/preview-v2/assets/mixer-native-vocal-throw.js").read_text("utf-8") + for field in ("musicLocked","musicBpm","musicGridAvailable", + "musicSourceChannelId"): + self.assertIn(field,throw_js) + self.assertNotIn("new AudioContext",throw_js) def test_fail_closed_on_repeat(self): with self.assertRaises(ValueError): diff --git a/tests/native_vocal_throw_cancel_test.cpp b/tests/native_vocal_throw_cancel_test.cpp new file mode 100644 index 000000000..0caf3b745 --- /dev/null +++ b/tests/native_vocal_throw_cancel_test.cpp @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Actual JUCE SPSC boundary, no ASIO device needed: an old cue must not +// sound when the device resumes after the native UI already rejected it. +#include "../engine/builtin_fx/VocalThrowProcessor.h" +#include +#include +#include +#include +#include +#define check(x) do{if(!(x)){std::fprintf(stderr,"FAIL %s:%d: %s\n",__FILE__,__LINE__,#x);std::abort();}}while(false) +static std::atomic noHeap{false}; +void* operator new(std::size_t n) { + if(noHeap.load(std::memory_order_relaxed))std::abort(); + if(void* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + if(noHeap.load(std::memory_order_relaxed))std::abort(); + if(void* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept{std::free(p);} +void operator delete[](void* p) noexcept{std::free(p);} +void operator delete(void* p,std::size_t) noexcept{std::free(p);} +void operator delete[](void* p,std::size_t) noexcept{std::free(p);} +using armix::builtin_fx::VocalThrowProcessor; +static void render(VocalThrowProcessor& p,juce::AudioBuffer& b, + juce::MidiBuffer& m,float amplitude) { + for(int c=0;c<2;++c)for(int i=0;i block(2,128); + juce::MidiBuffer midi; + std::array left{},right{}; + for(int b=0;b(n)]=v; + right[static_cast(n)]=v*.7f; + } + // Audio callback must never allocate, including first post-restart. + noHeap.store(true,std::memory_order_release); + reference.processStereo(left.data(),right.data(),left.size()); + noHeap.store(false,std::memory_order_release); + render(p,block,midi,amplitude); + for(int n=0;n<128;++n) { + const auto l=left[static_cast(n)]; + const auto r=right[static_cast(n)]; + check(std::isfinite(l)&&std::isfinite(r)); + check(std::abs(block.getSample(0,n)-l)<3.e-6f); + check(std::abs(block.getSample(1,n)-r)<3.e-6f); + if(echo && amplitude==0.f) + *echo+=std::abs(l)+std::abs(r); + } + } +} +static void testAudioAppliedStateSurvivesDeviceRestart() { + using armix::builtin_fx::VocalThrow; + for(const double firstRate:{44100.,48000.,96000.}) { + VocalThrowProcessor p; + p.prepareToPlay(firstRate,128); + check(p.isReady()); + p.sealForRealtime(); + auto latest=p.acceptedSettings(); + latest.mode=0; latest.bpm=156.f; latest.division=1; + latest.captureMs=300.f;latest.silenceMs=180.f; + latest.wet=.84f;latest.decay=.67f;latest.ducking=0.f; + latest.repeats=2; + check(p.queueSettings(latest,301)); + juce::AudioBuffer first(2,128);juce::MidiBuffer midi; + render(p,first,midi,0.f); + check(!p.stateSnapshotQuiescent()); + check(p.acceptedSettings().bpm!=latest.bpm); // ACK not yet polled + p.releaseResources(); + const auto secondRate=firstRate==96000.?48000.:96000.; + p.prepareToPlay(secondRate,128); + check(p.isReady()&&p.acceptedSampleRate()==secondRate); + check(p.acceptedSettings().bpm!=latest.bpm); + VocalThrow reference; + check(reference.prepare(secondRate)&&reference.resetUnpublished(latest)); + compareAudio(p,reference,140,.7f); + compareAudio(p,reference,45,0.f); + check(p.queueTrigger(302)); + check(reference.throwNow()); + float echo=0.f; + compareAudio(p,reference,320,0.f,&echo); + check(echo>.1f); // actual post-restart wet PCM, not only settings + VocalThrowProcessor::Completion completion{}; + check(p.pollCompletion(completion)&&completion.requestId==301&&completion.applied); + check(equalSettings(completion.settings,latest)); + check(p.pollCompletion(completion)&&completion.requestId==302&&completion.applied); + check(equalSettings(p.acceptedSettings(),latest)); + // Queued before yet another sample-rate change: packet is stale. + auto other=latest;other.bpm=85.f; + check(p.queueSettings(other,303)); + p.releaseResources(); + const auto thirdRate=secondRate==44100.?48000.:44100.; + p.prepareToPlay(thirdRate,257); + check(p.isReady()&&p.acceptedSampleRate()==thirdRate); + check(reference.prepare(thirdRate)&&reference.resetUnpublished(latest)); + compareAudio(p,reference,12,.7f); + check(p.pollCompletion(completion)&&completion.requestId==303&&!completion.applied); + check(equalSettings(p.acceptedSettings(),latest)); + check(p.stateSnapshotQuiescent()); + // Fresh revision with new coefficients succeeds after restart. + check(p.queueSettings(other,304)); + render(p,first,midi,0.f); + check(p.pollCompletion(completion)&&completion.requestId==304&&completion.applied); + check(equalSettings(p.acceptedSettings(),other)); + } +} +static void testColdShowRestoreAfterStart() { + using armix::builtin_fx::VocalThrow; + auto scene=armix::builtin_fx::VocalThrowSettings{}; + scene.mode=0;scene.bpm=92.f;scene.division=2; + scene.captureMs=670.f;scene.wet=.77f;scene.repeats=4; + juce::MemoryBlock stored; + { + juce::MemoryOutputStream writer(stored,false); + writer.writeInt(0x41565448);writer.writeInt(1); + writer.writeInt(scene.mode);writer.writeFloat(scene.bpm); + writer.writeInt(scene.division);writer.writeInt(scene.repeats); + writer.writeFloat(scene.captureMs);writer.writeFloat(scene.silenceMs); + writer.writeFloat(scene.thresholdDb);writer.writeFloat(scene.wet); + writer.writeFloat(scene.decay);writer.writeFloat(scene.ducking); + } + check(stored.getSize()==48); + VocalThrowProcessor cold; + check(cold.restoreUnpublishedState(stored.getData(), + static_cast(stored.getSize()))); + cold.prepareToPlay(48000.,128); + check(cold.isReady()&&equalSettings(cold.acceptedSettings(),scene)); + VocalThrow reference; + check(reference.prepare(48000.)&&reference.resetUnpublished(scene)); + compareAudio(cold,reference,50,.65f); + cold.releaseResources(); + cold.prepareToPlay(96000.,256); + check(cold.isReady()&&equalSettings(cold.acceptedSettings(),scene)); + check(reference.prepare(96000.)&&reference.resetUnpublished(scene)); + compareAudio(cold,reference,50,.65f); +} + + +static void testBypassNeverReplaysOldVocalCue() { + VocalThrowProcessor p; + p.prepareToPlay(48000.,128); + check(p.isReady()); + p.sealForRealtime(); + juce::AudioBuffer b(2,128); + juce::MidiBuffer midi; + auto settings=p.acceptedSettings(); + settings.mode=0;settings.wet=.9f;settings.ducking=0.f; + check(p.queueSettings(settings,501)); + render(p,b,midi,0.f); + VocalThrowProcessor::Completion done{}; + check(p.pollCompletion(done)&&done.requestId==501&&done.applied); + // Prime real singer history while FX is ON. + for(int n=0;n<115;++n)render(p,b,midi,.7f); + for(int n=0;n<32;++n)render(p,b,midi,0.f); + // A fade-out can still process audio; user cue must be rejected now. + p.onRealtimeBypass(true,false); + check(p.queueTrigger(502)); + render(p,b,midi,0.f); + check(p.pollCompletion(done)&&done.requestId==502&&!done.applied&& + done.bypassed); + // After full OFF the old ring is invalid, without a history-vector wipe + // in the realtime callback. Settings still ACK while the rack is OFF. + p.onRealtimeBypass(true,true); + auto next=settings;next.bpm=160.f; + check(p.queueSettings(next,503)); + p.consumeRealtimeEdits(); // native FX host fully-bypassed path + check(p.pollCompletion(done)&&done.requestId==503&&done.applied); + check(p.acceptedSettings().bpm==160.f); + check(p.queueTrigger(504)); + p.consumeRealtimeEdits(); + check(p.pollCompletion(done)&&done.requestId==504&&!done.applied&& + done.bypassed); + // Re-enable must not make the stale pre-bypass capture eligible again. + p.onRealtimeBypass(false,false); + check(p.queueTrigger(505)); + render(p,b,midi,0.f); + check(p.pollCompletion(done)&&done.requestId==505&&!done.applied&& + !done.bypassed); + check(p.observedThrowCount()==0); + // A FRESH sung phrase has an independent eligible manual cue. + for(int n=0;n<120;++n)render(p,b,midi,.7f); + for(int n=0;n<32;++n)render(p,b,midi,0.f); + check(p.queueTrigger(506)); + render(p,b,midi,0.f); + check(p.pollCompletion(done)&&done.requestId==506&&done.applied); + check(p.observedThrowCount()==1); + check(p.stateSnapshotQuiescent()); +} + +int main(){ + testBypassNeverReplaysOldVocalCue(); + testAudioAppliedStateSurvivesDeviceRestart(); + testColdShowRestoreAfterStart(); + VocalThrowProcessor p; + p.prepareToPlay(48000.,128); + check(p.isReady()); + p.sealForRealtime(); + juce::AudioBuffer b(2,128); + juce::MidiBuffer m; + auto old=p.acceptedSettings(); + auto changed=old;changed.bpm=156.f;changed.wet=.71f; + // Expired settings never mutate the DSP or its accepted settings shadow. + check(p.queueSettings(changed,101)); + p.cancelQueuedRequest(101); + // A second expired UI edit must not make the FIRST one executable + // again when ASIO eventually resumes. + check(p.queueSettings(changed,105)); + p.cancelQueuedRequest(105); + render(p,b,m,0.f); + VocalThrowProcessor::Completion c{}; + check(p.pollCompletion(c)&&c.requestId==101&&!c.applied); + render(p,b,m,0.f); + check(p.pollCompletion(c)&&c.requestId==105&&!c.applied); + check(p.acceptedSettings().bpm==old.bpm); + // A fresh request remains valid even after canceling an older ID. + check(p.queueSettings(changed,102)); + render(p,b,m,0.f); + check(p.pollCompletion(c)&&c.requestId==102&&c.applied); + check(p.acceptedSettings().bpm==156.f); + // Prime a real voiced phrase and then stop it; the trigger is valid. + for(int n=0;n<100;++n)render(p,b,m,.7f); + for(int n=0;n<32;++n)render(p,b,m,0.f); + check(p.queueTrigger(103)); + p.cancelQueuedRequest(103); + render(p,b,m,0.f); + check(p.pollCompletion(c)&&c.requestId==103&&!c.applied); + check(p.observedThrowCount()==0); + check(p.queueTrigger(104)); + render(p,b,m,0.f); + check(p.pollCompletion(c)&&c.requestId==104&&c.applied); + check(p.observedThrowCount()==1); + check(p.stateSnapshotQuiescent()); + std::puts("PASS: expired Vocal Throw cue and settings cannot replay on ASIO resume"); +} diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index b202f8c60..2cf1b3c23 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2739,6 +2739,8 @@ window.ArSonMixNativeCompressor?.open(t,slot); } else if(insert.catalogId==='armix.builtin.arson-harmony.v1') { window.ArSonMixNativeHarmony?.open(t,slot); + } else if(insert.catalogId==='armix.builtin.vocal-throw.v1') { + window.ArSonMixNativeVocalThrow?.open(t,slot); } else backend.emitEvent("arMixAction",{action:"routingFxEditor",channelId:id,slot, instanceId:insert.id,deviceEpoch:current.device.epoch,revision:current.graph.revision}); } else {discoverFxOnFirstPickerOpen();scope?.openFastPicker?.(t,slot,btn);} @@ -2936,7 +2938,8 @@ const plugin=nativeCatalog.get(id) || (id==='armix.builtin.channel-eq.v1'?{id,name:'Parametric EQ'}: id==='armix.builtin.channel-compressor.v1'?{id,name:'Compressor'}: - id==='armix.builtin.arson-harmony.v1'?{id,name:'ArSon Harmony'}:null); + id==='armix.builtin.arson-harmony.v1'?{id,name:'ArSon Harmony'}: + id==='armix.builtin.vocal-throw.v1'?{id,name:'ArSon Vocal Throw'}:null); const track=scope?.tracks?.find(x=>x.id===target?.channelId)|| (scope?.master?.id===target?.channelId?scope.master:null); const channel=m4Index(track),slot=Number(target?.slot);