From 5d0067d4f4b541108c2a13ecfba94c08133470fc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 09:09:47 +0700 Subject: [PATCH 1/2] fix(p0): forward-port verified ASIO recovery and Harmony safety onto main without GUI hide regression Preserve single native PCM pipeline and all already integrated Player, Compressor, Vocal Throw, WIRE, caption, updater, and session sources. Extend same-driver ASIO restart only with pinned registration/output readback; handle pristine SOURCE NONE restart without authored graph replacement; correct Harmony bypass sample-rate envelope and guide dropout reset; require native bridge handshake without hiding offline mixer shell. Tests cover ASIO policy, session rebind, Harmony PCM and GUI bundle. --- engine/builtin_fx/ChannelHarmonyProcessor.h | 22 +++++++-- src/LiveAudioEngine.h | 34 ++++++++++++-- src/LiveDryRoutingLab.h | 9 ++++ src/Main.cpp | 51 +++++++++++++++++---- src/NativeMixerSessionDocument.h | 5 +- tests/approved_native_gui_bundle_test.py | 4 ++ tests/harmony_bypass_reliability_test.cpp | 15 ++++++ tests/harmony_music_bank_test.cpp | 43 ++++++++++++++++- tests/mixer_io_operator_contract_test.mjs | 21 +++++++-- tests/native_mixer_session_store_test.cpp | 19 ++++++++ web/approved-native-bridge.js | 17 ++++--- 11 files changed, 212 insertions(+), 28 deletions(-) diff --git a/engine/builtin_fx/ChannelHarmonyProcessor.h b/engine/builtin_fx/ChannelHarmonyProcessor.h index 7d2e15a7d..eb90b555e 100644 --- a/engine/builtin_fx/ChannelHarmonyProcessor.h +++ b/engine/builtin_fx/ChannelHarmonyProcessor.h @@ -33,7 +33,7 @@ class ChannelHarmonyProcessor final : public juce::AudioProcessor, return b.getMainInputChannelSet()==juce::AudioChannelSet::stereo() && b.getMainOutputChannelSet()==juce::AudioChannelSet::stereo(); } - void prepareToPlay(double rate,int) override { + void prepareToPlay(double rate,int maximumExpectedSamplesPerBlock) override { ready_=dsp_.prepare(rate)&&guide_.prepare(rate)&&dsp_.setSettings(accepted_); guideSource_.store(accepted_.guideMode==1?accepted_.guideChannelId:0, std::memory_order_release); @@ -41,7 +41,16 @@ class ChannelHarmonyProcessor final : public juce::AudioProcessor, guideObservedScale_.store(-1,std::memory_order_relaxed); guideConfidence_.store(0.f,std::memory_order_relaxed); publishEffectiveKey(); - if(ready_) {sampleRate_=rate;setLatencySamples(dsp_.latencySamples());} + if(ready_) { + // FxInstance samples the AudioProcessor rate once, when its fixed + // 8 ms bypass envelope is prepared. Native built-ins are prepared + // directly; without JUCE rate metadata it otherwise sees zero + // and fades in only 64 samples at real 48/96 kHz device rates. + setRateAndBufferSizeDetails(rate, + std::max(1,maximumExpectedSamplesPerBlock)); + sampleRate_=rate; + setLatencySamples(dsp_.latencySamples()); + } } void releaseResources() override {ready_=false;} void processBlock(juce::AudioBuffer& samples,juce::MidiBuffer&) override { @@ -50,9 +59,16 @@ class ChannelHarmonyProcessor final : public juce::AudioProcessor, consumeRealtimeEdits(); // Missing/deleted/disconnected source must not leave a stale accepted // tonal estimate running indefinitely. Manual Key is the fallback. + const int guideTimeout=static_cast(sampleRate_*2.); + const bool guideWasFresh=guideAge_<=guideTimeout; guideAge_=std::min(guideAge_+samples.getNumSamples(), static_cast(sampleRate_*3.)); - if(guideAge_>static_cast(sampleRate_*2.)){ + if(guideWasFresh&&guideAge_>guideTimeout){ + // The guide source went missing. A detector that still retains + // old chroma would publish the old key on the FIRST resumed + // source block, before gathering fresh evidence. Invalidate once + // at the missing-source boundary, not at every audio callback. + guide_.reset(); dsp_.setGuideKey(-1,-1); guideObservedKey_.store(-1,std::memory_order_relaxed); guideObservedScale_.store(-1,std::memory_order_relaxed); diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 7768c6a43..8b16d7ca8 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -480,7 +480,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool selectedRetainedAsioDriverForReopen() { using Policy=armix::session::MixerDeviceBindingPolicy; if(deviceManager_.getCurrentAudioDevice() || !acceptedMixerBinding_ || - !Policy::isAsio4All(*acceptedMixerBinding_) || + acceptedMixerBinding_->backend!="ASIO" || !asioPinnedRegistration_.valid() || !attached_ || independent_.active() || deviceManager_.getCurrentAudioDeviceType()!="ASIO")return false; juce::AudioDeviceManager::AudioDeviceSetup setup; @@ -497,7 +497,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback bool authorizeRetainedAsioRestart() { using Policy=armix::session::MixerDeviceBindingPolicy; if(!hasRetainedNativeSession() || !acceptedMixerBinding_ || - !Policy::isAsio4All(*acceptedMixerBinding_) || !asioPinnedRegistration_.valid() || + acceptedMixerBinding_->backend!="ASIO" || !asioPinnedRegistration_.valid() || !allOutputsDisarmed() || independent_.active() || !attached_ || handoff_.busy() || fxMovePhase_.load(std::memory_order_acquire)!=0 || routeReconfiguring_.load(std::memory_order_acquire) || @@ -542,9 +542,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } bool reattachRetainedAsioMixer() { using Policy=armix::session::MixerDeviceBindingPolicy; - if(!acceptedMixerBinding_ || !Policy::isAsio4All(*acceptedMixerBinding_) || + if(!acceptedMixerBinding_ || acceptedMixerBinding_->backend!="ASIO" || !hasRetainedNativeSession() || !allOutputsDisarmed() || - !directFence_.permitted() || handoff_.busy())return false; + !directFence_.permitted() || handoff_.busy() || + !sameRetainedAsioDriver())return false; armix::session::MixerSessionDocument document; if(!dryRoutingLab_.describeRetainedAsioSession(document))return false; document.binding=*acceptedMixerBinding_; @@ -558,6 +559,31 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback acceptedMixerBinding_=std::move(inspected.live); return true; } + // A SOURCE NONE starter is not an authored Show: it has no FX/WIRE to + // rebind, yet still must survive an ASIO STOP/START as an actual PCM + // mixer. Keep the old playback identity and pin names; no auto-redirect. + bool hasPristineSilentMixerAwaitingAsio() const noexcept { + return dryRoutingLab_.hasPristineSilentMixerAwaitingDevice() && + acceptedMixerBinding_ && acceptedMixerBinding_->backend=="ASIO" && + asioPinnedRegistration_.valid() && attached_ && !independent_.active(); + } + bool rebuildPristineSilentAsioMixer() { + if(!hasPristineSilentMixerAwaitingAsio() || !allOutputsDisarmed() || + handoff_.busy() || + routeReconfiguring_.load(std::memory_order_acquire) || + diagnosticRoute()!=armix::diagnostics::Route::normal)return false; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen() || !sameRetainedAsioDriver())return false; + const auto current=readMixerBinding(*device); + if(current.backend!="ASIO" || + current.playback!=acceptedMixerBinding_->playback || + current.outputMask!=acceptedMixerBinding_->outputMask || + current.outputNames!=acceptedMixerBinding_->outputNames || + current.rate!=acceptedMixerBinding_->rate)return false; + if(!approveDirectRoute(&asioPinnedRegistration_))return false; + return startUnpatchedProductionSession().isEmpty() && + dryRoutingLab_.channelIdPhysicalPcmActive(); + } bool takeAsioResetMonitorIntent() noexcept { return resumeMainAfterAsioReset_.exchange(false,std::memory_order_acq_rel); } diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 3bf0cdb0b..ec399d3a5 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2654,6 +2654,15 @@ class LiveDryRoutingLab final { return true; return false; } + // A pristine SOURCE NONE mixer must not disappear when an ASIO callback + // stops/restarts. It contains no authored FX, WIRE, source or fader edit; + // rebuilding it is safe only on CONTROL after verifying the same device. + bool hasPristineSilentMixerAwaitingDevice() const noexcept { + return active() && sourceTemplate_.isObject() && + !acceptedRoute_.isObject() && !nativeStructureLive_ && + !nativeControlDirty_ && !channelIdPhysicalPcmActive() && + !hasAuthoredMixerContent(); + } // CONTROL only. The verified profile proves identical port ordinals. // Rebuild DSP scratch/PDC while retaining the accepted document and // compatible processors. Never re-use a processor at a different rate. diff --git a/src/Main.cpp b/src/Main.cpp index 2a2b7f01f..6a915369a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -231,6 +231,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr .withNativeIntegrationEnabled() .withEventListener ("arMixGuiReady", [this] (juce::var ready) { + // A Pages-only demo cannot authenticate native session readiness. + if (ready.getProperty ("gui", "").toString() != + "APPROVED_PAGES_PREVIEW_BUTTONS" || + !static_cast (ready.getProperty ("nativeBridgeAttached", false))) + { + diagnostics_.record ("GUI_NATIVE_BRIDGE_MISSING", + "Ignoring Pages-only readiness notification"); + return; + } browser_.loaded = true; guiReadyTick_ = juce::Time::getMillisecondCounter(); // WebView2 may finish its first navigation while this @@ -2522,7 +2531,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } if(bindingMode==MixerBindingMode::exact && startupOnSavedDevice && - armix::session::MixerDeviceBindingPolicy::isAsio4All(doc.binding)) + doc.binding.backend=="ASIO") bindingMode=MixerBindingMode::verifiedAsioRestart; const bool resume=startupOnSavedDevice && (bindingMode==MixerBindingMode::exact || bindingMode==MixerBindingMode::verifiedAsioRestart) && @@ -5415,7 +5424,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void serviceAsioMixerRestart() { const auto epoch=engine_.dryRoutingLabEpoch(); - if(epoch==asioRecoveryEpoch_ || !engine_.hasRetainedNativeSession() || + const bool retained=engine_.hasRetainedNativeSession(); + const bool silent=engine_.hasPristineSilentMixerAwaitingAsio(); + if(epoch==asioRecoveryEpoch_ || (!retained && !silent) || audioDeviceApplyActive_ || (audioSetupWindow_ && audioSetupWindow_->isVisible()) || nativeShowBusy_ || studioBackupBusy_ || mixerSessionWorker_.busy() || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.independentClockActive() || @@ -5423,7 +5434,6 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto* device=engine_.devices().getCurrentAudioDevice(); if(device) { if(device->getTypeName()!="ASIO" || - !device->getName().startsWithIgnoreCase("ASIO4ALL") || !engine_.sameRetainedAsioDriver())return; } else if(!engine_.selectedRetainedAsioDriverForReopen()) { // The device pointer disappeared: never open an unapproved or @@ -5448,28 +5458,49 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr setup.useDefaultInputChannels=!setup.inputChannels.isZero(); setup.useDefaultOutputChannels=true; asioRecoveryGate_.driverTransaction(now); - if(!device)diagnostics_.record("ASIO4ALL_DEVICE_MISSING", + if(!device)diagnostics_.record("ASIO_DEVICE_MISSING", "Reopening previously approved registered ASIO driver; no fallback"); const auto error=openSelectedAudioDevice("ASIO",setup,true); asioRecoveryGate_.carryInternalEpoch(engine_.dryRoutingLabEpoch()); device=engine_.devices().getCurrentAudioDevice(); if(error.isNotEmpty() || !device || !device->isOpen()) { - diagnostics_.record("ASIO4ALL_REOPEN_FAILED",error); + diagnostics_.record("ASIO_REOPEN_FAILED",error); + emitApprovedNativeSnapshot(); + return; + } + } + if(silent) { + // Recreate the original unedited SOURCE NONE PCM publisher only + // after proving the SAME ASIO driver and playback pin identity. + // No saved mixer, FX or WIRE may be replaced by this path. + if(!engine_.rebuildPristineSilentAsioMixer()) { + asioRecoveryGate_.bindFailed(now); + diagnostics_.record("ASIO_SILENT_MIXER_REBUILD_REJECTED", + "Registered ASIO driver/pins or native graph not ready"); emitApprovedNativeSnapshot(); return; } + asioRecoveryEpoch_=engine_.dryRoutingLabEpoch(); + asioRecoveryGate_.carryInternalEpoch(asioRecoveryEpoch_); + asioRecoveryGate_.recovered(); + mixerSessionStatus_="PRISTINE_SOURCE_NONE_REATTACHED"; + mixerSessionError_.clear(); + diagnostics_.record("ASIO_SILENT_MIXER_REATTACHED", + "Same physical ASIO output; no mic source and no auto-arm"); + emitApprovedNativeSnapshot(); + return; } if(!engine_.authorizeRetainedAsioRestart()) { // Admission can lag driver restart without any driver call. // It MUST NOT exhaust the bounded reopen/correction allowance. asioRecoveryGate_.waitForReadback(now); - diagnostics_.record("ASIO4ALL_BIND_NOT_READY","Waiting for verified callback/readback"); + diagnostics_.record("ASIO_BIND_NOT_READY","Waiting for verified callback/readback"); return; } if(const auto corrected=engine_.asioRestartPinCorrection()) { if(!asioRecoveryGate_.mayChangeDriver()) { asioRecoveryGate_.waitForReadback(now); - diagnostics_.record("ASIO4ALL_PIN_CORRECTION_DEFERRED", + diagnostics_.record("ASIO_PIN_CORRECTION_DEFERRED", "Driver transaction budget exhausted for this physical epoch"); return; } @@ -5485,7 +5516,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr reopened->getActiveInputChannels()!=corrected->inputChannels || reopened->getActiveOutputChannels()!=corrected->outputChannels || !engine_.authorizeRetainedAsioRestart()) { - diagnostics_.record("ASIO4ALL_PIN_CORRECTION_FAILED", + diagnostics_.record("ASIO_PIN_CORRECTION_FAILED", error.isNotEmpty()?error:juce::String("Readback changed during correction")); emitApprovedNativeSnapshot(); return; @@ -5498,7 +5529,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // current epoch; retry without reopening hardware at an // exponentially bounded CONTROL cadence. asioRecoveryGate_.bindFailed(now); - diagnostics_.record("ASIO4ALL_REATTACH_FAILED",error); + diagnostics_.record("ASIO_REATTACH_FAILED",error); emitApprovedNativeSnapshot(); return; } @@ -5509,7 +5540,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionError_.clear(); if(engine_.takeAsioResetMonitorIntent())requestAutomaticMain(false); if(engine_.isMonitorEnabled())mixerSessionStatus_="RESTORED_MONITORING"; - diagnostics_.record("ASIO4ALL_REATTACHED","Verified driver and current MAIN pair"); + diagnostics_.record("ASIO_REATTACHED","Verified driver and current MAIN pair"); emitApprovedNativeSnapshot(); } diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 68ce4c659..27f08581f 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -110,8 +110,11 @@ struct MixerDeviceBindingPolicy final { (mode==Mode::verifiedDeviceApply && (saved.backend!=live.backend || saved.playback!=live.playback))) return count==2?VerifiedNativeOutputs{count,0,1,-1,-1,false}:unavailable; + // The host checks the pinned registered ASIO driver identity first. + // Physical MAIN pin mapping still requires exact verified readback. if(mode==Mode::verifiedAsioRestart && - (!isAsio4All(live) || saved.backend!=live.backend || saved.playback!=live.playback)) + (saved.backend!="ASIO" || live.backend!="ASIO" || + saved.capture!=live.capture || saved.playback!=live.playback)) return unavailable; auto outputs=document.outputs; outputs.activeOutputChannels=count; diff --git a/tests/approved_native_gui_bundle_test.py b/tests/approved_native_gui_bundle_test.py index b770ba045..f3978481a 100644 --- a/tests/approved_native_gui_bundle_test.py +++ b/tests/approved_native_gui_bundle_test.py @@ -52,6 +52,10 @@ def test_native_is_exact_assembled_public_pages_plus_nonvisual_native_seam(self) self.assertIn("orbitAction", context_menu) self.assertNotIn("approved-native-context-menu.js", approved) self.assertIn("arMixGuiReady", (out / "assets/approved-native-bridge.js").read_text("utf-8")) + self.assertIn("nativeBridgeAttached:true", + (out / "assets/approved-native-bridge.js").read_text("utf-8")) + # Do not reintroduce #511's no-device hide/overlay regression. + self.assertNotIn('id="armix-native-boot-guard"', native) for asset in (source / "assets").iterdir(): self.assertEqual((out / "assets" / asset.name).read_bytes(), asset.read_bytes(), "Native /preview/ asset differs: " + asset.name) diff --git a/tests/harmony_bypass_reliability_test.cpp b/tests/harmony_bypass_reliability_test.cpp index a36135bbc..c23806e1d 100644 --- a/tests/harmony_bypass_reliability_test.cpp +++ b/tests/harmony_bypass_reliability_test.cpp @@ -28,6 +28,9 @@ static LiveChannelFxGraph::InstanceLease makeHarmony( p->prepareToPlay(rate,quantum); const int declaredLatency=2*static_cast(std::round(rate*.016)); assert(p->isReady() && p->getLatencySamples()==declaredLatency); + // Prepared built-in host metadata drives the live FxInstance envelope. + // A zero JUCE rate shortened 8 ms to just 64 frames at 48/96 kHz. + assert(std::abs(p->getSampleRate()-rate)<1.e-6); armix::harmony::Settings rich; rich.voices=5;rich.wet=wet;rich.space=space; assert(p->queueAccepted(rich,9001)); @@ -252,6 +255,18 @@ int main() { verifiedWet+=wetCount;verifiedDry+=dryCount; assert(!cycle.rackBypassed(vocal)); assert(!b->bypassRequested.load(std::memory_order_acquire)); + // Test the actual FX lease envelope, not an isolated Fade helper. + // Every WET/Space and callback-size variant must retain 8 ms at the + // device rate rather than falling back to 64 samples. + b->bypassFade.request(true); + int fadeFrames=0; + while(b->bypassFade.transitioning()&&fadeFrames<4096){ + b->bypassFade.next(); + ++fadeFrames; + } + assert(fadeFrames<4096); + const int expectedFade=static_cast(std::round(cfg.rate*.008)); + assert(std::abs(fadeFrames-expectedFade)<=1); } std::cout<<"Harmony multi-rate wet/space bypass matrix PASS; " <<"scenarios="<(i*128+j)/48000.; + l[j]=r[j]=static_cast(.20*std::sin( + 6.28318530718*220.*t)); + } + bank(vocal,l,r,128); // singer remains live during guide loss + for(int j=0;j<128;++j) + assert(std::isfinite(l[j])&&std::isfinite(r[j])); } + assert(live->observedNote()>=0); // no lead/pitch-analysis interruption assert(live->observedMusicKey()==-1); assert(live->effectiveKeyCode()==14); // music absent: manual D minor + // Regression: resuming a missing music ChannelId must NOT reuse its + // previously acquired key after two seconds of missing PCM. The old + // detector retained a valid C-major estimate and immediately published + // it on the first resumed source block, before any new tonal evidence. + { + float resumedL[128]{},resumedR[128]{}; + for(int j=0;j<128;++j){ + const double t=static_cast(j)/48000.; + resumedL[j]=resumedR[j]=static_cast(.09*( + std::sin(6.28318530718*220.*t)+ + std::sin(6.28318530718*261.625565*t)+ + std::sin(6.28318530718*329.627557*t))); + } + const float originalL=resumedL[17],originalR=resumedR[17]; + bank(music,resumedL,resumedR,128); + assert(resumedL[17]==originalL&&resumedR[17]==originalR); + assert(live->observedMusicKey()==-1); + assert(live->effectiveKeyCode()==14); // no stale C major flash + } + // Fresh A-minor guide must eventually retune after reacquisition. + for(int block=0;block<1450;++block){ + float l[128]{},r[128]{}; + for(int j=0;j<128;++j){ + const double t=static_cast(block*128+j)/48000.; + l[j]=r[j]=static_cast(.09*( + std::sin(6.28318530718*220.*t)+ + std::sin(6.28318530718*261.625565*t)+ + std::sin(6.28318530718*329.627557*t))); + } + bank(music,l,r,128); + } + assert(live->observedMusicKey()==9&&live->observedMusicScale()==1); + assert(live->effectiveKeyCode()==21); juce::MemoryBlock saved; live->getStateInformation(saved); // Realtime processor owns fixed DSP and reflection rings; production diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index 81bcf28f9..01a4c885c 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -617,23 +617,38 @@ test('ASIO4ALL automatic rebind has bounded retries, succeeds only after verifie assert.doesNotMatch(apply,/asioRecoveryEpoch_=engine_\.dryRoutingLabEpoch\(\);\s*if\(changedAsioPinLayout\)/); }); -test('ASIO4ALL missing JUCE device can reopen only the pinned user-selected driver',()=>{ +test('Missing ASIO device can reopen only the pinned registered user-selected driver',()=>{ const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'); const service=main.slice(main.indexOf('void serviceAsioMixerRestart()'), main.indexOf('void changeListenerCallback (')); assert.match(service,/else if\(!engine_\.selectedRetainedAsioDriverForReopen\(\)\)/); assert.match(service,/if\(!device \|\| !device->isOpen\(\)/); - assert.match(service,/ASIO4ALL_DEVICE_MISSING/); + assert.match(service,/ASIO_DEVICE_MISSING/); const selected=engine.slice(engine.indexOf('bool selectedRetainedAsioDriverForReopen()'), engine.indexOf('bool authorizeRetainedAsioRestart()')); assert.match(selected,/deviceManager_\.getCurrentAudioDevice\(\)/); assert.match(selected,/deviceManager_\.getCurrentAudioDeviceType\(\)!="ASIO"/); - assert.match(selected,/Policy::isAsio4All\(\*acceptedMixerBinding_\)/); + assert.match(selected,/acceptedMixerBinding_->backend!="ASIO"/); assert.match(selected,/setup\.outputDeviceName!=acceptedMixerBinding_->playback/); assert.match(selected,/setup\.inputDeviceName!=acceptedMixerBinding_->capture/); assert.match(selected,/asioPinnedRegistration_\.sameDriverClass\(registered\.registration\.identity\)/); }); +test('ASIO callback restart restores pristine SOURCE NONE without replacing authored mixer',()=>{ + const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'), + dry=read('src/LiveDryRoutingLab.h'); + const service=main.slice(main.indexOf('void serviceAsioMixerRestart()'), + main.indexOf('void changeListenerCallback (')); + assert.match(service,/const bool silent=engine_\.hasPristineSilentMixerAwaitingAsio\(\)/); + assert.match(service,/if\(silent\)\s*\{/); + assert.match(service,/engine_\.rebuildPristineSilentAsioMixer\(\)/); + assert.match(engine,/current\.outputMask!=acceptedMixerBinding_->outputMask/); + assert.match(engine,/current\.outputNames!=acceptedMixerBinding_->outputNames/); + assert.match(engine,/sameRetainedAsioDriver\(\)/); + assert.match(dry,/hasPristineSilentMixerAwaitingDevice\(\)/); + assert.match(dry,/!hasAuthoredMixerContent\(\)/); +}); + test('ASIO restart cannot strand MAIN off after temporary graph readiness faults',()=>{ const main=read('src/Main.cpp'),engine=read('src/LiveAudioEngine.h'); const arm=main.slice(main.indexOf('void serviceAutomaticMain()'),main.indexOf('void requestAutomaticMain(')); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 0255f8f25..57979cb39 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -864,6 +864,25 @@ int main(){ duplicatePins.outputNames.add("2nd output with SST 1"); assert(!MixerDeviceBindingPolicy::proposedOutputs(asio,duplicatePins,2, BindingMode::verifiedAsioRestart).valid()); + // A third-party ASIO driver must rebind only the SAME registered host + // and verified physical MAIN, never guess a new output or capture device. + auto vendor=asio; + vendor.binding.capture=vendor.binding.playback="MAONO PS22 ASIO"; + auto vendorCurrent=vendor.binding; + const auto vendorMain=MixerDeviceBindingPolicy::proposedOutputs( + vendor,vendorCurrent,2,BindingMode::verifiedAsioRestart); + assert(vendorMain.valid() && vendorMain.mainL==vendor.outputs.mainL && + vendorMain.mainR==vendor.outputs.mainR); + auto vendorRestored=vendor; + assert(MixerDeviceBindingPolicy::apply(vendorRestored,vendorCurrent,vendorMain,2, + BindingMode::verifiedAsioRestart).isEmpty()); + vendorCurrent.playback="Different ASIO interface"; + assert(!MixerDeviceBindingPolicy::proposedOutputs( + vendor,vendorCurrent,2,BindingMode::verifiedAsioRestart).valid()); + vendorCurrent=vendor.binding; + vendorCurrent.capture="Other capture"; + assert(!MixerDeviceBindingPolicy::proposedOutputs( + vendor,vendorCurrent,2,BindingMode::verifiedAsioRestart).valid()); auto exact=d; assert(MixerDeviceBindingPolicy::apply(exact,d.binding,d.outputs,2,BindingMode::exact) .isEmpty()); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 6e1ab7a1b..5a78df923 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -3272,12 +3272,17 @@ updateHardwarePanel(null); stopDemo(); status("NATIVE: subscribed · waiting for true device and accepted ChannelId graph"); - backend.emitEvent("arMixGuiReady",{ - gui:"APPROVED_PAGES_PREVIEW_BUTTONS",visualReady:true,audioReady:false, - viewportWidth:Math.round(window.innerWidth), - viewportHeight:Math.round(window.innerHeight), - devicePixelRatio:window.devicePixelRatio - }); + // Only the installed native Pages scope can authenticate host GUI readiness. + // This handshake says nothing about whether physical PCM is admitted. + if(scope?.installGraph && scope?.render){ + backend.emitEvent("arMixGuiReady",{ + gui:"APPROVED_PAGES_PREVIEW_BUTTONS",nativeBridgeAttached:true, + visualReady:true,audioReady:false, + viewportWidth:Math.round(window.innerWidth), + viewportHeight:Math.round(window.innerHeight), + devicePixelRatio:window.devicePixelRatio + }); + } else status("Native mixer renderer unavailable · repair application"); controller.subscribe(); }; if(document.readyState==="loading") From 378ffbc2aba4b3de421f723270951365c563b981 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 09:13:50 +0700 Subject: [PATCH 2/2] feat(vocal-throw): selectively forward-port M15 phrase cue and wet ping-pong on reconciled P0 source Only nine intended M15 files differ from current main; preserve ASIO recovery, mixer graph, Harmony fixes, Compressor, Player, updater, title and release sources. Cue waits for completed singer phrase, sends wet-only ping-pong with bounded control/no-heap DSP, keeps dry PCM unchanged and exposes readback. Extend dedicated visual and actual native PCM tests. No hardware claim or release authorization. --- .github/workflows/ui-smoke.yml | 2 +- engine/builtin_fx/VocalThrow.h | 133 ++++++++++++++---- engine/builtin_fx/VocalThrowProcessor.h | 7 +- site/preview-v2/assets/mixer-fx-rack.css | 33 +++-- .../assets/mixer-native-vocal-throw.js | 91 ++++++++---- src/Main.cpp | 1 + tests/approved_native_vocal_throw_smoke.py | 80 ++++++++++- tests/builtin_vocal_throw_test.cpp | 122 ++++++++++++---- tests/native_vocal_throw_cancel_test.cpp | 17 ++- 9 files changed, 386 insertions(+), 100 deletions(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index f2b5cfe4a..463b8b3de 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -134,7 +134,7 @@ jobs: needs: quick # Run dedicated Vocal Throw visual validation in the reconciled native # engine branch too; generic /preview/ smoke does not call this fixture. - if: ${{ github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feature/arson-vocal-throw-') || startsWith(github.head_ref, 'integration/arson-vocal-throw-') || github.head_ref == 'integration/asio4all-harmony-d4-compat-20261109') }} + if: ${{ github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feature/arson-vocal-throw-') || startsWith(github.head_ref, 'integration/arson-vocal-throw-') || github.head_ref == 'fix/p0-reconcile-native-asio-harmony-20261110' || github.head_ref == 'integration/asio4all-harmony-d4-compat-20261109') }} runs-on: ubuntu-latest timeout-minutes: 15 steps: diff --git a/engine/builtin_fx/VocalThrow.h b/engine/builtin_fx/VocalThrow.h index aa3cfbd1b..e1e64a880 100644 --- a/engine/builtin_fx/VocalThrow.h +++ b/engine/builtin_fx/VocalThrow.h @@ -117,20 +117,38 @@ class VocalThrow final { 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. + // AUDIO ONLY. A click DURING a syllable is a musical intent, not an + // immediate splice. The singer finishes naturally; we freeze at the + // verified end boundary. A second click cancels the queued intent. + // An already completed phrase (last 700ms) is fired immediately. 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; + const auto gap=static_cast(rate_*.06); + const bool finished=lastSoundEnd_>0&&quiet_>=gap&& + clock_>=lastSoundEnd_&&clock_-lastSoundEnd_<=recent; + if(finished) { + // AUTO/HYBRID has already consumed this phrase. + if(lastSoundEnd_==autoTriggeredPhraseEnd_)return false; + const bool fired=freezeAt(lastSoundEnd_); + if(fired) { + manualInCurrentPhrase_=true; + armed_=false; + } + return fired; + } + // Even before the first microphone frame, arm ONE future phrase. + // Never retain the cue past four seconds or a device/bypass reset. + cueArmed_=true; + cueSawVoice_=armed_ && lastSoundEnd_>0; + cueDeadline_=clock_+static_cast(rate_*4.); + return true; } + [[nodiscard]] bool cueArmed() const noexcept{return cueArmed_;} void processStereo(float* left,float* right,std::size_t frames) noexcept { if(!ready_||!left||!right)return; const bool mono=left==right; @@ -147,21 +165,38 @@ class VocalThrow final { const float coeff=peak>envelope_?envAttack_:envRelease_; envelope_=coeff*envelope_+(1.f-coeff)*peak; if(envelope_<1.0e-20f)envelope_=0.f; - const bool singing=envelope_>=settings_.gateLinear; + // Update ambient floor only when the vocal envelope is quiet. + // Gate hysteresis avoids chattering at syllable tails; never + // change the lead vocal dry PCM or demand calibration from user. + const float gate=std::max(settings_.gateLinear,noiseFloor_*3.0f); + const bool singing=envelope_>=gate*(quiet_==0?.75f:1.f); if(singing) { - if(quiet_>phraseGap) { - voiced_=0; - manualInCurrentPhrase_=false; // genuinely new sung phrase - autoTriggeredPhraseEnd_=0; + if(quiet_>phraseGap || lastWordStart_==0) { + lastWordStart_=clock_; + if(quiet_>phraseGap) { + voiced_=0; + manualInCurrentPhrase_=false; + autoTriggeredPhraseEnd_=0; + } } quiet_=0; voiced_=std::min(voiced_+1,maxQuiet); lastSoundEnd_=clock_; - if(voiced_>=minVoice)armed_=true; + if(voiced_>=minVoice) { + armed_=true; + if(cueArmed_)cueSawVoice_=true; + } } else { if(quiet_=settings_.silenceSamples) { - if(settings_.settings.mode!=0 && !manualInCurrentPhrase_ + // Manual queued cue gets priority over AUTO/HYBRID. + // Freeze the completed phrase, not the middle of a word. + if(cueArmed_ && cueSawVoice_) { + if(freezeAt(lastSoundEnd_)) + manualInCurrentPhrase_=true; + cueArmed_=cueSawVoice_=false; + } else if(settings_.settings.mode!=0 && !manualInCurrentPhrase_ && clock_>=nextAutoEligible_) { if(freezeAt(lastSoundEnd_)) { autoTriggeredPhraseEnd_=lastSoundEnd_; @@ -172,6 +207,8 @@ class VocalThrow final { armed_=false; } } + if(cueArmed_ && clock_>=cueDeadline_) + cueArmed_=cueSawVoice_=false; // bounded stale-cue expiry float echoL=0.f,echoR=0.f,activeTapGain=0.f; for(auto& voice:voices_) { if(voice.copying)copyFrozenChunk(voice); @@ -193,7 +230,31 @@ class VocalThrow final { } 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; + // Ping-pong is wet-only. A true stereo source is folded + // to a stable wet mid, then positioned alternately L/R; + // the dry original is preserved sample-for-sample. + const float mid=.5f*(voice.freezeL[p]+voice.freezeR[p]); + auto& lowpass=voice.tapTone[slot]; + const float alpha=.58f/(1.f+.22f*static_cast(tap)); + lowpass+=alpha*(mid-lowpass); + const float tone=(.75f-.07f*static_cast(tap))*mid+ + (.25f+.07f*static_cast(tap))*lowpass; + // Tiny asymmetric early reflection = spatial depth; + // bounded reads only from the already frozen phrase, + // never a second realtime delay allocation or HRTF. + const auto reflectionOffset=voice.reflectionSamples; + const float reflection=p>=reflectionOffset? + .5f*(voice.freezeL[p-reflectionOffset]+ + voice.freezeR[p-reflectionOffset]):0.f; + const float direct=tone*gain; + const float room=reflection*gain*.115f; + if((tap&1)==0) { + echoL+=direct*.93f; + echoR+=direct*.23f+room; + } else { + echoR+=direct*.93f; + echoL+=direct*.23f+room; + } activeTapGain+=gain; } const auto end=voice.repeatStarts[ @@ -224,9 +285,10 @@ class VocalThrow final { void invalidateCaptureHistory() noexcept { recorded_=0; lastSoundEnd_=nextAutoEligible_=autoTriggeredPhraseEnd_=0; + lastWordStart_=cueDeadline_=0; voiced_=quiet_=0; - armed_=manualInCurrentPhrase_=false; - envelope_=0.f; + armed_=manualInCurrentPhrase_=cueArmed_=cueSawVoice_=false; + noiseFloor_=0.f;envelope_=0.f; for(auto& voice:voices_) { voice.copying=false;voice.playing=false; voice.freezeCount=0;voice.copyIndex=0; @@ -245,10 +307,11 @@ class VocalThrow final { std::vector freezeL,freezeR; std::array repeatStarts{}; std::array repeatGains{}; + std::array tapTone{}; // voice-owned HF damping PreparedEdit active{}; std::uint64_t copyEnd=0,freezeCount=0; std::size_t copyIndex=0,sourceIndex=0; - std::uint32_t edgeSamples=0; + std::uint32_t edgeSamples=0,reflectionSamples=0; std::uint64_t gridAnchorFrame=0,gridCueFrame=0,gridCueLocal=0; bool gridValid=false; bool copying=false,playing=false; @@ -263,13 +326,20 @@ class VocalThrow final { } if(!slot)return false; const auto available=std::min(end,recorded_); - const auto count=std::min(available,settings_.captureSamples); + auto count=std::min(available,settings_.captureSamples); + // Prefer the actual last voiced onset (including 28ms consonant + // preroll) over an arbitrary fixed-size slice of the previous word. + const auto pre=static_cast(rate_*.028); + const auto onset=lastWordStart_>pre?lastWordStart_-pre:0; + if(onset>0&&onset(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->reflectionSamples=static_cast(rate_*.011); + slot->tapTone.fill(0.f); slot->active=settings_; if(musicIntervalSamples_) slot->active.intervalSamples=musicIntervalSamples_; @@ -313,7 +383,11 @@ class VocalThrow final { if(globalFirst>=voice.gridAnchorFrame) { const auto remainder= (globalFirst-voice.gridAnchorFrame)%interval; - if(remainder)first+=interval-remainder; + // Never wait nearly another beat just to satisfy a stale + // onset lattice. Small phase correction is musical; a full + // extra delay is not. Upper bound = one quarter subdivision. + if(remainder && interval-remainder<=interval/4) + first+=interval-remainder; } else if(voice.gridAnchorFrame-globalFirst<=interval) { first+=voice.gridAnchorFrame-globalFirst; } @@ -330,10 +404,11 @@ class VocalThrow final { } void reset() noexcept { clock_=lastSoundEnd_=nextAutoEligible_=autoTriggeredPhraseEnd_=0; + lastWordStart_=cueDeadline_=0; recorded_=writeIndex_=0; voiced_=quiet_=0; - armed_=manualInCurrentPhrase_=false; - envelope_=0.f;duck_=1.f;throwCount_=0; + armed_=manualInCurrentPhrase_=cueArmed_=cueSawVoice_=false; + noiseFloor_=0.f;envelope_=0.f;duck_=1.f;throwCount_=0; wetSmoothed_=settings_.settings.wet; if(rate_>0) { envAttack_=static_cast(std::exp(-1./(rate_*.004))); @@ -343,7 +418,8 @@ class VocalThrow final { for(auto& voice:voices_) { voice.copyEnd=voice.freezeCount=0; voice.copyIndex=voice.sourceIndex=0; - voice.edgeSamples=0; + voice.edgeSamples=voice.reflectionSamples=0; + voice.tapTone.fill(0.f); voice.copying=voice.playing=false; voice.gridValid=false; voice.gridAnchorFrame=voice.gridCueFrame=voice.gridCueLocal=0; @@ -356,9 +432,11 @@ class VocalThrow final { std::vector historyL_,historyR_; std::array voices_{}; std::uint64_t clock_=0,lastSoundEnd_=0,nextAutoEligible_=0,autoTriggeredPhraseEnd_=0; + std::uint64_t lastWordStart_=0,cueDeadline_=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 noiseFloor_=0.f; float duck_=1.f,wetSmoothed_=.42f; double rate_=0.; std::uint32_t musicIntervalSamples_=0; @@ -366,5 +444,6 @@ class VocalThrow final { bool gridValid_=false; unsigned throwCount_=0; bool armed_=false,manualInCurrentPhrase_=false,ready_=false; + bool cueArmed_=false,cueSawVoice_=false; }; } // namespace armix::builtin_fx diff --git a/engine/builtin_fx/VocalThrowProcessor.h b/engine/builtin_fx/VocalThrowProcessor.h index 793d628cd..dd04b9432 100644 --- a/engine/builtin_fx/VocalThrowProcessor.h +++ b/engine/builtin_fx/VocalThrowProcessor.h @@ -76,6 +76,7 @@ class VocalThrowProcessor final : public juce::AudioProcessor, static_cast(pcm.getNumSamples())); observedThrows_.store(core_.throwCount(),std::memory_order_relaxed); observedTail_.store(core_.echoActive(),std::memory_order_relaxed); + observedCueArmed_.store(core_.cueArmed(),std::memory_order_relaxed); } void processBlock(juce::AudioBuffer&,juce::MidiBuffer&) override{} void onRealtimeBypass(bool requested,bool fully) noexcept override { @@ -87,6 +88,7 @@ class VocalThrowProcessor final : public juce::AudioProcessor, if(clear&&ready_) { core_.invalidateCaptureHistory(); observedTail_.store(false,std::memory_order_relaxed); + observedCueArmed_.store(false,std::memory_order_relaxed); } if(requested&&fully)captureInvalidated_=true; if(!requested)captureInvalidated_=false; @@ -206,6 +208,9 @@ class VocalThrowProcessor final : public juce::AudioProcessor, bool observedTailActive() const noexcept { return observedTail_.load(std::memory_order_relaxed); } + bool observedCueArmed() const noexcept { + return observedCueArmed_.load(std::memory_order_relaxed); + } bool isReady() const noexcept{return ready_;} void sealForRealtime() noexcept override{published_=true;} bool stateSnapshotQuiescent() const noexcept override{ @@ -266,7 +271,7 @@ class VocalThrowProcessor final : public juce::AudioProcessor, std::array,32> cancelledIds_{}; std::uint32_t cancelWrite_=0; // CONTROL only bool bypassed_=false,captureInvalidated_=false; // AUDIO only - std::atomic observedTail_{false}; + std::atomic observedTail_{false},observedCueArmed_{false}; double rate_=0.; float lastTempoBpm_=0.f; // CONTROL only int lastTempoDivision_=-1; // CONTROL only diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index 35f92efef..d650c1d01 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -820,17 +820,34 @@ .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} + filter:drop-shadow(0 8px 9px #090d15af);transform:translateZ(0)} +/* Owner's unchanged SVG and OUTER bezel are fixed; only the interior + ring illuminates and the central cap gains a small inset shadow. */ .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)} + transition:box-shadow 140ms ease} +.mx-vthrow .vt-throw-button::after{content:"";position:absolute;inset:31%;border-radius:50%; + pointer-events:none;box-shadow:inset 0 0 0 1px #d7a2f008; + transform:translateY(0);transition:transform 100ms ease,box-shadow 100ms ease} +.mx-vthrow .vt-throw-button:hover:not(:disabled) .vt-throw-aura{ + box-shadow:0 0 22px #bc36df3b,inset 0 0 0 2px #c17fdd72} +.mx-vthrow .vt-throw-button:active:not(:disabled){transform:translateZ(0); + filter:drop-shadow(0 8px 9px #090d15af)} +.mx-vthrow .vt-throw-button:active:not(:disabled) .vt-throw-aura{ + box-shadow:0 0 34px #c743ffe0,inset 0 0 0 4px #e3a2ffdd} +.mx-vthrow .vt-throw-button:active:not(:disabled)::after{ + transform:translateY(2px);box-shadow:inset 0 5px 14px #160522a8,0 1px 0 #e1b2ff3d} +@keyframes vt-armed-ring{ + 0%,100%{box-shadow:0 0 14px #8c26b65b,inset 0 0 0 2px #9b57ba9c} + 50%{box-shadow:0 0 31px #c743ffa6,inset 0 0 0 3px #e2a0ffcc} +} +.mx-vthrow .vt-throw-button[data-armed=true]:not(:disabled) .vt-throw-aura{ + animation:vt-armed-ring 1.25s ease-in-out infinite} .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} + box-shadow:0 0 29px #bb29e78f,inset 0 0 0 3px #e7a7f7ad} +@media(prefers-reduced-motion:reduce){ + .mx-vthrow .vt-throw-button[data-armed=true] .vt-throw-aura{animation:none} +} .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; diff --git a/site/preview-v2/assets/mixer-native-vocal-throw.js b/site/preview-v2/assets/mixer-native-vocal-throw.js index ec50fab14..218a29551 100644 --- a/site/preview-v2/assets/mixer-native-vocal-throw.js +++ b/site/preview-v2/assets/mixer-native-vocal-throw.js @@ -70,6 +70,8 @@ for(const [key,[title,unit,,bank]] of Object.entries(encoderMeta)){ let current=null,accepted=defaults(),draft=defaults(),pending=null, readId="",readSent=0,seq=1,taps=[],windowDrag=null; let tempoPending=null,musicSource="0",musicReadback=null; +let snapshotReady=false,queuedSettings=false,activeRotaries=0,lastThrowCount=0; +const dirtyFields=new Set(); // never discard first-use knob edits on native readback 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]; @@ -122,8 +124,9 @@ function syncPower(){ 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"; + ($("vtThrow").dataset.tail==="true"?"TAIL": + $("vtThrow").dataset.armed==="true"?"ARMED":"LIVE"): + value==="off"?"BYPASS":value==="rack-off"?"RACK OFF":"OFFLINE"; } function paint(){ $("vtMode").value=String(draft.mode); @@ -175,14 +178,20 @@ function requestSnapshot(force=false){ function send(command){ const ctx=context(); if(!native()||!ctx){hint("Native DSP unavailable");return false;} - if(pending){hint("Waiting for DSP ACK");return false;} - if(command==="nativeThrowSet"&&(!valid(draft)||same(draft,accepted)))return false; + if(command==="nativeThrowSet"){ + // Gesture is always live visually. Do not send guessed defaults before + // receiving native settings or while an earlier control edit is pending. + if(!snapshotReady||pending||activeRotaries>0){ + queuedSettings=true;return true; + } + if(!valid(draft)||same(draft,accepted))return false; + } else if(pending){hint("Waiting for DSP ACK");return false;} const requestId="throw-"+String(Date.now()*1000+(++seq%1000)); pending={requestId,command,ack:false,created:Date.now()}; const payload={action:command,requestId,...ctx}; if(command==="nativeThrowSet")payload.settings={...draft}; backend().emitEvent("arMixAction",payload); - hint(command==="nativeThrowTrigger"?"Waiting for audio callback":"Applying to DSP"); + hint(command==="nativeThrowTrigger"?"Cue accepted by mixer":"Applying to DSP"); syncPower();return true; } // The large LCD numerals double as the manual BPM edit target. Numeric @@ -207,20 +216,25 @@ $("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"); + draft={...draft,[key]:Number($(id).value)}; + dirtyFields.add(key);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); + const [min,max]=ranges[key],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();}; + const update=v=>{ + draft={...draft,[key]:quantize(v)}; + dirtyFields.add(key);paint(); + }; face.addEventListener("pointerdown",e=>{ - if(e.button!==0||pending)return; + if(e.button!==0||panel.dataset.fxState!=="on")return; + // Don't block the first real pointer gesture behind a settings ACK. gesture={id:e.pointerId,y:e.clientY,initial:draft[key],changed:false}; + activeRotaries++; face.setPointerCapture(e.pointerId);e.preventDefault(); }); face.addEventListener("pointermove",e=>{ @@ -232,13 +246,19 @@ function bindRotary(face,key,step){ const finish=e=>{ if(!gesture||e.pointerId!==gesture.id)return; const changed=gesture.changed;gesture=null; + activeRotaries=Math.max(0,activeRotaries-1); if(face.hasPointerCapture?.(e.pointerId))face.releasePointerCapture(e.pointerId); - if(changed)send("nativeThrowSet"); + if(changed||queuedSettings)send("nativeThrowSet"); }; face.addEventListener("pointerup",finish); - face.addEventListener("pointercancel",()=>{gesture=null;paint();}); + face.addEventListener("pointercancel",e=>{ + if(gesture&&e.pointerId===gesture.id){ + gesture=null;activeRotaries=Math.max(0,activeRotaries-1); + if(queuedSettings)send("nativeThrowSet"); + } + }); face.addEventListener("wheel",e=>{ - if(pending)return; + if(panel.dataset.fxState!=="on")return; e.preventDefault();update(draft[key]+(e.deltaY<0?step:-step)); send("nativeThrowSet"); },{passive:false}); @@ -250,7 +270,6 @@ function bindRotary(face,key,step){ send("nativeThrowSet"); }); face.addEventListener("dblclick",()=>{ - if(pending)return; update(defaults()[key]);send("nativeThrowSet"); }); } @@ -280,7 +299,8 @@ $("vtMusicSource").addEventListener("change",()=>{ }); $("vtPreset").addEventListener("change",()=>{ const p=presets[$("vtPreset").value];if(!p)return; - draft={...p};paint();send("nativeThrowSet"); + draft={...p};Object.keys(draft).forEach(key=>dirtyFields.add(key)); + paint();send("nativeThrowSet"); }); $("vtThrow").addEventListener("click",()=>send("nativeThrowTrigger")); $("vtTap").addEventListener("click",()=>{ @@ -321,6 +341,9 @@ window.ArSonMixNativeVocalThrow=Object.freeze({ 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=""; + snapshotReady=false;queuedSettings=false;activeRotaries=0;lastThrowCount=0; + dirtyFields.clear(); + $("vtThrow").dataset.armed="false";$("vtThrow").dataset.tail="false"; 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){ @@ -368,17 +391,34 @@ backend()?.addEventListener?.("arMixBuiltinThrowSnapshot",reply=>{ musicSource=String(reply.musicSourceChannelId||"0"); refreshMusicChannels();renderMusicStatus(reply); } - $("vtCount").textContent=String(reply.throwCount||0); - $("vtCount").setAttribute("aria-label",String(reply.throwCount||0)+" completed throws"); + const count=Number(reply.throwCount)||0,armed=reply.cueArmed===true; + const wasArmed=$("vtThrow").dataset.armed==="true"; + $("vtCount").textContent=String(count); + $("vtCount").setAttribute("aria-label",count+" 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};} + $("vtThrow").dataset.armed=String(armed); + if(armed)hint("ARMED · waiting for end of vocal phrase"); + else if(wasArmed)hint(count>lastThrowCount? + "THROWN · stereo ping-pong":"READY · cue cleared"); + lastThrowCount=count; + if(pending&&(!pending.ack||reply.appliedRequestId!==pending.requestId)){ + paint();return; + } + const local={...draft},wasReady=snapshotReady; + snapshotReady=true;accepted={...reply.settings}; + if(!wasReady||queuedSettings||activeRotaries>0){ + draft={...accepted}; + for(const key of dirtyFields)draft[key]=local[key]; + }else draft={...accepted}; + pending=null; + if(activeRotaries===0) { + if(!same(draft,accepted)){ + queuedSettings=false; + send("nativeThrowSet"); // latest coalesced intent: never one per pixel + }else{dirtyFields.clear();queuedSettings=false;} + } paint(); }); backend()?.addEventListener?.("arMixConsoleSnapshot",()=>{ @@ -391,7 +431,10 @@ backend()?.addEventListener?.("arMixConsoleSnapshot",()=>{ }); window.setInterval(()=>{ if(panel.hidden)return; - if(pending&&Date.now()-pending.created>3500){hint("DSP ACK timeout");pending=null;} + if(pending&&Date.now()-pending.created>3500){ + hint("DSP response late · resyncing"); + pending=null;requestSnapshot(true); + } if(tempoPending&&Date.now()-tempoPending.created>3500){ hint("Tempo source ACK timeout");tempoPending=null;refreshMusicChannels(); } diff --git a/src/Main.cpp b/src/Main.cpp index 6a915369a..4ada180a0 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2373,6 +2373,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr reply->setProperty("throwCount",static_cast(processor->observedThrowCount())); reply->setProperty("tailActive",processor->observedTailActive()); + reply->setProperty("cueArmed",processor->observedCueArmed()); reply->setProperty("addedLatencySamples",processor->getLatencySamples()); if(instanceId==lastNativeThrowInstance_&& epoch==lastNativeThrowEpoch_&&revision==lastNativeThrowRevision_) diff --git a/tests/approved_native_vocal_throw_smoke.py b/tests/approved_native_vocal_throw_smoke.py index 94dd89676..66e4870ec 100644 --- a/tests/approved_native_vocal_throw_smoke.py +++ b/tests/approved_native_vocal_throw_smoke.py @@ -22,13 +22,14 @@ def last(page,action): assert records, "No "+action+" event" return records[-1] -def reply_snapshot(page,state,settings,applied=None,count=0,tail=False,music=None): +def reply_snapshot(page,state,settings,applied=None,count=0,tail=False,music=None,armed=False): 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, + "cueArmed":armed, "musicSourceChannelId":music["source"] if music else "0", "musicSourceActive":bool(music), "musicLocked":bool(music), @@ -136,6 +137,44 @@ def main(): assert last(page,"nativeThrowSnapshot")["requestId"]==initial["requestId"],\ "snapshot polling overwrote outstanding request too early" reply_snapshot(page,state,DEFAULTS) + if width==1366: + # First-ever knob gesture must work without pressing any + # MAN/AUTO/HYBRID mode control or waiting for FX re-open. + capture=editor.locator('.vt-encoder[data-key="captureMs"] .vt-encoder-face') + initial_capture=capture.bounding_box() + assert initial_capture + px=initial_capture["x"]+initial_capture["width"]/2 + py=initial_capture["y"]+initial_capture["height"]/2 + page.mouse.move(px,py) + page.mouse.down() + page.mouse.move(px,py-23,steps=8) + page.mouse.up() + first=last(page,"nativeThrowSet") + cap1=first["settings"]["captureMs"] + assert cap1>DEFAULTS["captureMs"],first + # While ACK is outstanding, a real wheel gesture still + # changes the encoder visually. Latest edit is coalesced. + capture.hover() + page.mouse.wheel(0,-120) + assert float(capture.get_attribute("aria-valuenow"))>cap1 + assert last(page,"nativeThrowSet")["requestId"]==first["requestId"] + emit(page,"arMixBuiltinThrowQueue",{"requestId":first["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinThrowAck",{"requestId":first["requestId"],"status":"APPLIED"}) + reply_snapshot(page,state,{**DEFAULTS,"captureMs":cap1},applied=first["requestId"]) + second=last(page,"nativeThrowSet") + assert second["requestId"]!=first["requestId"] + assert second["settings"]["captureMs"]>cap1,second + emit(page,"arMixBuiltinThrowQueue",{"requestId":second["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinThrowAck",{"requestId":second["requestId"],"status":"APPLIED"}) + reply_snapshot(page,state,{**DEFAULTS,"captureMs":second["settings"]["captureMs"]}, + applied=second["requestId"]) + # Reset CAPTURE for later existing preset/tempo regressions. + capture.dblclick() + restored=last(page,"nativeThrowSet") + assert restored["settings"]["captureMs"]==DEFAULTS["captureMs"] + emit(page,"arMixBuiltinThrowQueue",{"requestId":restored["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinThrowAck",{"requestId":restored["requestId"],"status":"APPLIED"}) + reply_snapshot(page,state,DEFAULTS,applied=restored["requestId"]) assert editor.locator("#vtStatus").inner_text()=="LIVE" assert editor.locator("#vtCount").inner_text()=="0" box=editor.bounding_box() @@ -311,14 +350,47 @@ def main(): 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" + # Pointer down MUST NOT shrink the original SVG or bezel. + trigger=editor.locator("#vtThrow") + outer=trigger.evaluate("""el=>{ + const r=el.getBoundingClientRect(); + return {x:r.x,y:r.y,width:r.width,height:r.height, + filter:getComputedStyle(el).filter, + ring:getComputedStyle(el.querySelector('.vt-throw-aura')).boxShadow}; + }""") + tb=trigger.bounding_box();assert tb + page.mouse.move(tb["x"]+tb["width"]/2,tb["y"]+tb["height"]/2) + page.mouse.down() + page.wait_for_timeout(160) # let the 140ms purple ring transition settle + pressed=trigger.evaluate("""el=>{ + const r=el.getBoundingClientRect(); + return {x:r.x,y:r.y,width:r.width,height:r.height, + filter:getComputedStyle(el).filter, + ring:getComputedStyle(el.querySelector('.vt-throw-aura')).boxShadow, + cap:getComputedStyle(el,'::after').transform}; + }""") + for axis in ("x","y","width","height"): + assert abs(pressed[axis]-outer[axis])<.01,(axis,outer,pressed) + assert pressed["filter"]==outer["filter"] + assert pressed["ring"]!=outer["ring"] + assert pressed["cap"]!="none" + page.mouse.up() # real pointer click -> actual native request + assert trigger.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) + reply_snapshot(page,state,{**DEFAULTS,"mode":0,"wet":rotary["settings"]["wet"]}, + count=0,tail=False,armed=True) + assert editor.locator("#vtThrow").get_attribute("data-armed")=="true" + assert editor.locator("#vtStatus").inner_text()=="ARMED" + last_snap=last(page,"nativeThrowSnapshot")["requestId"] + page.wait_for_function("""old=>window.__actions.filter( + x=>x.action==='nativeThrowSnapshot').at(-1)?.requestId!==old""", + arg=last_snap,timeout=4000) + reply_snapshot(page,state,{**DEFAULTS,"mode":0,"wet":rotary["settings"]["wet"]}, + count=1,tail=True,armed=False) assert editor.locator("#vtCount").inner_text()=="1" assert editor.locator("#vtStatus").inner_text()=="TAIL" assert editor.locator("#vtThrow").get_attribute("data-tail")=="true" diff --git a/tests/builtin_vocal_throw_test.cpp b/tests/builtin_vocal_throw_test.cpp index 30f125715..fd16482c2 100644 --- a/tests/builtin_vocal_throw_test.cpp +++ b/tests/builtin_vocal_throw_test.cpp @@ -88,7 +88,9 @@ static void manualAndDry(double rate) { noHeap.store(true); const bool fired=fx.throwNow(); noHeap.store(false); - check(fired&&fx.throwCount()==1); + check(fired&&fx.cueArmed()&&fx.throwCount()==0); + run(fx,0,0,static_cast(rate*.23),peakL,peakR); + check(fx.throwCount()==1&&!fx.cueArmed()); peakL=peakR=0; run(fx,0,0,static_cast(rate*.10),peakL,peakR); check(peakL==0&&peakR==0); // beat-scheduled, no immediate echo smear @@ -99,7 +101,9 @@ static void manualAndDry(double rate) { noHeap.store(true); const bool staleCue=fx.throwNow(); noHeap.store(false); - check(!staleCue); // 700ms after last vocal: never report an empty throw + check(staleCue&&fx.cueArmed()); // arm for future, never replay old word + run(fx,0,0,static_cast(rate*4.1),peakL,peakR); + check(!fx.cueArmed()&&fx.throwCount()==1); } static void automaticAndHybrid(double rate) { VocalThrow fx;check(fx.prepare(rate)); @@ -148,13 +152,13 @@ static void twoTailsStayLive(double rate) { run(overlap,input,input*.5f,frames,l,r); }; both(.5f,static_cast(rate*.20)); - both(0.f,static_cast(rate*.10)); + both(0.f,static_cast(rate*.20)); 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)); + both(0.f,static_cast(rate*.20)); noHeap.store(true); const bool second=overlap.throwNow(); const bool saturated=overlap.throwNow(); @@ -177,7 +181,8 @@ static void twoTailsStayLive(double rate) { for(std::size_t i=0;i.001f&&maxOverlap>.001f); @@ -203,7 +208,9 @@ static void autoThenManualMustNotDoubleEcho() { noHeap.store(true); const bool newPhrase=fx.throwNow(); noHeap.store(false); - check(newPhrase&&fx.throwCount()==2); + check(newPhrase&&fx.cueArmed()&&fx.throwCount()==1); + run(fx,0.f,0.f,14400,l,r); + check(!fx.cueArmed()&&fx.throwCount()==2); } static void denseRepeatsStayBounded() { VocalThrow fx;check(fx.prepare(48000)); @@ -236,9 +243,9 @@ static void manualOverrideSuppressesAuto() { noHeap.store(true); const bool fired=fx.throwNow(); noHeap.store(false); - check(fired&&fx.throwCount()==1); + check(fired&&fx.cueArmed()&&fx.throwCount()==0); run(fx,0.f,0.f,12000,l,r); - check(fx.throwCount()==1); // same phrase must not double-fire + check(!fx.cueArmed()&&fx.throwCount()==1); // manual fires on END 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 @@ -268,20 +275,20 @@ static void musicTempoChangesOnlyFutureTail() { 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); + check(firedMusic&&firedManual&&music.cueArmed()&&manual.cueArmed()); + run(music,0.f,0.f,12000,a,b); // complete sung phrase, then freeze + run(manual,0.f,0.f,12000,a,b); + check(!music.cueArmed()&&!manual.cueArmed()); + music.setMusicIntervalSamples(0); // must NOT re-time the frozen echo 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 + run(music,0.f,0.f,6000,a,b); check(a>.01f&&b>.01f); a=b=0.f; - run(manual,0.f,0.f,17760,a,b); // manual .5s must still be silent + run(manual,0.f,0.f,6000,a,b); check(a==0.f&&b==0.f); a=b=0.f; - run(manual,0.f,0.f,7680,a,b); + run(manual,0.f,0.f,9000,a,b); check(a>.01f&&b>.01f); } // M3 beat-phase regression. Vocal PCM remains zero-latency dry, while the @@ -299,11 +306,10 @@ static void nativeMusicBeatGridQuantization(int quantum) { 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); + run(gridded,0.f,0.f,14400,l,r); + run(unquantized,0.f,0.f,14400,l,r); + // Completed phrase and a 180 BPM beat anchor at global 15000. + gridded.setMusicBeatGrid(16000,15000,26400,true); noHeap.store(true,std::memory_order_release); const auto snapped=gridded.throwNow(); const auto plain=unquantized.throwNow(); @@ -327,16 +333,80 @@ static void nativeMusicBeatGridQuantization(int quantum) { } return -1; }; - // First native music grid point >= intended onset: frame 32100. - // Cue at graph frame 15000 => first wet sample around offset 17100. + // Compare relative onset, not a hardcoded physical silence-end frame. + // M15 intentionally tracks the complete sung word with envelope release + // and hysteresis: the final voiced sample may be later than M3's gate. + // Both processors received the IDENTICAL dry PCM, so their endpoint, + // frozen copy budget and fade are shared. Only accepted interval and + // bounded beat-lattice phase correction may differ. 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=0&&fallback>=0); + const int delta=fallback-quantized; + // Grid correction can postpone an echo by at most a quarter of one + // 180 BPM beat, never a surprise extra full beat. The 120 BPM fallback + // keeps its longer interval regardless of later source invalidation. + check(delta>=manualInterval-musicInterval-maxPhaseCorrection); + check(delta<=manualInterval-musicInterval); + check(quantizedquantized); +} + +static void smartCueStereoAndCancellation() { + constexpr double rate=48000.; + VocalThrow fx;check(fx.prepare(rate)); + auto s=fx.settingsForTests(); + s.mode=0;s.bpm=120;s.division=1;s.repeats=4;s.captureMs=120; + s.silenceMs=100;s.wet=1.f;s.ducking=0.f;s.decay=.8f; + check(fx.resetUnpublished(s)); + float peakL=0.f,peakR=0.f; + run(fx,.5f,.5f,9600,peakL,peakR); + check(fx.throwNow()&&fx.cueArmed()&&fx.throwCount()==0); + run(fx,0.f,0.f,8640,peakL,peakR); + check(!fx.cueArmed()&&fx.throwCount()==1); + std::array energyL{},energyR{}; + std::array left{},right{}; + for(int begin=0;begin<57600;begin+=64) { + left.fill(0.f);right.fill(0.f); + noHeap.store(true,std::memory_order_release); + fx.processStereo(left.data(),right.data(),64); + noHeap.store(false,std::memory_order_release); + for(int i=0;i<64;++i) { + const double elapsed=(18240+begin+i)/rate; + for(int tap=0;tap<4;++tap) { + const double first=.45+.25*tap; + if(elapsed>=first+.018&&elapsedenergyR[0]*1.8); + check(energyR[1]>energyL[1]*1.8); + check(energyL[2]>energyR[2]*1.8); + check(energyR[3]>energyL[3]*1.8); + VocalThrow c;check(c.prepare(rate)&&c.resetUnpublished(s)); + check(c.throwNow()&&c.cueArmed()); // before vocal + check(c.throwNow()&&!c.cueArmed()); // explicit performer cancel + run(c,.5f,.5f,9600,peakL,peakR); + run(c,0.f,0.f,24000,peakL,peakR); + check(c.throwCount()==0); + c.invalidateCaptureHistory(); + check(c.throwNow()&&c.cueArmed()); + run(c,0.f,0.f,static_cast(rate*4.1),peakL,peakR); + check(!c.cueArmed()&&c.throwCount()==0); // bounded expiry + check(c.throwNow()&&c.cueArmed()); + run(c,.5f,.5f,9600,peakL,peakR); + run(c,0.f,0.f,24000,peakL,peakR); + check(!c.cueArmed()&&c.throwCount()==1); } int main() { validation(); + smartCueStereoAndCancellation(); manualAndDry(8000); manualAndDry(44100); manualAndDry(48000); diff --git a/tests/native_vocal_throw_cancel_test.cpp b/tests/native_vocal_throw_cancel_test.cpp index 0caf3b745..f1d3ac638 100644 --- a/tests/native_vocal_throw_cancel_test.cpp +++ b/tests/native_vocal_throw_cancel_test.cpp @@ -195,16 +195,13 @@ static void testBypassNeverReplaysOldVocalCue() { p.onRealtimeBypass(false,false); check(p.queueTrigger(505)); render(p,b,midi,0.f); - check(p.pollCompletion(done)&&done.requestId==505&&!done.applied&& + 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. + check(p.observedThrowCount()==0&&p.observedCueArmed()); + // The old phrase is invalid. This cue is for a NEW sung phrase only. 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); + for(int n=0;n<130;++n)render(p,b,midi,0.f); + check(p.observedThrowCount()==1&&!p.observedCueArmed()); check(p.stateSnapshotQuiescent()); } @@ -249,7 +246,9 @@ int main(){ 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.observedThrowCount()==0&&p.observedCueArmed()); + for(int n=0;n<140;++n)render(p,b,m,0.f); + check(p.observedThrowCount()==1&&!p.observedCueArmed()); check(p.stateSnapshotQuiescent()); std::puts("PASS: expired Vocal Throw cue and settings cannot replay on ASIO resume"); }